#!/usr/bin/env python3
"""Put the FLEURS reference transcriptions into a murmela-bench corpus manifest and mark them verified.

    python3 -I apply_references.py <corpus dir> <references.json>

FLEURS references were written by the dataset's authors, so they count as verified. Clips are tagged "fleurs".
"""
import json
import sys
from pathlib import Path


def main() -> int:
    corpus, refs_path = Path(sys.argv[1]), Path(sys.argv[2])
    refs = json.loads(refs_path.read_text(encoding="utf-8"))
    manifest_path = corpus / "manifest.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    updated = 0
    for clip in manifest["clips"]:
        stem = Path(clip.get("original") or clip["audio"]).stem
        ref = refs.get(stem) or refs.get(clip["id"])
        if ref is None:
            continue
        clip["reference"] = ref
        clip["referenceStatus"] = "verified"
        clip["referenceDraftedBy"] = ["fleurs"]
        clip["tags"] = sorted(set(clip.get("tags", [])) | {"fleurs"})
        clip["notes"] = "FLEURS test set (Google, CC BY 4.0); reference = raw transcription."
        updated += 1
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"{updated} of {len(manifest['clips'])} clips updated", file=sys.stderr)
    return 0 if updated else 1


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