"""Build the pronunciation table of a study pack from an ipa-dict word list.

Usage: build-index.py <en_US|de|sv> <ipa-dict list.txt> <study pack dir> [--only-missing]

The table `ipa/<shard>.tsv` holds `word <TAB> [ipa] · [ipa]` for every single-word entry of the list.
With --only-missing it keeps just the words that the pack's forms table lists without a pronunciation,
so the list only fills the gaps of the forms table and stays a separate file with its own licence.
The pack format is described in ../language-packs/README.md.
"""
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "language-packs"))
import packlib  # noqa: E402

SOURCES = {
    "en_US": {
        "language": "en",
        "name": "ipa-dict en_US (cmudict-ipa, from the CMU Pronouncing Dictionary)",
        "url": "https://github.com/open-dict-data/ipa-dict/blob/master/data/en_US.txt",
        "licence": "MIT (ipa-dict, cmudict-ipa) and the CMUdict licence",
        "snapshot": "",
    },
    "de": {
        "language": "de",
        "name": "ipa-dict de (german-ipa-dict by devio-at, extracted from Wiktionary)",
        "url": "https://github.com/open-dict-data/ipa-dict/blob/master/data/de.txt",
        "licence": "CC BY-SA (Wiktionary; the source does not state a version)",
        "snapshot": "2026-11-19",
    },
    "sv": {
        "language": "sv",
        "name": "ipa-dict sv (Folkets lexikon)",
        "url": "https://github.com/open-dict-data/ipa-dict/blob/master/data/sv.txt",
        "licence": "CC BY-SA 2.5 (Folkets lexikon)",
        "snapshot": "2026-11-24",
    },
}


def pronunciations(source):
    entries = {}
    for line in Path(source).read_text(encoding="utf-8").splitlines():
        word, separator, raw = line.partition("\t")
        key = packlib.normalize(word)
        if not separator or not packlib.is_single_word(key) or key in entries:
            continue
        variants = [f"[{ipa}]" for ipa in re.findall(r"/([^/]+)/", raw)]
        if variants:
            entries[key] = [" · ".join(variants)]
    return entries


def forms_without_pronunciation(pack_dir):
    return {form for form, fields in packlib.read_table(pack_dir, "forms").items()
            if not (fields and fields[0])}


def main(name, source, pack_dir, *flags):
    entries = pronunciations(source)
    if "--only-missing" in flags:
        wanted = forms_without_pronunciation(pack_dir)
        entries = {key: value for key, value in entries.items() if key in wanted}
    details = SOURCES[name]
    rows = packlib.write_table(pack_dir, "ipa", entries)
    source_note = {key: details[key] for key in ("name", "url", "licence", "snapshot")}
    packlib.update_manifest(pack_dir, "study", details["language"], "ipa", rows, source_note)
    print(f"{details['language']}: {rows:,} pronunciations.")


if __name__ == "__main__":
    main(*sys.argv[1:])
