"""Collect meanings of a study language from Wiktionary editions other than the English one.

Usage:
  build-meaning-supplement.py <study> <meaning> <out.tsv>
      [--glosses <extract.jsonl.gz>] [--translations <extract.jsonl.gz>]

Example (Italian with Czech meanings):
  build-meaning-supplement.py it cs it-cs-supplement.tsv \
      --glosses cs-extract.jsonl.gz --translations it-extract.jsonl.gz

The extracts are Kaikki.org's wiktextract files of whole Wiktionary editions
(https://kaikki.org/dictionary/downloads/<edition>/<edition>-extract.jsonl.gz):

- --glosses: the edition written in the meaning language (cs.wiktionary for Czech meanings). Its
  entries of the study language explain the word in the meaning language; senses tagged form-of
  ("first person of avere") or no-gloss are skipped, and a gloss listing synonyms ("koncept, náčrt")
  gives one meaning per item.
- --translations: the edition written in the study language (it.wiktionary). Its entries list
  translations into the meaning language.

The output is one table row per headword (key<TAB>meaning...), glosses before translations, keys
normalised like the packs (see ../language-packs/README.md) and sorted. build-meaning-pack.py takes it
with --supplement and uses it only for headwords its main source does not have.
"""
import argparse
import gzip
import json
import re
import sys
from pathlib import Path

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

MAX_MEANINGS = 8
SKIPPED_SENSE_TAGS = {"form-of", "no-gloss"}
LIST_SEPARATOR = re.compile(r"\s*[,;]\s*(?![^()]*\))")


def entries(path, language):
    with gzip.open(path, "rt", encoding="utf-8") as lines:
        for line in lines:
            entry = json.loads(line)
            if entry.get("lang_code") == language and entry.get("word"):
                yield entry


def gloss_meanings(entry):
    """Meanings from the glosses of an entry, one per listed synonym, form-of senses left out."""
    for sense in entry.get("senses", []):
        if SKIPPED_SENSE_TAGS & set(sense.get("tags", [])) or sense.get("form_of"):
            continue
        for gloss in sense.get("glosses", []):
            yield from LIST_SEPARATOR.split(gloss)


def translation_meanings(entry, meaning):
    for translation in entry.get("translations", []):
        if translation.get("lang_code") == meaning:
            yield translation.get("word", "")


def collect(study, meaning, glosses=None, translations=None):
    index = {}

    def add(word, found):
        key = packlib.normalize(word)
        if not packlib.is_single_word(key):
            return
        meanings = index.setdefault(key, [])
        for item in found:
            item = packlib.clean_meaning(item)
            if item and item not in meanings:
                meanings.append(item)

    if glosses:
        for entry in entries(glosses, study):
            add(entry["word"], gloss_meanings(entry))
    if translations:
        for entry in entries(translations, study):
            add(entry["word"], translation_meanings(entry, meaning))
    return {key: meanings[:MAX_MEANINGS] for key, meanings in index.items() if meanings}


def main(arguments):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("study")
    parser.add_argument("meaning")
    parser.add_argument("out")
    parser.add_argument("--glosses", help="extract of the Wiktionary written in the meaning language")
    parser.add_argument("--translations", help="extract of the Wiktionary written in the study language")
    options = parser.parse_args(arguments)
    if not options.glosses and not options.translations:
        parser.error("give --glosses, --translations or both")

    index = collect(options.study, options.meaning, options.glosses, options.translations)
    Path(options.out).write_text(packlib.table_text(index), encoding="utf-8")
    print(f"{options.study}-{options.meaning} supplement: {len(index):,} headwords.")


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