"""Audita currículo o comparación pareada, con costes de construcción separados."""
import argparse,hashlib,json,random,statistics
from collections import Counter
from pathlib import Path
from skill_library_env import make_tasks,retrieve
from skill_library_eval import (MODEL,REV,MODEL_SHA,ATTEMPTS,TOTAL_BUDGET,OUTPUT_BUDGET,
                                PER_ATTEMPT,validate_history)

def analyze(path,library_path=None,development_input=None,allow_partial=False,draws=2000,seed=3035):
    from transformers import AutoTokenizer
    from skill_library_learn import derive
    path=Path(path);raw=path.read_bytes();lines=raw.decode('utf8').splitlines()
    meta=json.loads(lines[0])['metadata'];split=meta['split']
    if (meta['protocol'],meta['model'],meta['revision'],meta['expected_model_sha256'],meta['backend'])!=(3,MODEL,REV,MODEL_SHA,'cuda'):
        raise ValueError('unexpected model identity')
    conditions=('retry',) if split=='development' else ('retry','library')
    if (split not in ('development','test') or meta['conditions']!=list(conditions)
        or (meta['attempts'],meta['total_token_cap'],meta['output_token_allocation'],meta['output_cap_per_attempt'])
           !=(ATTEMPTS,TOTAL_BUDGET,OUTPUT_BUDGET,PER_ATTEMPT)
        or meta['sampling']!={'temperature':.7,'top_p':1.,'top_k':0,'min_p':None,'repetition_penalty':1.}
        or meta['eos_rule']!='únicamente tokenizer.eos_token_id'):
        raise ValueError('unexpected protocol')
    source=Path(__file__)
    for key,name in (('code_sha256','skill_library_eval.py'),('environment_sha256','skill_library_env.py'),('learning_sha256','skill_library_learn.py')):
        if meta[key]!=hashlib.sha256(source.with_name(name).read_bytes()).hexdigest():raise ValueError('protocol code differs')
    tasks=make_tasks()[0 if split=='development' else 1]
    if meta['task_count']!=len(tasks) or meta['task_sha256']!=hashlib.sha256(json.dumps(tasks,sort_keys=True,ensure_ascii=False).encode()).hexdigest():
        raise ValueError('task set differs')
    tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    library=None;learned=None
    if split=='test':
        if not library_path or not development_input:raise ValueError('test requires frozen library and development data')
        library_raw=Path(library_path).read_bytes();learned=json.loads(library_raw)
        if (meta['library_sha256']!=hashlib.sha256(library_raw).hexdigest()
            or learned!=derive(development_input,tokenizer) or meta['development_source_sha256']!=learned['source_sha256']):
            raise ValueError('library provenance differs')
        library=learned['skills']
    elif meta['library_sha256'] is not None or meta['development_source_sha256'] is not None:
        raise ValueError('development cannot consume a library')
    rows={}
    for line in lines[1:]:
        row=json.loads(line);key=(row['task_id'],row['condition'])
        if key in rows:raise ValueError('duplicate row')
        rows[key]=row
    journal=Path(str(path)+'.calls.jsonl');jraw=journal.read_bytes();jlines=jraw.decode('utf8').splitlines()
    if json.loads(jlines[0])!={'metadata':meta}:raise ValueError('journal metadata differs')
    calls={}
    for line in jlines[1:]:
        event=json.loads(line);key=(event['task_id'],event['condition'],event['attempt'])
        if key in calls:raise ValueError('duplicate call')
        calls[key]=event
    validate_history(tasks,rows,calls,tokenizer,split,conditions,library)
    selected=[t for t in tasks if all((t['id'],c) in rows for c in conditions)]
    if len(selected)!=len(tasks) and not allow_partial:raise ValueError('incomplete evaluation')
    if len(selected)<2:raise ValueError('not enough tasks')
    grouped={c:[rows[(t['id'],c)] for t in selected] for c in conditions}
    result={'metadata':meta,'source_sha256':hashlib.sha256(raw).hexdigest(),
            'journal_sha256':hashlib.sha256(jraw).hexdigest(),'tasks':len(selected),
            'expected_tasks':len(tasks),'complete':len(selected)==len(tasks),
            'conditions':{c:{**{f'success_at_{k}':sum(r[f'success_at_{k}'] for r in group)/len(group) for k in range(1,ATTEMPTS+1)},
                             'mean_input_tokens':statistics.mean(r['input_tokens'] for r in group),
                             'mean_output_tokens':statistics.mean(r['output_tokens'] for r in group),
                             'mean_total_tokens':statistics.mean(r['total_tokens'] for r in group),
                             'max_total_tokens':max(r['total_tokens'] for r in group),
                             'truncated_attempts':sum(a['event']['end_reason']=='length' for r in group for a in r['attempts']),
                             'verdicts':dict(Counter(a['verdict'].get('error','success') for r in group for a in r['attempts']))}
                          for c,group in grouped.items()},
            'observed_calls':len(calls),'mean_seconds_per_call':statistics.mean(e['seconds'] for e in calls.values()),
            'max_allocated_bytes':max(e['peak_allocated_bytes'] for e in calls.values()),
            'max_reserved_bytes':max(e['peak_reserved_bytes'] for e in calls.values()),
            'limitation':'presupuesto común no implica gasto idéntico; biblioteca derivada de desarrollo, '
                         'herramientas aritméticas cerradas y recuperación léxica; no mide generalidad'}
    if learned is not None:
        diffs=[int(b[f'success_at_{ATTEMPTS}'])-int(a[f'success_at_{ATTEMPTS}']) for a,b in zip(grouped['retry'],grouped['library'])]
        rng=random.Random(seed);boot=sorted(sum(rng.choice(diffs) for _ in diffs)/len(diffs) for _ in range(draws))
        cost=learned['construction_input_tokens']+learned['construction_output_tokens']
        retrieved=[retrieve(task['prompt'],library) for task in selected]
        result.update(difference_library_minus_retry=statistics.mean(diffs),
                      paired_bootstrap_95=[boot[int(.025*draws)],boot[min(draws-1,int(.975*draws))]],
                      library_families=[s['id'] for s in learned['skills']],missing_families=learned['missing_families'],
                      retrieval_correct=sum(item is not None and item['id']==task['skill'] for task,item in zip(selected,retrieved)),
                      retrieval_wrong=sum(item is not None and item['id']!=task['skill'] for task,item in zip(selected,retrieved)),
                      retrieval_empty=sum(item is None for item in retrieved),
                      construction_tokens=cost,construction_calls=learned['construction_calls'],
                      construction_tokens_amortized_per_test_task=cost/len(tasks))
    return result

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--output')
    p.add_argument('--library');p.add_argument('--development-input');p.add_argument('--allow-partial',action='store_true')
    args=p.parse_args();result=analyze(args.input,args.library,args.development_input,args.allow_partial)
    text=json.dumps(result,ensure_ascii=False,indent=2)
    if args.output:
        out=Path(args.output)
        if out.exists():raise ValueError('refusing to overwrite')
        out.write_text(text+'\n',encoding='utf8')
    print(text)
