"""Build a meaning pack (headword -> meanings) from a WikDict bilingual database.

Usage:
  build-meaning-pack.py <wikdict.sqlite3[.xz]> <study> <meaning> <meaning pack dir>
                        [--snapshot YYYY-MM-DD] [--irregular <irregular.txt> <study pack dir>]
                        [--supplement <table.tsv> <name> <url> <snapshot>] [--curated <curated.json>]
                        [--replace <replace.json>]

Example (English with Czech meanings, plus the hand-written list of irregular English forms):
  build-meaning-pack.py wikdict-en-cs-2026-06-23.sqlite3.xz en cs \
      ../../shared/src/commonMain/composeResources/files/packs/en-cs \
      --snapshot 2026-06-23 --irregular irregular-en.txt \
      ../../shared/src/commonMain/composeResources/files/packs/en

The same script serves every WikDict pair (de-cs, de-en, ...); nothing in it is specific to a
language. Every meaning of the source and of a supplement is cleaned (packlib.clean_meaning: wiki
markup, HTML entities, mojibake). The output format is described in ../language-packs/README.md.

--supplement adds headwords the WikDict pair lacks from a table written by another converter
(../kaikki/build-meaning-supplement.py, meanings from other Wiktionary editions); a headword WikDict
has keeps WikDict's meanings only.

--curated puts the hand-written meanings of a list (../language-packs/curated/cs-xx.json) before the
source's meanings of the same headword. The app shows a form's own curated meanings first, but a form
reaches its dictionary form's meanings through this table only, so a curated dictionary form (rád,
celý) leads for all its forms (ráda, celou) only when its row starts with the curated meanings.

--replace takes a hand-written list in the same format whose rows replace the source's row of a headword
(an empty list removes the row). It hides a source meaning that is wrong (nl water: objevit se), which
--curated cannot do, because curated meanings come before the source's meanings, not instead of them.
"""
import argparse
import collections
import json
import lzma
import sqlite3
import sys
import tempfile
import unicodedata
from pathlib import Path

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

MAX_MEANINGS = 12
SECTIONS = {"[base-first]": "baseFirst", "[own-first]": "ownFirst"}
OWN_ENTRY = "[own-entry]"
LICENCE = "CC BY-SA 4.0"


def translation_rows(source_path):
    """Rows (written_rep, trans_list, score) of the database, which may be compressed with xz."""
    source = Path(source_path)
    with tempfile.NamedTemporaryFile(suffix=".sqlite3") as database:
        if source.suffix == ".xz":
            with lzma.open(source) as archive:
                database.write(archive.read())
            database.flush()
            source = Path(database.name)
        connection = sqlite3.connect(f"file:{source}?mode=ro", uri=True)
        try:
            return connection.execute(
                "SELECT written_rep, trans_list, score FROM translation "
                "WHERE written_rep IS NOT NULL AND trans_list IS NOT NULL"
            ).fetchall()
        finally:
            connection.close()


def meanings_by_word(rows):
    """Orders meanings by WikDict's score, entries written like the lookup key before capitalised ones."""
    scored = collections.defaultdict(list)
    for position, (written, translations, score) in enumerate(rows):
        word = packlib.normalize(written)
        if not packlib.is_single_word(word):
            continue
        different_case = unicodedata.normalize("NFC", written.strip()) != word
        scored[word].append((different_case, -(score or 0), position, translations))
    index = {}
    for word, candidates in scored.items():
        confident = [candidate for candidate in candidates if candidate[1] < 0]
        meanings = []
        for _, _, _, translations in sorted(confident or candidates):
            for meaning in translations.split(" | "):
                meaning = packlib.clean_meaning(meaning)
                if meaning and meaning not in meanings:
                    meanings.append(meaning)
        if meanings:
            index[word] = meanings[:MAX_MEANINGS]
    return index


def read_supplement(path):
    """Rows key<TAB>meaning... of a supplement table."""
    rows = {}
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        key, *meanings = line.split("\t")
        meanings = packlib.clean_meanings(meanings)
        if meanings:
            rows[key] = meanings[:MAX_MEANINGS]
    return rows


def with_supplement(index, supplement):
    """WikDict's index plus the supplement's headwords that WikDict does not have."""
    added = {key: meanings for key, meanings in supplement.items() if key not in index}
    return {**index, **added}, len(added)


def with_curated(index, curated):
    """The index with the curated meanings of every single-word headword before the source's ones.

    Hand-written meanings are not cleaned; a damaged one (wiki markup, entity, mojibake) stops the build.
    Returns the rows and the number of curated headwords written.
    """
    packlib.check_curated(curated)
    rows = dict(index)
    led = 0
    for word, meanings in curated.items():
        key = packlib.normalize(word)
        if not packlib.is_single_word(key):
            continue
        first = [packlib.clean_field(meaning) for meaning in meanings if packlib.clean_field(meaning)]
        rows[key] = list(dict.fromkeys(first + rows.get(key, [])))[:MAX_MEANINGS]
        led += 1
    return rows, led


def with_replaced(index, replaced):
    """The index with the rows of a replacement list instead of the source's rows of the same headwords.

    An empty list removes the headword. Only headwords the index has are replaced. Returns the rows and
    the number of headwords replaced or removed.
    """
    rows = dict(index)
    count = 0
    for word, meanings in replaced.items():
        key = packlib.normalize(word)
        if key not in rows:
            continue
        kept = list(dict.fromkeys(packlib.clean_field(m) for m in meanings if packlib.clean_field(m)))
        if kept:
            rows[key] = kept[:MAX_MEANINGS]
        else:
            del rows[key]
        count += 1
    return rows, count


def irregular_forms(path):
    forms = {name: collections.defaultdict(list) for name in SECTIONS.values()}
    section = None
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        line = line.split("#")[0].strip()
        if not line:
            continue
        if line in SECTIONS:
            section = SECTIONS[line]
            continue
        if line == OWN_ENTRY:
            section = None
            continue
        if section is None:
            continue
        headword, listed = line.split(":")
        for form in listed.split():
            if headword.strip() not in forms[section][form]:
                forms[section][form].append(headword.strip())
    # A form may be listed in both sections; its own entry then leads and every headword is kept.
    for form in set(forms["baseFirst"]) & set(forms["ownFirst"]):
        merged = forms["baseFirst"].pop(form)
        merged += [word for word in forms["ownFirst"][form] if word not in merged]
        forms["ownFirst"][form] = merged
    return forms


def own_entry_words(path):
    """Words of the [own-entry] section: plurals whose own entry translates them (goods, means)."""
    words, inside = set(), False
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        line = line.split("#")[0].strip()
        if line.startswith("["):
            inside = line == OWN_ENTRY
        elif inside and line:
            words.update(line.split())
    return words


def plural_bases(key):
    """Singular forms a regular English plural may come from, as the app's wordCandidates tries them."""
    bases = []
    if key.endswith("ies"):
        bases.append(key[:-3] + "y")
    if key.endswith("s") and not key.endswith("ss"):
        bases.append(key[:-1])
    if key.endswith("es"):
        bases.append(key[:-2])
    return bases


def regular_plurals(index, forms, keep_own):
    """Regular plurals whose own entry shares no meaning with their singular ("years": a rare sense).

    The app shows the singular's meanings first and the plural's own entry after them. Words ending
    in -ics (physics) and the words of [own-entry] keep their own entry first.
    """
    known = set(forms["baseFirst"]) | set(forms["ownFirst"]) | set(keep_own)
    plurals = {}
    for key, meanings in index.items():
        if len(key) < 4 or key in known or key.endswith("ics"):
            continue
        base = next((candidate for candidate in plural_bases(key) if candidate in index), None)
        if base is not None and not set(meanings) & set(index[base]):
            plurals[key] = [base]
    return plurals


def write_irregular(index, irregular_path, study_pack_dir):
    forms = irregular_forms(irregular_path)
    forms["baseThenOwn"] = regular_plurals(index, forms, own_entry_words(irregular_path))
    missing = sorted({headword for section in forms.values() for headwords in section.values()
                      for headword in headwords if headword not in index})
    if missing:
        raise SystemExit(f"Irregular forms point to headwords without an entry: {', '.join(missing)}")
    target = Path(study_pack_dir)
    target.mkdir(parents=True, exist_ok=True)
    (target / "irregular.json").write_text(
        json.dumps(forms, ensure_ascii=False, separators=(",", ":"), sort_keys=True), encoding="utf-8")
    return sum(len(section) for section in forms.values())


def main(arguments):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("source")
    parser.add_argument("study")
    parser.add_argument("meaning")
    parser.add_argument("pack_dir")
    parser.add_argument("--snapshot", default="", help="date of the upstream database file")
    parser.add_argument("--irregular", nargs=2, metavar=("LIST", "STUDY_PACK_DIR"))
    parser.add_argument("--supplement", nargs=4, metavar=("TABLE", "NAME", "URL", "SNAPSHOT"))
    parser.add_argument("--curated", metavar="LIST", help="hand-written meanings that lead their headwords")
    parser.add_argument("--replace", metavar="LIST", help="hand-written rows that replace the source's rows")
    options = parser.parse_args(arguments)

    index = meanings_by_word(translation_rows(options.source))
    source = {
        "name": f"WikDict {options.study}-{options.meaning}",
        "url": "https://download.wikdict.com/dictionaries/sqlite/2/"
               f"{options.study}-{options.meaning}.sqlite3",
        "licence": LICENCE,
        "snapshot": options.snapshot,
    }
    added = 0
    if options.supplement:
        table, name, url, snapshot = options.supplement
        index, added = with_supplement(index, read_supplement(table))
        source["supplement"] = {
            "name": name, "url": url, "licence": LICENCE, "snapshot": snapshot, "rows": added,
        }
    if options.replace:
        replaced = json.loads(Path(options.replace).read_text(encoding="utf-8"))
        index, count = with_replaced(index, replaced)
        source["replaced"] = {"name": "HooLang replacement list", "rows": count}
    led = 0
    if options.curated:
        curated = json.loads(Path(options.curated).read_text(encoding="utf-8"))
        index, led = with_curated(index, curated)
        source["curated"] = {"name": "HooLang curated list", "rows": led}
    rows = packlib.write_table(options.pack_dir, "meanings", index)
    packlib.update_manifest(
        options.pack_dir, "meanings", options.study, "meanings", rows, source,
        meaning_language=options.meaning,
    )
    print(f"{options.study}-{options.meaning}: {rows:,} single-word headwords"
          + (f", {added:,} of them from the supplement" if options.supplement else "")
          + (f", {led:,} led by curated meanings." if options.curated else "."))
    if options.irregular:
        count = write_irregular(index, *options.irregular)
        print(f"{options.study}: {count} irregular forms.")


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