"""Análisis exploratorio de marcadores Markdown/LaTeX, sin alterar puntuación fijada."""
import hashlib,json,re,sys
from pathlib import Path
from pal_campaign import final_number,numeric
from analyze_pal import analyze

if len(sys.argv)!=3:raise SystemExit('uso: pal_format_sensitivity_autor11.py resultados.jsonl salida.json')
source=Path(sys.argv[1]);out=Path(sys.argv[2])
if out.exists():raise FileExistsError('no sobrescribir análisis')
raw=source.read_bytes();lines=[json.loads(x) for x in raw.splitlines()]
rows=lines[1:]
if len(rows)!=2000 or lines[0]['metadata']['n_per_family']!=500:
    raise ValueError('se necesita el corpus completo')
def normalized(text):
    fixed=[]
    for line in text.splitlines():
        stripped=line.strip()
        # Solo se quitan asteriscos que rodean la línea entera; no se adivinan respuestas.
        if stripped.startswith('**') and stripped.endswith('**'):
            stripped=stripped[2:-2].strip()
        match=re.fullmatch(r'(?i)\\text\{\s*final\s*:\s*\}\s*([+-]?[\d,.]+)',stripped)
        fixed.append('FINAL: '+match.group(1) if match else stripped)
    return '\n'.join(fixed)

alternative=[];new_markers={family:0 for family in ('gsm8k','gsm8k-large')};changed=[]
for row in rows:
    copy=dict(row)
    if row['method']=='cot' and final_number(row['model_output']) is None:
        value=final_number(normalized(row['model_output']))
        if value is not None:
            new_markers[row['family']]+=1
            copy['correct']=value==numeric(row['answer'])
            changed.append({'id':row['id'],'family':row['family'],'parsed':str(value),'correct':copy['correct']})
    alternative.append(copy)
result={'source_sha256':hashlib.sha256(raw).hexdigest(),
        'scope':'Exploratorio posterior a inspección de fallos; conserva puntuación original como principal.',
        'rule':'Aceptar, además del marcador original, una línea FINAL rodeada por negrita Markdown o una línea con \\text{FINAL: } seguida de un número.',
        'new_recognized_by_family':new_markers,'original':analyze(rows,expected=500),
        'sensitivity':analyze(alternative,expected=500),'changed':changed}
out.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
print('Sensibilidad exploratoria guardada en',out)
