"""Analyze the fixed report cohort without model calls or campaign mutations.

The census classifies observed trajectories, not hidden intentions. A fixed,
stratified sample supports separately reviewed explanations and case studies.
"""
import argparse
from collections import Counter
import csv
from datetime import datetime,timezone
import gzip
import hashlib
import json
from pathlib import Path
import random
import statistics

ROOT=Path(__file__).resolve().parents[1]

def read(path):return json.loads(path.read_text())
def write(path,value):
    path.parent.mkdir(parents=True,exist_ok=True)
    path.write_text(json.dumps(value,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n')
def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()

DIRECTIONAL={'up','down','left','right'}
TRAJECTORIES={
    'wait_only':'Waits only',
    'long_wait_tail':'Actions, then a majority waiting tail',
    'short_wait_tail':'Ends with a shorter waiting tail',
    'non_wait_finish':'Ends on a non-wait command',
}


def compressed(path):return json.loads(gzip.decompress(path.read_bytes()))


def trajectory(playback):
    frames=playback['frames'];commands=[f['command'] for f in frames[1:]]
    if any(c not in DIRECTIONAL|{'wait','undo','restart'} for c in commands):raise ValueError('Unknown command')
    n=len(commands);tail=0
    for command in reversed(commands):
        if command!='wait':break
        tail+=1
    if n and tail==n:kind='wait_only'
    elif tail>n/2:kind='long_wait_tail'
    elif tail:kind='short_wait_tail'
    else:kind='non_wait_finish'
    counts=Counter(commands);entities={};row_hashes={};board_hash=0;seen=set()
    directional_unchanged=0;directional_revisits=0;last_visible_you=None;visible_you=0
    wait_changes=0;terminal_wait_changes=0
    def row_hash(row):return int.from_bytes(hashlib.blake2b(json.dumps(row[:8],separators=(',',':')).encode(),digest_size=16).digest(),'big')
    previous=None
    for index,frame in enumerate(frames):
        for ident in frame['removed']:
            old=entities.pop(ident)
            visible_you-=int('you' in old[7]);board_hash^=row_hashes.pop(ident)
        for row in frame['changed']:
            ident=row[0]
            if ident in entities:
                visible_you-=int('you' in entities[ident][7]);board_hash^=row_hashes[ident]
            entities[ident]=row;visible_you+=int('you' in row[7]);row_hashes[ident]=row_hash(row);board_hash^=row_hashes[ident]
        signature=(board_hash,tuple(frame['rules']),tuple(frame.get('room_offset',[0,0])),frame.get('level_direction','down'))
        if frame['command'] in DIRECTIONAL:
            if signature==previous:directional_unchanged+=1
            elif signature in seen:directional_revisits+=1
        if frame['command']=='wait' and signature!=previous:
            wait_changes+=1
            if index>n-tail:terminal_wait_changes+=1
        if visible_you:last_visible_you=index
        seen.add(signature);previous=signature
    return dict(trajectory=kind,actions=n,directional=sum(counts[c] for c in DIRECTIONAL),
        waits=counts['wait'],undos=counts['undo'],restarts=counts['restart'],terminal_waits=tail,
        before_terminal_wait=n-tail,terminal_wait_share=tail/n if n else 0,
        unchanged_visible_board_directional_inputs=directional_unchanged,
        revisited_visible_board_directional_inputs=directional_revisits,
        final_visible_you=visible_you,last_visible_you_action=last_visible_you,
        wait_visible_changes=wait_changes,terminal_wait_visible_changes=terminal_wait_changes,
        final_level_is_you=any(rule=='LEVEL IS YOU' for rule in frames[-1]['rules']))


def aggregate(rows):
    failures=[r for r in rows if not r['won']];long=[r for r in failures if r['trajectory'] in ('wait_only','long_wait_tail')]
    return dict(attempts=len(rows),wins=sum(r['won'] for r in rows),failures=len(failures),
        trajectories={k:sum(r['trajectory']==k for r in failures) for k in TRAJECTORIES},
        long_wait_failures=len(long),median_non_wait_commands_on_failures=statistics.median([r['actions']-r['waits'] for r in failures]) if failures else None,
        median_prefix_before_long_wait=statistics.median([r['before_terminal_wait'] for r in long]) if long else None,
        failure_undos=sum(r['undos'] for r in failures),failure_restarts=sum(r['restarts'] for r in failures),
        failures_with_undo=sum(r['undos']>0 for r in failures),failures_with_restart=sum(r['restarts']>0 for r in failures),
        failures_without_visible_you_at_end=sum(r['final_visible_you']==0 and not r['final_level_is_you'] for r in failures),
        failures_with_directional_board_revisit=sum(r['revisited_visible_board_directional_inputs']>0 for r in failures),
        wait_only_with_visible_changes=sum(r['trajectory']=='wait_only' and r['wait_visible_changes']>0 for r in failures),
        long_wait_with_visible_changes=sum(r['terminal_wait_visible_changes']>0 for r in long),
        failures_with_any_recovery=sum(r['undos']+r['restarts']>0 for r in failures),
        failure_directional_inputs=sum(r['directional'] for r in failures),
        failure_directional_unchanged=sum(r['unchanged_visible_board_directional_inputs'] for r in failures))


def validate_review(annotation,selected,episodes):
    if set(annotation['cases'])!={r['key'] for r in selected}:raise ValueError('Review sample differs from its fixed manifest')
    for key,case in annotation['cases'].items():
        if case['label'] not in annotation['codebook']:raise ValueError('Unknown review label')
        evidence=case.get('evidence')
        if evidence:
            event=next((e for e in episodes[key]['events'] if e['seq']==evidence['seq']),None)
            if not event or event.get('type') not in ('agent.message','agent.reasoning') or event.get('at')!=evidence['at'] or evidence['quote'] not in event.get('text',''):
                raise ValueError('Review evidence does not match its recorded event: '+key)
        elif case['label']!='unavailable':raise ValueError('A substantive reviewed reason needs quoted evidence')


def state_at(playback,index):
    entities={}
    for frame in playback['frames'][:index+1]:
        for ident in frame['removed']:entities.pop(ident)
        for row in frame['changed']:entities[row[0]]=row
    frame=playback['frames'][index]
    return dict(action=index,hash=frame['hash'],rules=frame['rules'],entities=list(entities.values()),won=frame['won'])


def case_studies(report,episodes):
    specifications=[('identity','r-252050b3d99ea0','puzzle-021',[0,27,43]),
                    ('moving_target','r-cafcdc2565377c','puzzle-062',[70,71,72,73,74,152]),
                    ('control_loss','r-8a39b7a3bf8d4e','puzzle-011',[5,6,8,234])]
    records={}
    for name,run,tid,indices in specifications:
        p=compressed(report/'data/playback'/run/(tid+'.json.gz'))
        records[name]=dict(key=run+'/'+tid,checkpoints=[state_at(p,i) for i in indices])
    identity=records['identity']['checkpoints']
    assert all('ROCK IS ROCK' in s['rules'] for s in identity)
    assert all('ROCK NEVER IS FLAG' in s['rules'] for s in identity[1:])
    note=episodes[records['identity']['key']]['notebook_after']
    note=note.get('text','') if isinstance(note,dict) else note or ''
    assert 'Unwinnable as far as found' in note and 'ROCK IS ROCK' not in note
    moving=records['moving_target']['checkpoints']
    assert all(any(e[1]=='ghost' for e in s['entities']) for s in moving[:4])
    assert all(not any(e[1]=='ghost' for e in s['entities']) for s in moving[4:])
    assert not any(s['won'] for s in moving)
    note=episodes[records['moving_target']['key']]['notebook_after']
    note=note.get('text','') if isinstance(note,dict) else note or ''
    assert 'WEAK obj dies' in note and 'moves into baba' in note
    control=records['control_loss']['checkpoints']
    assert any('you' in e[7] for e in control[0]['entities'])
    assert all(not any('you' in e[7] for e in s['entities']) and 'LEVEL IS DEFEAT' in s['rules'] for s in control[1:])
    return records


def analyze(report,output,audit_output,annotations=None):
    summary=read(report/'data/summary.json');rows=[];episodes={};fingerprints=[]
    for run in summary['runs']:
        if not run['main']:continue
        for outcome in run['outcomes']:
            tid=outcome['task'];p=report/'data/playback'/run['id']/(tid+'.json.gz')
            playback=compressed(p);features=trajectory(playback)
            if features['actions']!=outcome['actions'] or bool(playback['frames'][-1]['won'])!=bool(outcome['won']):raise ValueError('Outcome mismatch')
            ep=report/'data/episodes'/run['id']/(tid+'.json.gz');episode=compressed(ep)
            key=run['id']+'/'+tid;episodes[key]=episode
            rows.append(dict(key=key,run=run['id'],model=run['model'],group=run['group'],label=run['label'],rep=run['rep'],task=tid,
                won=bool(outcome['won']),reference_moves=outcome['reference'],**features))
            fingerprints.append([key,hashlib.sha256(p.read_bytes()).hexdigest(),hashlib.sha256(ep.read_bytes()).hexdigest()])
    if len(rows)!=1575 or sum(not r['won'] for r in rows)!=1037:raise ValueError('Unexpected fixed cohort')
    rng=random.Random(20261121);selected=[]
    for run_id in sorted({r['run'] for r in rows}):
        candidates=sorted((r for r in rows if r['run']==run_id and not r['won']),key=lambda r:r['task'])
        selected.extend(rng.sample(candidates,3))
    selected.sort(key=lambda r:(r['label'],r['rep'],r['task']))
    packets=[]
    task_names={t['id']:t['name'] for t in summary['tasks']}
    for row in selected:
        episode=episodes[row['key']]
        text=[{k:e[k] for k in ('seq','at','type','text')} for e in episode['events'] if e['type'] in ('agent.message','agent.reasoning') and e.get('text')]
        packets.append(dict(**row,task_name=task_names[row['task']],commentary=text,
            notebook_before=episode.get('notebook_before'),notebook_after=episode.get('notebook_after')))
    audit_output.parent.mkdir(parents=True,exist_ok=True);write(audit_output,dict(seed=20261121,sample_size=63,packets=packets))
    groups=[]
    for group in summary['groups']:
        group_rows=[r for r in rows if r['group']==group['id']]
        groups.append(dict(id=group['id'],label=group['label'],color=group['color'],**aggregate(group_rows)))
    value=dict(schema='baba-lab.failure-analysis.v1',generated_at=datetime.now(timezone.utc).isoformat(),
        cohort_sha256=summary['cohort_sha256'],source_fingerprint=digest(fingerprints),
        analysis_code_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        scope='Fixed 21-campaign cohort only. No new model calls or campaign changes.',
        trajectory_labels=TRAJECTORIES,definitions=dict(
            long_wait='A consecutive suffix of wait commands occupies strictly more than half of all charged commands. Waits-only failures are separated.',
            unchanged_board='Visible entity identity, position, direction, words, properties and active text, rules, room offset and level direction are unchanged. Turn counters and hidden engine state are excluded.',
            revisit='A directional input reaches an earlier visible-board signature and changes the preceding visible board. Undo and restart commands themselves are excluded.',
            visible_you='Number of visible entities with the you property. A missing visible entity does not establish loss of all control; hidden state is unavailable in these compact playbacks.'),
        overall=aggregate(rows),groups=groups,
        campaigns=[dict(run=run_id,**aggregate([r for r in rows if r['run']==run_id])) for run_id in sorted({r['run'] for r in rows})],
        episodes=rows,sample=dict(seed=20261121,selection='Three failures sampled uniformly without replacement within each of 21 campaigns.',
            keys=[r['key'] for r in selected],size=63,per_configuration=9,
            caveats='The sample overweights configurations with fewer total failures. Report reviewed counts as sample descriptions, not pooled estimates of all failures. Single-reviewer labels are not an independent reliability study.'))
    if annotations and annotations.exists():
        annotation=read(annotations)
        validate_review(annotation,selected,episodes)
        value['review']=annotation
        value['review_counts']={label:sum(c['label']==label for c in annotation['cases'].values()) for label in annotation['codebook']}
        value['annotation_sha256']=hashlib.sha256(annotations.read_bytes()).hexdigest()
        value['case_studies']=case_studies(report,episodes)
    write(output,value)
    fields=['key','label','rep','task','trajectory','actions','directional','waits','undos','restarts','terminal_waits','before_terminal_wait',
            'wait_visible_changes','terminal_wait_visible_changes','final_visible_you','last_visible_you_action','reviewed_stopping_reason']
    with output.with_name('failure-classifications.csv').open('w',newline='') as stream:
        writer=csv.DictWriter(stream,fieldnames=fields,extrasaction='ignore');writer.writeheader()
        for row in rows:
            if not row['won']:
                reason=value.get('review',{}).get('cases',{}).get(row['key'],{}).get('label','not_reviewed')
                writer.writerow(dict(row,reviewed_stopping_reason=reason))
    print(json.dumps(dict(overall=value['overall'],groups=groups,sample_cases=63,
        sample_commentary_characters=sum(len(e['text']) for p in packets for e in p['commentary']))),flush=True)
    return value


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--report',type=Path,default=ROOT/'.local/website-integration/writing/baba-is-benchmark')
    parser.add_argument('--output',type=Path,default=ROOT/'reports/continuous-campaign/data/failure-analysis.json')
    parser.add_argument('--audit-output',type=Path,default=ROOT/'.local/failure-audit-packets.json')
    parser.add_argument('--annotations',type=Path,default=ROOT/'benchmarks/failure-audit-20261121.json')
    args=parser.parse_args();analyze(args.report,args.output,args.audit_output,args.annotations)
