"""Freeze dictionary-backed word families; no morphological runtime on phones.

Install the pinned authoring-only dependency with:
python -m pip install --target tmp/golf-morphology simplemma==2.0.0
Then run this script from the repository root. See site/semantic-golf/lexicon/
for the source-data licenses. Deliberately avoid greedy stemming or synonyms.
"""
import hashlib
import importlib.metadata
import json
from pathlib import Path
import re
import sys
import unicodedata

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT/'tmp/golf-morphology'))
from simplemma.strategies.dictionaries.dictionary_factory import DefaultDictionaryFactory

if importlib.metadata.version('simplemma') != '2.0.0':
    raise ValueError('Use the reviewed simplemma 2.0.0 dictionaries')
catalog_path = ROOT/'site/semantic-golf/corner-languages.json'
catalog = json.loads(catalog_path.read_text(encoding='utf-8'))

def normalize(text, language):
    text = unicodedata.normalize('NFKC', text)
    if language == 'tr':
        text = text.replace('I', 'ı').replace('İ', 'i')
    text = text.lower()
    return ' '.join(''.join(c if unicodedata.category(c)[0] in 'LMN' else ' ' for c in text).split())

factory = DefaultDictionaryFactory(cache_max_size=1)
overrides = json.loads((ROOT/'tools/golf/inflection-overrides.json').read_text(encoding='utf-8'))
result = {'wordVersion':hashlib.sha256(catalog_path.read_bytes()).hexdigest()[:20],
          'source':'simplemma 2.0.0 dictionary subset; see lexicon/NOTICE.md', 'languages':{}}
report = {}
for language, info in catalog['languages'].items():
    dictionary = factory.get_dictionary(language)
    families = {normalize(word,language):{normalize(word,language)} for word in info['words']}
    targets = {}
    for word, part in zip(info['words'],catalog['partsOfSpeech'],strict=True):
        key = normalize(word,language)
        tokens = word.split()
        head = 0
        if len(tokens)>1 and language=='tr' and part=='verb':
            head = len(tokens)-1
        # Keep multiword nouns literal; inflect only a known verb/adjective head.
        if len(tokens)>1 and part=='noun':
            continue
        value = tokens[head]
        lemmas = {normalize(value,language)}
        # Italian clitic infinitive: the dictionary stores the bare verb lemma.
        if language=='it' and value=='arrampicarsi':
            lemmas.add('arrampicare')
        found = dictionary.get(value) or dictionary.get(value.lower())
        if found:
            lemmas.add(normalize(found,language))
        prefix = ' '.join(tokens[:head]);suffix = ' '.join(tokens[head+1:])
        for lemma in lemmas:
            targets.setdefault(lemma,[]).append((key,prefix,suffix))
    for form, lemma in dictionary.items():
        entries = targets.get(normalize(lemma,language))
        if not entries:
            continue
        normalized = normalize(form,language)
        if not normalized or len(normalized)>80:
            continue
        for key,prefix,suffix in entries:
            candidate = normalize(' '.join(p for p in (prefix,normalized,suffix) if p),language)
            if len(candidate)<=80:
                families[key].add(candidate)
    for word, forms in overrides.get(language,{}).items():
        key=normalize(word,language)
        if key not in families:
            raise ValueError('Unknown inflection override: '+word)
        families[key].update(normalize(form,language) for form in forms)
    result['languages'][language] = {key:sorted(forms) for key,forms in sorted(families.items())}
    missing = [word for word,part in zip(info['words'],catalog['partsOfSpeech'],strict=True)
               if part=='verb' and len(families[normalize(word,language)])==1]
    report[language] = {'words':len(families),'forms':sum(map(len,families.values())), 'verbsWithoutForms':missing}
    print(language,report[language],flush=True)

output = ROOT/'site/semantic-golf/corner-forms.json'
output.write_text(json.dumps(result,ensure_ascii=False,separators=(',',':')),encoding='utf-8')
(ROOT/'tmp/golf-web/inflection-coverage.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print('Published',output.stat().st_size,'bytes of explicit word families')
