"""Audita campañas de frontera y vuelve a extraer respuestas, sin inferencia."""
import argparse,gzip,hashlib,json,sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'l05'))
import answer_extract_v2 as extractor

EXPECTED={'qwen05':(32,494032768),'qwen15':(32,1543714304),'qwen7':(2,7615616512)}
def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def main():
    p=argparse.ArgumentParser();p.add_argument('--samples',required=True);p.add_argument('--run',action='append',required=True);p.add_argument('--output',required=True);a=p.parse_args()
    source=Path(a.samples)
    with gzip.open(source,'rt',encoding='utf8') as f:old=[json.loads(line) for line in f if line.strip()]
    questions=sorted((r for r in old if r['problema']<200 and r['muestra']==0),key=lambda r:r['problema'])
    if [r['problema'] for r in questions]!=list(range(200)):raise ValueError('Preguntas incompletas')
    folders=dict(spec.split('=',1) for spec in a.run)
    if set(folders)!=set(EXPECTED):raise ValueError('Se requieren los tres modelos')
    results={}
    for name,(n,parameters) in EXPECTED.items():
        root=Path(folders[name]);protocol=json.loads((root/'protocol.json').read_text(encoding='utf8'))
        if protocol['count']!=200 or protocol['n']!=n or protocol['questions_sha256']!=sha(source) or protocol['extractor_sha256']!=sha(extractor.__file__):
            raise ValueError(f'Protocolo incompatible: {name}')
        totals={'questions':0,'samples':0,'abstentions':0,'truncated':0,'input_tokens':0,'output_tokens':0}
        hashes={'protocol.json':sha(root/'protocol.json')}
        for i,question in enumerate(questions):
            path=root/f'problem-{i:04d}.json';row=json.loads(path.read_text(encoding='utf8'));hashes[path.name]=sha(path)
            if (row['problem']!=i or row['question']!=question['pregunta'] or row['reference']!=question['referencia'] or
                row['parameters']!=parameters or len(row['samples'])!=n):raise ValueError(f'Identidad incorrecta: {name}/{i}')
            batches={}
            expected_batch={'qwen05':8,'qwen15':32,'qwen7':1}[name]
            for j,sample in enumerate(row['samples']):
                answer=extractor.extract(sample['text'],truncated=sample['truncated'])
                expected=None if answer is None else int(answer==row['reference'])
                if answer!=sample['answer'] or sample['correct']!=expected:raise ValueError(f'Extracción distinta: {name}/{i}')
                if not (type(sample['input_tokens']) is int and sample['input_tokens']>0 and
                        type(sample['output_tokens']) is int and 0<=sample['output_tokens']<=256):raise ValueError('Tokens inválidos')
                if sample['batch_index']!=j//expected_batch or sample['batch_size']!=expected_batch:raise ValueError('Asignación de lotes incorrecta')
                if name=='qwen05' and sample['input_tokens']+256>1024:raise ValueError('Contexto 0.5B insuficiente')
                if name=='qwen7' and sample['repeat_last_n_effective']<sample['input_tokens']+256:raise ValueError('Penalización no cubre el contexto')
                batches.setdefault(sample['batch_index'],[]).append(sample)
                totals['samples']+=1;totals['abstentions']+=answer is None;totals['truncated']+=sample['truncated']
                totals['input_tokens']+=sample['input_tokens'];totals['output_tokens']+=sample['output_tokens']
            for batch in batches.values():
                if (len(batch)!=batch[0]['batch_size'] or len({s['batch_wall_seconds'] for s in batch})!=1 or
                    batch[0]['batch_wall_seconds']<0):raise ValueError('Lote o tiempo incompleto')
            totals['questions']+=1
        results[name]={'totals':totals,'sha256':hashes}
    Path(a.output).write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf8')
    print('Auditoría de tres campañas completa:',{k:v['totals'] for k,v in results.items()})
if __name__=='__main__':main()
