"""Offline prompt, notebook, experimentation and recovery analysis of fixed runs."""
import argparse
import ast
from collections import Counter
from datetime import datetime,timezone
import difflib
import gzip
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import statistics

ROOT=Path(__file__).resolve().parents[1]
MOVE={'l':'left','r':'right','u':'up','d':'down','p':'wait'}
MARKERS={
 'impossibility':r'\b(?:unwinnable|unsolvable|impossible)\b',
 'uncertainty':r'\b(?:hypothes\w*|untested|unclear|unknown|maybe|suspect\w*)\b',
 'confirmation':r'\b(?:confirmed|tested|verified|observed)\b',
 'budget_advice':r'\b(?:budget|moves?|actions?)\b',
 'has':r'\bHAS\b',
 'level_hazard_rule':r'LEVEL IS (?:WEAK|DEFEAT)',
}

def read(path):return json.loads(path.read_text())
def compressed(path):return json.loads(gzip.decompress(path.read_bytes()))
def note(value):return value.get('text','') if isinstance(value,dict) else value or ''
def digest(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
def median(values):return statistics.median(values) if values else None
def notebook_markers(text):return {k:bool(re.search(pattern,text,0 if k=='has' else re.I)) for k,pattern in MARKERS.items()}


def supplementary_notebooks(report,summary):
    """Recover writes after campaign completion, omitted by per-level log grouping."""
    destination=report/'data/notebook-postcampaign.json'
    if destination.exists():return read(destination)['events']
    sources=read(ROOT/'reports/continuous-campaign/.sources.json');events=[]
    for run in summary['runs']:
        if not run['main']:continue
        mapped=set()
        for outcome in run['outcomes']:
            ep=compressed(report/'data/episodes'/run['id']/(outcome['task']+'.json.gz'))
            mapped.update(e['revision'] for e in ep['events'] if e['type']=='notebook.updated')
        missing=set(range(1,run['notebook_revisions']+1))-mapped
        if not missing:continue
        path=Path(sources[run['id']])/'campaign.sqlite3'
        con=sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True)
        try:
            con.execute('BEGIN')
            final=[]
            for seq,raw in con.execute("SELECT seq,event FROM events WHERE json_extract(event,'$.type') IN ('notebook.updated','tool.completed') ORDER BY seq"):
                event=json.loads(raw);d=event.get('data',{})
                if event['type']=='tool.completed' and d.get('name')=='next_level' and d.get('response',{}).get('complete') and d.get('response',{}).get('ok'):final.append(seq)
                if event['type']=='notebook.updated' and d.get('revision') in missing:
                    if not final:raise ValueError('Unmapped write is not after campaign completion')
                    events.append(dict(run=run['id'],seq=seq,revision=d['revision'],text=d['text'],task=None,at=None,after_campaign=True,
                        source_event_sha256=hashlib.sha256(raw.encode()).hexdigest()))
        finally:con.close()
    destination.write_text(json.dumps(dict(schema='baba-lab.postcampaign-notebooks.v1',
        provenance='Read-only notebook.updated events after the final next_level, capped at each frozen campaign revision. No source database paths are exported.',events=events),ensure_ascii=False,indent=2)+'\n')
    return events


def inspect_playback(p):
    entities={};you=0;previous_you=None;first_undo=None;first_restart=None;restore=[];losses=[]
    for index,f in enumerate(p['frames']):
        for ident in f['removed']:you-=int('you' in entities.pop(ident)[7])
        for e in f['changed']:
            if e[0] in entities:you-=int('you' in entities[e[0]][7])
            entities[e[0]]=e;you+=int('you' in e[7])
        level_you='LEVEL IS YOU' in f['rules'];control=you>0 or level_you
        if previous_you is True and not control:losses.append(index)
        if previous_you is False and control:restore.append(dict(action=index,command=f['command']))
        if f['command']=='undo' and first_undo is None:first_undo=index
        if f['command']=='restart' and first_restart is None:first_restart=index
        previous_you=control
    n=len(p['frames'])-1
    last_loss=losses[-1] if losses and not previous_you else None
    return dict(first_undo=first_undo,first_restart=first_restart,visible_control_loss_actions=losses,
        restored_visible_control=restore,ends_without_visible_control=not previous_you,
        last_visible_control_loss=last_loss,
        recovery_after_last_loss=sum(f['command'] in ('undo','restart') for f in p['frames'][last_loss+1:]) if last_loss is not None else None,
        recorded_commands_after_first_restart=n-first_restart if first_restart is not None else None)


def build(report,output):
    summary=read(report/'data/summary.json');failures=read(report/'data/failure-analysis.json')
    supplementary=supplementary_notebooks(report,summary)
    features={r['key']:r for r in failures['episodes']};campaigns=[];rows=[];episodes={};versions=[];prompt_errors=[];fingerprints=[]
    for run in summary['runs']:
        if not run['main']:continue
        writes=[];reads=[];tool_waits=0;all_inputs=[];first_next_errors=[];rejected_writes=[]
        for outcome in run['outcomes']:
            tid=outcome['task'];key=run['id']+'/'+tid;ep_path=report/'data/episodes'/run['id']/(tid+'.json.gz')
            playback_path=report/'data/playback'/run['id']/(tid+'.json.gz')
            ep=compressed(ep_path);p=compressed(playback_path);episodes[key]=ep
            fingerprints.append([key,hashlib.sha256(ep_path.read_bytes()).hexdigest(),hashlib.sha256(playback_path.read_bytes()).hexdigest()])
            reconstructed=[]
            for event in ep['events']:
                if event['type']=='notebook.updated':
                    text=event['text'];writes.append(dict(task=tid,seq=event['seq'],at=event['at'],revision=event['revision'],text=text,
                        timing='during_level' if event['at']<outcome['actions'] else 'after_level',
                        before_future_gameplay=int(tid[-3:])<75 or event['at']<outcome['actions']))
                if event['type']!='tool.completed':continue
                name=event['name'];response=event.get('response',{});args=event.get('arguments',{})
                if name=='notebook_read' and response.get('ok'):
                    reads.append(dict(task=tid,revision=response['revision'],characters=len(response.get('text',''))))
                if name=='notebook_write' and not response.get('ok'):
                    rejected_writes.append(dict(task=tid,seq=event['seq'],error=response.get('error','')))
                if name=='next_level' and not response.get('ok'):
                    first_next_errors.append(dict(key=key,seq=event['seq'],at=event['at'],error=response.get('error','')))
                executed=response.get('executed',[]) if response.get('ok') else []
                if executed:
                    if name=='act':
                        requested=[MOVE[c] for c in args['moves']]
                        if executed!=requested[:len(executed)]:raise ValueError('Game inputs differ from agent requests: '+key)
                    elif name=='undo':
                        if any(c!='undo' for c in executed):raise ValueError('Wrong undo command')
                    elif name=='restart':
                        if executed!=['restart']:raise ValueError('Wrong restart command')
                    else:raise ValueError('Unknown mutating game tool')
                    reconstructed.extend(executed)
            commands=[f['command'] for f in p['frames'][1:]]
            if reconstructed!=commands:raise ValueError('Canonical tool calls differ from saved command trace: '+key)
            tool_waits+=commands.count('wait');all_inputs.extend(commands)
            recovered=inspect_playback(p)
            recovered['remaining_budget_after_first_restart']=summary['settings']['reference_multiplier']*outcome['reference']-recovered['first_restart'] if recovered['first_restart'] is not None else None
            rows.append(dict(key=key,run=run['id'],model=run['model'],label=run['label'],rep=run['rep'],task=tid,won=outcome['won'],
                actions=outcome['actions'],reference=outcome['reference'],undos=outcome['undos'],restarts=outcome['restarts'],
                **recovered))
        writes.extend(dict(task=None,seq=e['seq'],at=None,revision=e['revision'],text=e['text'],timing='after_campaign',before_future_gameplay=False) for e in supplementary if e['run']==run['id'])
        writes.sort(key=lambda w:w['seq'])
        if len(writes)!=run['notebook_revisions']:raise ValueError('Notebook revision count mismatch: '+run['id'])
        previous='';previous_markers={k:False for k in MARKERS};revision_rows=[]
        for w in writes:
            text=w['text'];markers=notebook_markers(text)
            delta=list(difflib.ndiff(previous.splitlines(),text.splitlines()))
            revision=dict(run=run['id'],model=run['model'],rep=run['rep'],**w,characters=len(text),sha256=hashlib.sha256(text.encode()).hexdigest(),markers=markers,
                added_lines=[line[2:] for line in delta if line.startswith('+ ')],removed_lines=[line[2:] for line in delta if line.startswith('- ')],
                introduced_markers=[k for k in MARKERS if markers[k] and not previous_markers[k]])
            revision_rows.append(revision);versions.append(revision);previous=text;previous_markers=markers
        final=previous
        campaigns.append(dict(run=run['id'],model=run['model'],label=run['label'],rep=run['rep'],wins=run['wins'],writes=len(writes),
            reads=len(reads),nonempty_reads=sum(r['characters']>0 for r in reads),max_characters=max([len(w['text']) for w in writes]+[0]),
            final_characters=len(final),final_markers=notebook_markers(final),
            writes_before_future_gameplay=sum(w['before_future_gameplay'] for w in writes),write_timing=dict(Counter(w['timing'] for w in writes)),
            markers_ever={k:any(w['markers'][k] for w in revision_rows) for k in MARKERS},
            rejected_advances=len(first_next_errors),wait_commands=tool_waits,rejected_notebook_writes=rejected_writes))
        prompt_errors.extend(first_next_errors)
    if len(rows)!=1575:raise ValueError('Wrong cohort')
    outcome_groups={}
    for won in (True,False):
        rr=[r for r in rows if bool(r['won'])==won];recovery=[r for r in rr if r['undos']+r['restarts']>0]
        outcome_groups['wins' if won else 'failures']=dict(attempts=len(rr),with_recovery=len(recovery),
            undo_commands=sum(r['undos'] for r in rr),restart_commands=sum(r['restarts'] for r in rr),
            with_undo=sum(r['undos']>0 for r in rr),with_restart=sum(r['restarts']>0 for r in rr),
            restored_visible_control_by_recovery=sum(any(e['command'] in ('undo','restart') for e in r['restored_visible_control']) for r in rr),
            with_any_visible_control_loss=sum(bool(r['visible_control_loss_actions']) for r in rr))
    groups=[]
    for group in summary['groups']:
        cc=[c for c in campaigns if c['run'] in group['runs']];rr=[r for r in rows if r['run'] in group['runs']]
        groups.append(dict(id=group['id'],label=group['label'],campaigns=len(cc),writes=sum(c['writes'] for c in cc),
            reads=sum(c['reads'] for c in cc),nonempty_reads=sum(c['nonempty_reads'] for c in cc),
            campaigns_with_writes=sum(c['writes']>0 for c in cc),max_characters=max(c['max_characters'] for c in cc),
            writes_before_future_gameplay=sum(c['writes_before_future_gameplay'] for c in cc),
            campaigns_with_impossibility_notes=sum(c['markers_ever']['impossibility'] for c in cc),
            campaigns_with_uncertainty_markers=sum(c['markers_ever']['uncertainty'] for c in cc),
            recovery_wins=sum(r['won'] and r['undos']+r['restarts']>0 for r in rr),
            recovery_failures=sum(not r['won'] and r['undos']+r['restarts']>0 for r in rr)))
    no_control=[r for r in rows if not r['won'] and r['ends_without_visible_control']]
    restart_rows=[r for r in rows if r['first_restart'] is not None]
    campaign_source=ROOT/'baba_env/benchmark/campaign.py'
    prompt_source=next(ast.literal_eval(n.value) for n in ast.parse(campaign_source.read_text()).body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='PLAYER_PROMPT' for t in n.targets))
    current_prompt=prompt_source.format(notebook_characters=summary['settings']['notebook_characters'],subagents='disabled')
    if current_prompt!=summary['prompt']:raise ValueError('Current prompt differs from frozen player instructions')
    value=dict(schema='baba-lab.learning-analysis.v1',generated_at=datetime.now(timezone.utc).isoformat(),cohort_sha256=summary['cohort_sha256'],
        source_fingerprint=digest(fingerprints),code_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        prompt_audit=dict(prompt=summary['prompt'],prompt_sha256=hashlib.sha256(summary['prompt'].encode()).hexdigest(),settings=summary['settings'],
            all_1575_command_traces_match_agent_tool_requests=True,wait_commands=sum(c['wait_commands'] for c in campaigns),
            rejected_advances=len(prompt_errors),episodes_with_rejected_advances=len({e['key'] for e in prompt_errors}),advance_errors=prompt_errors),
        notebooks=dict(committed_versions=len(versions),campaigns_with_writes=sum(c['writes']>0 for c in campaigns),
            campaigns_without_writes=sum(c['writes']==0 for c in campaigns),max_characters=max(c['max_characters'] for c in campaigns),
            post_campaign_versions=len(supplementary),campaigns_writing_before_future_gameplay=sum(c['writes_before_future_gameplay']>0 for c in campaigns),
            post_campaign_export_sha256=hashlib.sha256((report/'data/notebook-postcampaign.json').read_bytes()).hexdigest(),
            write_timing=dict(Counter(v['timing'] for v in versions)),
            rejected_in_level_writes=[dict(run=c['run'],**e) for c in campaigns for e in c['rejected_notebook_writes']],
            marker_definitions=MARKERS,marker_campaign_counts={k:sum(c['markers_ever'][k] for c in campaigns) for k in MARKERS},
            marker_version_counts={k:sum(v['markers'][k] for v in versions) for k in MARKERS},
            caveat='Literal text markers are not semantic correctness scores. Versions within a campaign are dependent; native context can retain information without notebook reads.'),
        groups=groups,campaigns=campaigns,versions=versions,recovery=dict(by_outcome=outcome_groups,
            final_no_visible_control_failures=len(no_control),no_recovery_after_last_visible_control_loss=sum(r['recovery_after_last_loss']==0 for r in no_control),
            attempts_with_restart=len(restart_rows),first_restart_later_than_reference_remaining=sum(r['remaining_budget_after_first_restart']<r['reference'] for r in restart_rows),
            caveat='Recovery use and outcomes are associations. Task difficulty and earlier mistakes determine when recovery is needed; these records do not estimate its causal benefit. Visible control excludes hidden entities.'),episodes=rows)
    value['prompt_audit']['current_prompt_matches_frozen']=True
    value['prompt_audit']['source_files']=[dict(file=str(p.relative_to(ROOT)),sha256=hashlib.sha256(p.read_bytes()).hexdigest()) for p in (campaign_source,ROOT/'baba_env/benchmark/native_agents.py')]
    output.parent.mkdir(parents=True,exist_ok=True);output.write_text(json.dumps(value,ensure_ascii=False,separators=(',',':'))+'\n')
    print(json.dumps({k:value[k] for k in ('groups','recovery')},ensure_ascii=False),flush=True)
    print(json.dumps(dict(notebooks=value['notebooks'],prompt_audit={k:v for k,v in value['prompt_audit'].items() if k not in ('prompt','settings','advance_errors')})),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/learning-analysis.json')
    args=parser.parse_args();build(args.report,args.output)
