"""Emit a per-turn CSV of the text content of the trimmed long_*.mp3 set.

For each scenario in SET_LIST, looks up which turns survived the 15s cap
(per concat_report.json from audio_preview_monologue_trim) and joins them
with the original turn text from the emotion seed jsonls.

Output: one row per kept turn + one summary row per set (joined text +
concat duration + dropped-turn note).
"""
from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path

TRIM_DIR = Path(
    "/dataset/kemix-engine/package/face/animasync-face-v3/data/audio_preview_monologue_trim"
)
REPORT = TRIM_DIR / "concat_report.json"
EMO_DIR = Path(
    "/dataset/kemix-engine/package/face/animasync-face-v3/data/emotion"
)
SEED_PRIORITY = [
    "seed_scenarios_final.jsonl",
    "seed_train_final.jsonl",
    "seed_train.jsonl",
    "seed_val.jsonl",
    "seed_test.jsonl",
    "seed_generated.jsonl",
    "seed_augmented.jsonl",
]

SET_LIST = [
    "long_001", "long_002", "long_003", "long_004", "long_005",
    "long_006", "long_007", "long_008", "long_009", "long_010",
    "long_011", "long_055_p1", "long_048", "long_042", "long_102_p1",
    "long_055", "long_gen_028", "long_012", "long_055_p0", "long_081",
    "long_049", "long_gen_026", "long_063", "long_032", "long_108_p1",
    "long_102_p0", "long_gen_050", "long_078", "long_013", "long_014",
    "long_001_p0", "long_002_p0", "long_018_p1", "long_116_p0", "long_111",
    "long_074", "long_003_p0", "long_108", "long_116_p1", "long_002_p1",
    "long_gen_025", "long_106_p1", "long_060", "long_065_p1", "long_050_p1",
    "long_087", "long_041_p1", "long_107_p1", "long_065", "long_050_p0",
    "long_066", "long_gen_042", "long_gen_035_p0", "long_024_p1", "long_084",
    "long_003_p1", "long_041", "long_041_p0", "long_gen_056", "long_001_p1",
]


def load_scenarios() -> dict[str, dict]:
    out: dict[str, dict] = {}
    for fn in SEED_PRIORITY:
        p = EMO_DIR / fn
        if not p.exists():
            continue
        with p.open() as f:
            for line in f:
                try:
                    obj = json.loads(line)
                except json.JSONDecodeError:
                    continue
                sid = obj.get("scenario_id")
                if sid and sid not in out:
                    obj["_source_file"] = fn
                    out[sid] = obj
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", type=Path, default=Path("/tmp/trimmed_transcripts.csv"))
    args = ap.parse_args()

    report = json.loads(REPORT.read_text())
    scenarios = load_scenarios()

    args.out.parent.mkdir(parents=True, exist_ok=True)
    with args.out.open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow([
            "set_no", "filename", "scenario_id", "row_type",
            "turn_idx", "emotion", "duration_s", "speaker",
            "text", "source_jsonl", "dropped_note",
        ])

        for set_no, sid in enumerate(SET_LIST, start=1):
            filename = f"{sid}.mp3"
            entry = report.get(sid)
            scenario = scenarios.get(sid)

            if entry is None:
                w.writerow([set_no, filename, sid, "summary", "", "", "", "",
                            "MISSING from concat_report.json", "", ""])
                continue
            if scenario is None:
                w.writerow([set_no, filename, sid, "summary", "", "", "", "",
                            "MISSING from seed jsonls", "", ""])
                continue

            turns = scenario.get("turns", [])
            src = scenario.get("_source_file", "")
            kept = entry.get("kept", [])
            dropped = entry.get("dropped", [])

            kept_texts: list[str] = []
            for k in kept:
                ti = k["turn_idx"]
                dur = k.get("duration", "")
                if ti < len(turns):
                    t = turns[ti]
                    txt = t.get("text", "")
                    emo = t.get("emotion", "")
                    spk = t.get("speaker", "")
                else:
                    txt = "<turn_idx out of range>"
                    emo = ""
                    spk = ""
                kept_texts.append(txt)
                w.writerow([set_no, filename, sid, "turn", ti, emo, dur, spk,
                            txt, src, ""])

            dropped_note = ""
            if dropped:
                parts = []
                for d in dropped:
                    di = d["turn_idx"]
                    dtxt = turns[di].get("text", "") if di < len(turns) else "?"
                    parts.append(f"t{di} ({d.get('duration','?')}s) -> {dtxt}")
                dropped_note = "; ".join(parts)

            w.writerow([
                set_no, filename, sid, "summary", "", "",
                entry.get("concat_duration", ""), "",
                " ".join(kept_texts),
                src,
                dropped_note,
            ])

    print(f"Wrote {args.out}")


if __name__ == "__main__":
    main()
