"""Reproducible conservative bank audit + RLA-ES lexical expansion.
Run with silabeador==1.2.4.post1 and spylls==0.1.7 (development only).
Generated lexicon is a recognition guard, never a claim of semantic review.
"""
from pathlib import Path
import json,re,unicodedata,collections,hashlib,base64,gzip
from spylls.hunspell import Dictionary
import silabeador
ROOT=Path(__file__).resolve().parents[1]
D=Dictionary.from_files(str(ROOT/'vendor/rla-es/index'))
VALID=re.compile(r'^[a-záéíóúüñ]+$')
def acceptable(w): return bool(VALID.fullmatch(w)) and len(w)>1
lex=set()
# Only suffix forms and suffix continuation flags; no speculative prefix cross-products.
# Every generated form is independently checked by the Hunspell-compatible lookup.
for entry in D.dic.words:
    if not acceptable(entry.stem): continue
    lex.add(entry.stem)
    frontier=[(entry.stem,entry.flags)]
    for depth in range(2):
        nxt=[]
        for word,flags in frontier:
            for flag in flags:
                for aff in D.aff.SFX.get(flag,[]):
                    if not aff.cond_regexp.search(word):continue
                    if aff.strip and not word.endswith(aff.strip):continue
                    form=(word[:-len(aff.strip)] if aff.strip else word)+aff.add
                    if acceptable(form) and form not in lex and D.lookup(form):
                        lex.add(form)
                        if aff.flags:nxt.append((form,aff.flags))
        frontier=nxt
# Lower-case single letters are real lexical candidates too.
lex.update('a e o u y'.split())
original=json.loads((ROOT/'scripts/data/bank-original.json').read_text())
# Context-dependent distinctions are never safe in an isolated choose-the-spelling item.
ambiguous=set('a ha ah e he eh o oh ay hay ahí aya haya halla halla hayas hallas vaya valla baya vayas vallas bayas hecho echo hechos ecos hecha echa hechas echas tubo tuvo tubos tuvo hola ola hola olas asta hasta uso huso usos husos bello vello bellos vellos bienes vienes votar botar vote bote votar botar grabar gravar grabe grave sabia savia sabias savias rebelar revelar rebelo revelo casa caza casas cazas cocer coser cima sima cimas simas callo cayo calló cayó arrollo arroyo arrolló arroyó abría habría habría abrían habrían hierba hierva hierbas hiervas desecho deshecho deshecha desecha desechos deshechos errar herrar erró herró hojear ojear hojea ojea abría habría vaca baca vacas bacas basto vasto basta vasta bastos vastos baso vaso basos vasos barón varón barones varones honda onda hondas ondas hondo ondo si sí tu tú el él mi mí te té de dé se sé mas más aun aún solo sólo este éste esta ésta estos éstos estas éstas ese ése esa ésa esos ésos esas ésas aquel aquél aquella aquélla aquellos aquéllos aquellas aquéllas que qué quien quién quienes quiénes como cómo cuando cuándo donde dónde adonde adónde cual cuál cuales cuáles cuanto cuánto cuanta cuánta cuantos cuántos cuantas cuántas porque porqué rio río rió crio crío crió frio frío fío fio pie píe pío pio lie líe lio lío'.split())
# Regional/admitted accentuation variants must never be marked incorrect.
variant_groups=[['futbol','fútbol'],['periodo','período'],['icono','ícono'],['video','vídeo'],['chófer','chofer'],['élite','elite'],['reuma','reúma'],['osmosis','ósmosis'],['zodiaco','zodíaco'],['austriaco','austríaco'],['policiaco','policíaco'],['cardiaco','cardíaco'],['amoniaco','amoníaco'],['maniaco','maníaco'],['olimpiada','olimpíada'],['alergeno','alérgeno'],['pabilo','pábilo'],['medula','médula'],['alveolo','alvéolo'],['isobara','isóbara'],['pentagrama','pentágrama']]
for g in variant_groups:ambiguous.update(g)
essential_ambiguous=set(ambiguous)
# More potentially valid accent contrasts are detected lexically.
def noaccent(w):return ''.join(c for c in unicodedata.normalize('NFD',w) if unicodedata.category(c)!='Mn')
folded=collections.defaultdict(list)
for w in lex:folded[noaccent(w)].append(w)
for ws in folded.values():
    if len(ws)>1:ambiguous.update(ws)
manual_allow=set('brócoli cartita cúter dúplex ecólogo feísimo fotito fórceps fórum gatito gijonés híper librito monito médanos osito ovejita patito pénsil póker pólder sillita sófbol tándem vaquita wáter yoga ónix'.split())
manual={
'azul':('letras','«Azul» se escribe con z y termina en l.'),
'guion':('letras','«Guion» es monosílaba a efectos ortográficos y se escribe sin tilde.'),
'truhan':('letras','«Truhan» es monosílaba a efectos ortográficos y se escribe sin tilde.'),
'solo':('diacrítica','Se escribe «solo» sin tilde. En el uso adverbial puede tildarse si quien escribe aprecia riesgo de ambigüedad.'),
'aquel':('diacrítica','Los demostrativos se escriben sin tilde. En usos pronominales puede emplearse si quien escribe aprecia riesgo de ambigüedad.'),
'búho':('hiato','«Búho» lleva tilde en la ú: la vocal cerrada tónica forma hiato. La h intercalada no impide el hiato.'),
'ahí':('hiato','«Ahí» señala un lugar. Lleva h y tilde en la í; no equivale a «hay», del verbo haber.'),
}
bank=[];removed=[];seen=set();changed=0
# Keep the familiar graded pool: expansion of the recognition lexicon does not
# silently turn rare inflections into beginner exercises.
for old in original:
    w=unicodedata.normalize('NFC',old['p'].strip().lower())
    if w in seen:continue
    if not acceptable(w) and w not in {'a','e','o','u','y'}:removed.append(w);continue
    if not D.lookup(w) and w not in manual and w not in manual_allow:removed.append(w);continue
    seen.add(w)
    item={'p':w,'n':old['n'],'c':'letras','r':f'Observa y recuerda la grafía correcta: «{w}».','source':'RLA-ES 2.8','review':'automatic'}
    is_amb=w in ambiguous or old['c']=='diacrítica'
    if is_amb:item['ambiguous']=True
    # Use standard orthographic vowel group conventions, not poetic exceptions.
    # -mente has two stress centres; exclude it from single-tonic-syllable questions.
    if not w.endswith('mente') and not is_amb:
        syl=silabeador.Syllabification(w,exceptions=False)
        s=syl.syllables;t=len(s)+syl.stress
        if ''.join(s)==w and 0<=t<len(s):
            item.update(s=s,t=t)
            if old['c']!='letras':
                distance=len(s)-t
                cat={1:'aguda',2:'llana',3:'esdrújula'}.get(distance)
                if len(s)==1:
                    item['r']=f'«{w}» es monosílaba a efectos ortográficos.'
                elif cat:
                    item['c']=cat
                    if old['c']=='hiato' and re.search(r'[aeoáéóh][íú]|[íú][haeoáéó]',w):item['c']='hiato'
                    tonic=s[t]
                    # Do not infer blanket letter-choice rules or stress rules from suffix matching.
                    item['r']=f'La sílaba tónica es «{tonic}». La grafía correcta es «{w}».'
    if w in manual:item['c'],item['r']=manual[w];item['review']='manual'
    if w in manual_allow:item['source']='Revisión editorial';item['review']='manual'
    if w.endswith('mente'):
        item['r']=f'«{w}» conserva la tilde del adjetivo del que se forma, si este la lleva.'
        item.pop('s',None);item.pop('t',None)
    changed+=item['r']!=old['r'];bank.append(item)
# Ensure canonical current spellings are present even if old bank omitted them.
for w in ['guion','truhan']:
    if w not in seen:
        c,r=manual[w];bank.append({'p':w,'n':2,'c':c,'r':r,'source':'RAE DPD','review':'manual'})
lex.update(x['p'] for x in bank)
lexlist=sorted(lex)
# A Bloom guard conservatively rejects plausible valid distractors. False positives
# only reduce the number of distractors; it never turns a valid word into an error.
BIT_COUNT=8388608
HASH_COUNT=7
bits=bytearray(BIT_COUNT//8)
def hashes(word):
    a,b=2166136261,3339675911
    for ch in word:
        a=((a^ord(ch))*16777619)&0xffffffff
        b=((b^ord(ch))*16777619)&0xffffffff
    return a,b|1
for w in lexlist:
    a,b=hashes(w)
    for i in range(HASH_COUNT):
        bit=(a+i*b)%BIT_COUNT
        bits[bit//8]|=1<<(bit%8)
encoded=base64.b64encode(bits).decode()
js_guard="""// RLA-ES-derived Bloom guard; see language-sources.md. False positives only suppress distractors.
const LEXICON_SET=(()=>{const bits=Uint8Array.from(atob(__BITS__),c=>c.charCodeAt(0));return Object.freeze({size:__SIZE__,has(word){if(typeof word!=='string')return false;let a=2166136261,b=3339675911;for(let i=0;i<word.length;i++){a=Math.imul(a^word.charCodeAt(i),16777619)>>>0;b=Math.imul(b^word.charCodeAt(i),16777619)>>>0;}b=(b|1)>>>0;for(let i=0;i<7;i++){let bit=(a+i*b)%8388608;if(!(bits[bit>>>3]&(1<<(bit&7))))return false;}return true;}});})();
const AMBIGUOUS_SET = new Set(__AMBIGUOUS__);
""".replace('__BITS__',json.dumps(encoded)).replace('__SIZE__',str(len(lex))).replace('__AMBIGUOUS__',json.dumps(sorted((ambiguous & seen) | essential_ambiguous),ensure_ascii=False,separators=(',',':')))
(ROOT/'site/lexicon.js').write_text(js_guard)
lexbytes=('\n'.join(lexlist)+'\n').encode()
(ROOT/'site/lexicon-forms.txt.gz').write_bytes(gzip.compress(lexbytes,mtime=0))
# Compact the repeated explanations and fields without changing BANK's public shape.
rows=[[x['p'],x['n'],x['c'],x.get('s'),x.get('t'),bool(x.get('ambiguous')),x['review']=='manual',x['r'] if x['review']=='manual' else None] for x in bank]
js_bank="""// Audited graded pool. Automatic entries are not individually reviewed.
const BANK=__ROWS__.map(([p,n,c,s,t,ambiguous,manual,explanation])=>{const r=explanation||(p.endsWith('mente')?`«${p}» conserva la tilde del adjetivo del que se forma, si este la lleva.`:s&&s.length===1?`«${p}» es monosílaba a efectos ortográficos.`:s&&c!=='letras'?`La sílaba tónica es «${s[t]}». La grafía correcta es «${p}».`:`Observa y recuerda la grafía correcta: «${p}».`);const w={p,n,c,r,source:manual?'Revisión editorial / RAE':'RLA-ES 2.8',review:manual?'manual':'automatic'};if(s){w.s=s;w.t=t;}if(ambiguous)w.ambiguous=true;return w;});
const BANK_METADATA=__METADATA__;
""".replace('__ROWS__',json.dumps(rows,ensure_ascii=False,separators=(',',':'))).replace('__METADATA__',json.dumps({'version':'2026-11-17','practiceWords':len(bank),'lexicalForms':len(lex),'manualEntries':sum(x['review']=='manual' for x in bank),'method':'RLA-ES lexical check; conservative explanations; orthographic syllabification','notEquivalentTo':'individually reviewed exercises'},ensure_ascii=False,separators=(',',':')))
(ROOT/'site/bank.js').write_text(js_bank)
report={'original':len(original),'practice':len(bank),'lexicalForms':len(lex),'removedCount':len(removed),'removed':removed,'rewrittenExplanations':changed,'ambiguous':sum(bool(x.get('ambiguous')) for x in bank),'syllabified':sum('s' in x for x in bank)}
(ROOT/'scripts/data/bank-audit.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
print(json.dumps({k:v for k,v in report.items() if k!='removed'},ensure_ascii=False))
