"""Turn a WikDict <language>-<meaning> database around into a supplement table <meaning> -> <language>.

Usage:
  build-reverse-supplement.py <wikdict.sqlite3[.xz]> <out.tsv> [--first <table.tsv>]

Example (Spanish meanings of Czech words, from the Spanish-Czech database):
  build-reverse-supplement.py es-cs.sqlite3 cs-es-reverse.tsv --first cs-es-supplement.tsv

WikDict's pair for the other direction lists the Czech words each Spanish headword translates.
Read backwards, every Czech translation gets the Spanish headwords as its meanings, best score
first, at most four. Only single-word headwords and single-word translations are used. The rows of
--first (another supplement, for example the translations of the Czech Wiktionary) are copied as
they are, and a reversed row is added only for a word the table does not have yet. The output is
what build-meaning-pack.py takes with --supplement, so WikDict's own cs-xx entries still win.
"""
import argparse
import collections
import importlib.util
import sys
from pathlib import Path

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

spec = importlib.util.spec_from_file_location("wikdict_pack", HERE / "build-meaning-pack.py")
wikdict = importlib.util.module_from_spec(spec)
spec.loader.exec_module(wikdict)

MAX_MEANINGS = 4


def reverse_meanings(rows):
    """Rows (written_rep, trans_list, score) of an xx-cs database as {cs word: [xx headwords]}."""
    candidates = collections.defaultdict(list)
    for position, (written, translations, score) in enumerate(rows):
        headword = packlib.clean_meaning(written)
        if not headword or " " in headword:
            continue
        for translation in translations.split(" | "):
            key = packlib.normalize(packlib.clean_meaning(translation) or "")
            if key and packlib.is_single_word(key):
                candidates[key].append((-(score or 0), position, headword))
    index = {}
    for key, entries in candidates.items():
        meanings = []
        for _, _, headword in sorted(entries):
            if headword not in meanings:
                meanings.append(headword)
        index[key] = meanings[:MAX_MEANINGS]
    return index


def main(arguments):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("source")
    parser.add_argument("out")
    parser.add_argument("--first", help="supplement table whose rows stay as they are")
    options = parser.parse_args(arguments)

    table = wikdict.read_supplement(options.first) if options.first else {}
    reversed_rows = reverse_meanings(wikdict.translation_rows(options.source))
    merged, added = wikdict.with_supplement(table, reversed_rows)
    Path(options.out).write_text(
        "".join(f"{key}\t" + "\t".join(meanings) + "\n" for key, meanings in sorted(merged.items())),
        encoding="utf-8")
    print(f"{len(table)} rows of the first table, {added} reversed rows added.")


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