"""Turn the Parlez 3 / Parlez 5 dialogues into app data for Level 4 (Mission Dialogues).
Inputs : Book/L4/parlez_data.json (tools/parlez_extract.py) + Book/L4/parlez_review.json (checked answers, Arabic).
Outputs: curriculum/level4/dial_data.py and the recordings used, copied to static/audio/l4/<book>/.
    python tools/build_dialogues.py"""
import os, re, json, shutil, pprint, unicodedata
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
L4 = os.path.join(ROOT, "Book", "L4")
SRC = "D:/OneDrive - DolfTech/SABIS-EBooks/EBooks/French"
DST = os.path.join(ROOT, "static", "audio", "l4")


def key(title):
    title = pretty(title)
    t = unicodedata.normalize("NFD", title.lower().replace("’", "'"))
    t = "".join(c for c in t if unicodedata.category(c) != "Mn")
    return re.sub(r"[^a-z0-9]+", " ", t).strip()


def res_dir(slug):
    for d in os.listdir(SRC):
        if unicodedata.normalize("NFC", d).strip().endswith("parlez " + slug[-1]):
            return os.path.join(SRC, d, "resources")


FIX = {"l'alimentation sainte": "l'alimentation saine", "au zoo": "au zoo (1)"}


def pretty(title):
    t = title.strip().strip("*").strip().lower().replace("’", "'")
    t = FIX.get(t, t)
    return t[:1].upper() + t[1:]


def main():
    data = json.load(open(os.path.join(L4, "parlez_data.json"), encoding="utf-8"))
    rev = json.load(open(os.path.join(L4, "parlez_review.json"), encoding="utf-8"))
    themes = {}
    for slug in ("parlez5", "parlez3"):           # Parlez 5 sets the order of the themes
        src = res_dir(slug)
        os.makedirs(os.path.join(DST, slug), exist_ok=True)
        for d in data[slug]:
            r = rev.get(slug, {}).get(str(d["n"]), {})
            ar = r.get("ar") or [""] * len(d["fr"])
            if len(ar) != len(d["fr"]):
                ar = [""] * len(d["fr"])
            lines = []
            for k, fr in enumerate(d["fr"]):
                a = d["audio"][k]
                if a:
                    shutil.copyfile(os.path.join(src, a), os.path.join(DST, slug, a))
                lines.append(dict(fr=fr, en=d["en"][k] if k < len(d["en"]) else "", ar=ar[k], who=d["speaker"][k],
                                  audio=f"l4/{slug}/{a}" if a else None))
            qs = []
            for q in r.get("questions", []):
                if not q.get("keep") or q["i"] >= len(d["questions"]):
                    continue
                src_q = d["questions"][q["i"]]
                opts = q.get("opts") or src_q["opts"]
                k = ord(q["answer"]) - 97
                if 0 <= k < len(opts) and len(set(opts)) == len(opts):
                    qs.append(dict(q=q.get("q") or src_q["q"], opts=opts, answer=opts[k]))
            t = themes.setdefault(key(d["title"]), dict(title=pretty(d["title"]), title_ar=r.get("title_ar", ""), books={}))
            if not t["title_ar"]:
                t["title_ar"] = r.get("title_ar", "")
            t["books"][slug] = dict(n=d["n"], lines=lines, questions=qs)
    out = list(themes.values())
    with open(os.path.join(ROOT, "curriculum", "level4", "dial_data.py"), "w", encoding="utf-8") as f:
        f.write('# -*- coding: utf-8 -*-\n"""Dialogues of « À vos marques, prêts… parlez ! » 3 and 5 — generated by tools/build_dialogues.py, do not edit by hand."""\n')
        f.write("THEMES = " + pprint.pformat(out, width=160, sort_dicts=False) + "\n")
    n_audio = sum(1 for t in out for b in t["books"].values() for l in b["lines"] if l["audio"])
    print(len(out), "themes;", sum(len(b["questions"]) for t in out for b in t["books"].values()), "questions;", n_audio, "recordings copied")


if __name__ == "__main__":
    main()
