"""Download the MT-Bench expert votes and question file, check them, and write the small derived tables.

Usage: python3 -I -B tools/get_data.py <new empty dir for the raw files>
Writes, beside this study: data/votes-turn1.csv, data/answers-turn1.csv, data/questions.csv.
Needs pyarrow to read the parquet file.
"""
import csv
import hashlib
import json
import sys
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SOURCES = json.loads((ROOT / "data" / "sources.json").read_text(encoding="utf-8"))
SHORT = "alp"


def model_id(name):
    """Each model id as the dataset writes it, except the one id that starts with SHORT, which is written alp-13b.
    The short id sorts in the same place as the full one, so the samples and every result are the same either way."""
    if name.startswith(SHORT):
        assert name.endswith("-13b"), name
        return SHORT + "-13b"
    return name


def fetch(raw_dir):
    raw_dir.mkdir(parents=True, exist_ok=True)
    paths = {}
    for s in SOURCES["files"]:
        p = raw_dir / s["name"]
        if not p.exists():
            with urllib.request.urlopen(s["url"], timeout=120) as r:
                p.write_bytes(r.read())
        h = hashlib.sha256(p.read_bytes()).hexdigest()
        assert h == s["sha256"], f"{s['name']}: sha256 {h} does not match data/sources.json"
        paths[s["key"]] = p
    return paths


def load(paths):
    """Return (questions, votes, answers) for turn 1 only."""
    import pyarrow.parquet as pq
    questions = {}
    for line in paths["questions"].read_text(encoding="utf-8").splitlines():
        q = json.loads(line)
        questions[q["question_id"]] = {"category": q["category"], "text": q["turns"][0]}
    votes, answers = [], {}
    for r in pq.read_table(paths["votes"]).to_pylist():
        if r["turn"] != 1:
            continue
        votes.append({"question_id": r["question_id"], "model_a": model_id(r["model_a"]),
                      "model_b": model_id(r["model_b"]),
                      "winner": r["winner"], "rater": r["judge"]})
        for side in ("a", "b"):
            conv = r["conversation_" + side]
            assert conv[0]["role"] == "user" and conv[1]["role"] == "assistant"
            key = (r["question_id"], model_id(r["model_" + side]))
            text = conv[1]["content"]
            assert answers.get(key, text) == text, f"two different answer texts for {key}"
            answers[key] = text
    return questions, votes, answers


def main():
    paths = fetch(Path(sys.argv[1]))
    questions, votes, answers = load(paths)
    out = ROOT / "data"
    with open(out / "votes-turn1.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=["question_id", "model_a", "model_b", "winner", "rater"], lineterminator="\n")
        w.writeheader()
        w.writerows(votes)
    with open(out / "answers-turn1.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(["question_id", "model", "chars", "words", "sha256"])
        for (qid, model), text in sorted(answers.items()):
            w.writerow([qid, model, len(text), len(text.split()), hashlib.sha256(text.encode("utf-8")).hexdigest()])
    with open(out / "questions.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(["question_id", "category"])
        for qid in sorted(questions):
            w.writerow([qid, questions[qid]["category"]])
    print(f"votes {len(votes)}, answers {len(answers)}, questions {len(questions)}")


if __name__ == "__main__":
    main()
