#!/usr/bin/env python3
"""Build a small, reproducible FLEURS sample for murmela-bench.

FLEURS (Google, CC BY 4.0): https://huggingface.co/datasets/google/fleurs
Download per language: data/<lang>/test.tsv and data/<lang>/audio/test.tar.gz.

    python3 -I prepare_fleurs.py <download dir> <out dir> [--per-lang 50] [--seed 2026]

<download dir>/<lang>/test.tsv and test.tar.gz for lang in en_us, de_de, fr_fr.
Writes <out dir>/audio/<xx>-fleurs-<sentence id>.wav and <out dir>/references.json
({clip stem: raw transcription}). One recording per sentence, sentences picked with a fixed seed,
so anyone with the same files gets the same sample.

Then:
    npm run bench -- corpus import <out dir>/audio --corpus _private/asr-corpus-fleurs
    python3 -I apply_references.py _private/asr-corpus-fleurs <out dir>/references.json
"""
import argparse
import csv
import json
import random
import sys
import tarfile
from pathlib import Path

LANGS = {"en_us": "en", "de_de": "de", "fr_fr": "fr"}


def rows(tsv: Path):
    # FLEURS tsv has no header: id, file name, raw transcription, normalised transcription, characters,
    # number of samples, gender.
    with tsv.open(encoding="utf-8", newline="") as f:
        for r in csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
            if len(r) >= 3:
                yield {"sentence": r[0], "file": r[1], "raw": r[2].strip()}


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("download", type=Path)
    ap.add_argument("out", type=Path)
    ap.add_argument("--per-lang", type=int, default=50)
    ap.add_argument("--seed", type=int, default=2026)
    a = ap.parse_args()

    audio_out = a.out / "audio"
    audio_out.mkdir(parents=True, exist_ok=True)
    references = {}
    for folder, code in LANGS.items():
        by_sentence = {}
        for r in rows(a.download / folder / "test.tsv"):
            # First recording (by file name) of each sentence.
            if r["sentence"] not in by_sentence or r["file"] < by_sentence[r["sentence"]]["file"]:
                by_sentence[r["sentence"]] = r
        sentences = sorted(by_sentence, key=int)
        random.Random(f"{a.seed}-{code}").shuffle(sentences)
        picked = {by_sentence[s]["file"]: by_sentence[s] for s in sentences[: a.per_lang]}

        found = 0
        with tarfile.open(a.download / folder / "test.tar.gz", "r:gz") as tar:
            for member in tar:
                name = Path(member.name).name
                if not member.isfile() or name not in picked:
                    continue
                row = picked[name]
                stem = f"{code}-fleurs-{int(row['sentence']):04d}"
                data = tar.extractfile(member).read()  # read bytes only; nothing from the archive is executed
                (audio_out / f"{stem}.wav").write_bytes(data)
                references[stem] = row["raw"]
                found += 1
        print(f"{code}: {found} of {len(picked)} clips", file=sys.stderr)

    (a.out / "references.json").write_text(json.dumps(references, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    print(f"{len(references)} clips in {audio_out}", file=sys.stderr)
    return 0


if __name__ == "__main__":
    sys.exit(main())
