"""Comparación pareada CoT/PAL en GSM8K y variantes del mismo problema."""
import json
from random import Random
from statistics import mean
import sys


def analyze(rows, expected=500, draws=2000, seed=1414):
    if expected<2 or draws<100:raise ValueError('invalid sample or bootstrap count')
    pairs={}
    for row in rows:
        family=row.get('family');method=row.get('method')
        if family not in ('gsm8k','gsm8k-large') or method not in ('cot','pal'):
            raise ValueError('unexpected family or method')
        source=row['id'] if family=='gsm8k' else row.get('source_id')
        if not isinstance(source,str) or not source:raise ValueError('missing source id')
        key=(source,family,method)
        if key in pairs:raise ValueError('duplicate condition')
        if type(row.get('correct')) is not bool:raise ValueError('invalid result')
        usage=row.get('usage',{})
        if any(type(usage.get(k)) is not int or usage[k]<0 for k in ('prompt_tokens','completion_tokens')):
            raise ValueError('invalid token usage')
        pairs[key]=row
    ids=sorted({key[0] for key in pairs})
    if len(ids)!=expected or len(pairs)!=expected*4:raise ValueError('incomplete paired sample')
    if any((id,family,method) not in pairs for id in ids for family in ('gsm8k','gsm8k-large') for method in ('cot','pal')):
        raise ValueError('missing paired condition')
    rng=Random(seed);out={}
    for family in ('gsm8k','gsm8k-large'):
        diff=[int(pairs[(id,family,'pal')]['correct'])-int(pairs[(id,family,'cot')]['correct']) for id in ids]
        bootstrap=sorted(mean(rng.choice(diff) for _ in ids) for _ in range(draws))
        conditions={}
        for method in ('cot','pal'):
            subset=[pairs[(id,family,method)] for id in ids]
            durations=[row['usage'].get('wall_seconds') for row in subset]
            conditions[method]={'accuracy':mean(int(row['correct']) for row in subset),
                                'mean_prompt_tokens':mean(row['usage']['prompt_tokens'] for row in subset),
                                'mean_completion_tokens':mean(row['usage']['completion_tokens'] for row in subset),
                                'mean_generation_seconds':mean(durations) if all(type(x) in (int,float) and x>=0 for x in durations) else None,
                                'filter_rejections':sum(row.get('observation',{}).get('status')=='rejected'
                                                        for row in subset if isinstance(row.get('observation'),dict))}
        out[family]={'conditions':conditions,'difference_pal_minus_cot':mean(diff),
                     'paired_bootstrap_95':[bootstrap[int(.025*draws)],bootstrap[min(draws-1,int(.975*draws))]]}
    variation={}
    for method in ('cot','pal'):
        diff=[int(pairs[(id,'gsm8k-large',method)]['correct'])-int(pairs[(id,'gsm8k',method)]['correct']) for id in ids]
        boot=sorted(mean(rng.choice(diff) for _ in ids) for _ in range(draws))
        variation[method]={'difference_large_minus_original':mean(diff),
                           'paired_bootstrap_95':[boot[int(.025*draws)],boot[min(draws-1,int(.975*draws))]]}
    return {'n_source_problems':len(ids),'results':out,'large_variant_effect':variation,
            'limitation':'one generation per method and task; large variant adds a final multiplication; '
                         'intervals conditional on these selected GSM8K problems'}


if __name__=='__main__':
    with open(sys.argv[1],encoding='utf8') as f:lines=[json.loads(line) for line in f]
    print(json.dumps(analyze(lines[1:],expected=lines[0]['metadata']['n_per_family']),ensure_ascii=False,indent=2))
