#!/usr/bin/env python3
import json
import re
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
SPECS = [
    ("narration", PROJECT / "story/spoken-narration.txt", PROJECT / "log/tts-pronunciation.json"),
    ("intro", PROJECT / "audio/intro-voice-source.txt", PROJECT / "log/intro-tts-pronunciation.json"),
]
KNOWN = ("Facebook", "YouTube", "audio", "video", "radio", "vali")


def rx(token):
    return re.compile(r"(?<![0-9A-Za-zÀ-ỹĐđ])" + re.escape(token) + r"(?![0-9A-Za-zÀ-ỹĐđ])", re.IGNORECASE)


def main():
    rows = []
    verified = True
    for kind, source_path, receipt_path in SPECS:
        if not source_path.is_file() or not receipt_path.is_file():
            raise RuntimeError(f"missing pronunciation source/receipt for {kind}")
        source = source_path.read_text(encoding="utf-8")
        receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
        by_token = {row["source"].casefold(): row for row in receipt.get("lexicon", [])}
        counts = {}
        for token in KNOWN:
            source_count = len(rx(token).findall(source))
            row = by_token.get(token.casefold(), {})
            replacement_count = row.get("replacement_count")
            ok = replacement_count == source_count
            counts[token] = {"source_count": source_count, "replacement_count": replacement_count, "verified": ok}
            verified = verified and ok
        verified = verified and receipt.get("verified") is True and not receipt.get("unresolved_required")
        rows.append({"kind": kind, "source": str(source_path.relative_to(PROJECT)), "counts": counts})
    print(json.dumps({"verified": verified, "sources": rows}, ensure_ascii=False))
    return 0 if verified else 1


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as exc:
        print(f"Pronunciation audit blocked: {exc}", file=sys.stderr)
        sys.exit(1)
