"""Build the forms table of a study pack from a Kaikki.org (wiktextract) dictionary extract.

Usage: build-study-pack.py <kaikki.org-dictionary-<Language>.jsonl[.gz]> <language code> <study pack dir>
                           [--snapshot YYYY-MM-DD]

Output, in the pack format of ../language-packs/README.md:
  <study pack dir>/forms/<shard>.tsv   form <TAB> [IPA] <TAB> lemma/pos|lemma/pos...

Every word form that Wiktionary lists for the language is mapped to its dictionary forms (lemmas), so the app
translates inflected words without any grammar rules. Two kinds of Wiktionary data are combined:
  - the inflection tables and head-line forms of a lemma entry ("Haus": Hauses, Häuser, ...),
  - entries that are only a form of another word ("ging": past of "gehen"), including alternative spellings.
Nothing in this script is specific to one language; the tag names below are wiktextract's own vocabulary.
"""
import argparse
import collections
import gzip
import json
import sys
from pathlib import Path

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

LICENCE = "CC BY-SA 4.0 (Wiktionary is dual-licensed CC BY-SA 4.0 and GFDL; HooLang uses CC BY-SA 4.0)"
MAX_LEMMAS = 4
MAX_CHAIN = 3
# Entry kinds that are not words a reader taps in a text.
SKIPPED_POS = {"prefix", "suffix", "infix", "interfix", "circumfix", "affix", "combining_form", "character",
               "symbol", "punct", "phrase", "proverb", "prep_phrase"}
# Rows of an inflection table that describe the table (its class, its template, the auxiliary verb)
# instead of naming a form.
PSEUDO_FORM_TAGS = {"table-tags", "inflection-template", "class", "auxiliary"}
# Head-line "forms" that are other words (a verb's auxiliary, a noun's diminutive or counterpart of the other
# gender) or other spellings of the headword itself, not inflected forms of it.
RELATED_WORD_TAGS = {"auxiliary", "diminutive", "augmentative", "feminine", "masculine", "neuter", "canonical",
                     "romanization", "alternative", "abbreviation", "definite", "with-article"}
# A "form of" sense with one of these tags names an inflected form ("ging": preterite of "gehen"). Without
# them the sense describes a word derived from another one ("Lehrer": agent noun of "lehren", "Freundin":
# female equivalent of "Freund"), which is a dictionary form of its own.
INFLECTION_TAGS = {
    "nominative", "genitive", "dative", "accusative", "instrumental", "locative", "vocative", "ablative",
    "singular", "plural", "dual", "first-person", "second-person", "third-person",
    "present", "past", "preterite", "imperfect", "future", "perfect", "pluperfect",
    "imperative", "subjunctive", "subjunctive-i", "subjunctive-ii", "indicative", "conditional",
    "participle", "infinitive", "infinitive-zu", "comparative", "superlative",
}
# A gerund is a verb form in some languages and a noun with its own declension in others ("das Leben").
FORM_UNLESS_INFLECTED_TAGS = {"gerund"}
GENDERED_POS = {"noun", "name"}
GENDERS = {"masculine": "m", "feminine": "f", "neuter": "n"}
EMPTY_FORMS = {"", "-", "—", "–"}


def read_entries(path, language_code):
    """Yields the wiktextract entries of one language from a .jsonl or .jsonl.gz file."""
    opener = gzip.open if str(path).endswith(".gz") else open
    with opener(path, "rt", encoding="utf-8") as lines:
        for line in lines:
            entry = json.loads(line)
            if entry.get("lang_code") == language_code:
                yield entry


def single_word(text):
    """The text when it is one word, also after dropping bracketed hints such as "(du)"; else None."""
    tokens = [token for token in text.split() if not (token.startswith("(") and token.endswith(")"))]
    if len(tokens) != 1:
        return None
    word = tokens[0].strip(",;:!?.")
    separators = any(character in word for character in "|/\t")
    return word if packlib.is_single_word(packlib.normalize(word)) and not separators else None


def first_ipa(entry):
    for sound in entry.get("sounds", []):
        ipa = sound.get("ipa", "").strip().strip("/[]").strip()
        if ipa:
            return f"[{ipa}]"
    return ""


def targets(sense, key):
    return [target.get("word", "") for target in sense.get(key, [])]


def is_table_form(form):
    return "source" in form and not set(form.get("tags", [])) & PSEUDO_FORM_TAGS


def gender_of(entry):
    if entry.get("pos") not in GENDERED_POS:
        return ""
    tags = {tag for sense in entry.get("senses", []) for tag in sense.get("tags", [])}
    found = {code for tag, code in GENDERS.items() if tag in tags}
    return found.pop() if len(found) == 1 else ""


def inflected_forms(entry):
    """Single-word inflected forms listed by a lemma entry."""
    for form in entry.get("forms", []):
        tags = set(form.get("tags", []))
        related_word = "source" not in form and tags & RELATED_WORD_TAGS
        if tags & PSEUDO_FORM_TAGS or related_word:
            continue
        text = form.get("form", "").strip()
        if text in EMPTY_FORMS:
            continue
        word = single_word(text)
        if word:
            yield word


def classify(entry):
    """Splits an entry into (number of senses that make it a dictionary form, words it is a form of).

    A sense without "form of" is a real sense, and so is a "form of" sense that describes a derived word.
    The entry is followed to the other word for inflected forms and for alternative spellings.
    """
    has_table = any(is_table_form(form) for form in entry.get("forms", []))
    own_senses = 0
    linked = []
    for sense in entry.get("senses", []):
        tags = set(sense.get("tags", []))
        form_of = targets(sense, "form_of")
        alt_of = targets(sense, "alt_of")
        inflected = bool(tags & INFLECTION_TAGS) or (not has_table and bool(tags & FORM_UNLESS_INFLECTED_TAGS))
        linked += alt_of
        if form_of and inflected:
            linked += form_of
        elif not alt_of:
            own_senses += 1
    return own_senses, linked


class Collected:
    """What the extract says about every word form, keyed by normalised form."""

    def __init__(self):
        # key -> {(lemma text, part of speech with gender): number of real senses}
        self.lemmas = collections.defaultdict(dict)
        # key -> {(word as written, lemma text, part of speech)}: the word is a form of the lemma
        self.links = collections.defaultdict(set)
        self.ipa = {}

    def add(self, entry):
        word = single_word(entry.get("word", ""))
        pos = entry.get("pos", "")
        if not word or pos in SKIPPED_POS:
            return
        key = packlib.normalize(word)
        own_senses, linked = classify(entry)
        ipa = first_ipa(entry)
        if ipa and key not in self.ipa:
            self.ipa[key] = ipa
        for target in linked:
            lemma = single_word(target)
            if lemma and lemma != word:
                self.links[key].add((word, lemma, pos))
        # A participle is only a form of its verb, yet it has a declension of its own: its forms link to
        # it and are followed to the verb when the table is built.
        for form in inflected_forms(entry):
            if form != word:
                self.links[packlib.normalize(form)].add((form, word, pos))
        if own_senses:
            gender = gender_of(entry)
            spec = (word, f"{pos}.{gender}" if gender else pos)
            self.lemmas[key][spec] = self.lemmas[key].get(spec, 0) + own_senses


def collect(entries):
    collected = Collected()
    for entry in entries:
        collected.add(entry)
    return collected


def resolve(collected, lemma, pos, depth=0):
    """Dictionary forms a link ends at.

    A target that is no dictionary form itself is followed further, so "gelaufene" reaches "laufen" through
    the participle "gelaufen". Only the links of the word as written are followed: the noun "Ding" must not
    lead to the verb whose imperative is "ding".
    """
    key = packlib.normalize(lemma)
    own = [spec for spec in collected.lemmas.get(key, {}) if spec[0] == lemma]
    found = [spec for spec in own if spec[1].split(".")[0] == pos] or own
    if not found and depth < MAX_CHAIN:
        for word, onward, onward_pos in sorted(collected.links.get(key, ())):
            if word == lemma:
                found += [spec for spec in resolve(collected, onward, onward_pos, depth + 1) if spec not in found]
    # Without any entry for the lemma the word itself is kept, a meaning pack may still know it.
    return found or [(lemma, pos)]


def build_rows(collected):
    """Table rows {form key: [ipa, lemma column]}; a form's own entry leads, then lemmas with more senses."""
    def weight(spec):
        return collected.lemmas.get(packlib.normalize(spec[0]), {}).get(spec, 0)

    rows = {}
    for key in set(collected.lemmas) | set(collected.links):
        own = sorted(collected.lemmas.get(key, {}), key=lambda spec: (-weight(spec), spec))
        linked = []
        for _, lemma, pos in sorted(collected.links.get(key, ())):
            for spec in resolve(collected, lemma, pos):
                if spec not in own and spec not in linked:
                    linked.append(spec)
        linked.sort(key=lambda spec: (-weight(spec), spec))
        specs = (own + linked)[:MAX_LEMMAS]
        rows[key] = [collected.ipa.get(key, ""), "|".join(f"{text}/{pos}" if pos else text for text, pos in specs)]
    return rows


def main(arguments):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("source")
    parser.add_argument("language")
    parser.add_argument("pack_dir")
    parser.add_argument("--snapshot", default="", help="date of the Kaikki.org extraction")
    options = parser.parse_args(arguments)

    collected = collect(read_entries(options.source, options.language))
    rows = build_rows(collected)
    count = packlib.write_table(options.pack_dir, "forms", rows)
    packlib.update_manifest(
        options.pack_dir, "study", options.language, "forms", count,
        {
            "name": "Kaikki.org machine-readable dictionary (wiktextract, English Wiktionary)",
            "url": "https://kaikki.org/dictionary/rawdata.html",
            "licence": LICENCE,
            "snapshot": options.snapshot,
        },
    )
    with_ipa = sum(1 for fields in rows.values() if fields[0])
    print(f"{options.language}: {len(collected.lemmas):,} lemma keys, {count:,} forms, {with_ipa:,} with IPA.")


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