"""Seal completed normal gameplay gates while their continuation is still live.

This observes the executing orchestration event stream at the normal-phase
boundary. It never promotes a failed final report or credits an unfinished gate.
The runtime must match an independently passing exact-runtime scope report.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import time

PHASE=('normal_entry','carrying','card_save_load_restart')
GATES=PHASE+('local_remote_delivery','progression','water_blue_only','physical_replacements','reconnect','original_goals')


def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


def phase_events(path):
    events=[]
    for line in path.read_text(encoding='utf8').splitlines():
        try:events.append(json.loads(line))
        except json.JSONDecodeError:break # writer may be between write/flush
    found={}
    for event in events:
        if event.get('label')=='gate' and event.get('name') in PHASE:
            value=event.get('result',{})
            if not value.get('passed') or not value.get('evidence'):
                raise AssertionError('normal phase contains a failed or empty gate')
            found[event['name']]=event
        if len(found)==len(PHASE):return found,event['seconds']
    return None,None


def bind_inputs(run_dir,tools,native,client,reference):
    assert reference['status']=='passed' and all(reference['execution_inputs_unchanged'].values())
    assert sha(native)==reference['native_sha256']
    assert sha(client)==reference['client_sha256']
    runtime={p.name:sha(p) for p in native.parent.glob('*.dll')}
    assert runtime==reference['native_runtime_sha256']
    snapshots=run_dir/'executed-orchestration'
    helpers={str(tools/p.name):sha(p) for p in snapshots.glob('*.py')}
    assert helpers,'missing retained executed orchestration'
    assert all(Path(path).is_file() and sha(Path(path))==digest for path,digest in helpers.items()),'executed helper changed'
    route=run_dir/'executed-route.json'
    assert sha(route)==reference['route_manifest_sha256'],'normal route differs from frozen primary manifest'
    driver=run_dir/'executed-driver.py'
    assert driver.is_file()
    return dict(native_sha256=sha(native),client_sha256=sha(client),native_runtime_sha256=runtime,
        driver_sha256=sha(driver),route_manifest_sha256=sha(route),orchestration_sha256=helpers)


def seal(args):
    reference=json.loads(args.runtime_reference.read_text(encoding='utf8'))
    initial=bind_inputs(args.run,args.tools,args.native,args.client,reference)
    assert not args.output.exists(),'phase receipt is immutable once written'
    deadline=time.monotonic()+args.timeout
    while time.monotonic()<deadline:
        events,cutoff=phase_events(args.run/'orchestration.jsonl')
        if events:
            final=bind_inputs(args.run,args.tools,args.native,args.client,reference)
            assert final==initial,'normal phase execution inputs changed during observation'
            gates={name:{'passed':False,'evidence':[],'shortcuts':[],
                         'remaining':'outside the sealed normal phase'} for name in GATES}
            for name,event in events.items():gates[name]=event['result']
            report=dict(format='pikmin2-live-normal-phase-v1',status='passed',scope_gates=list(PHASE),
                acceptance_kind='normal_gameplay',**final,
                execution_inputs_unchanged={key:True for key in ('native','client','native_runtime','driver','route','orchestration')},
                gates=gates,phase_event_cutoff_seconds=cutoff,
                source_event_stream=str(args.run/'orchestration.jsonl'),
                source_event_prefix_sha256=hashlib.sha256(json.dumps(events,sort_keys=True).encode()).hexdigest(),
                observer_sha256=sha(Path(__file__)),runtime_reference_sha256=sha(args.runtime_reference),
                ap_revision=reference['ap_revision'],toolkit_revision=reference['toolkit_revision'],
                apworld_sha256=reference['apworld_sha256'],catalog_sha256=reference['catalog_sha256'],
                boundary='completed normal entry/carry/MemoryCard/restart phase of the live original-world two-slot AP run; later progression is a separate scope',
                events=list(events.values()),failure=None)
            args.output.write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')
            return report
        if (args.run/'report.json').exists():
            raise AssertionError('execution ended before a live normal-phase boundary was sealed')
        time.sleep(.2)
    raise TimeoutError('normal phase has not completed')


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--run',type=Path,required=True)
    parser.add_argument('--tools',type=Path,default=Path(__file__).parent)
    parser.add_argument('--native',type=Path,required=True)
    parser.add_argument('--client',type=Path,required=True)
    parser.add_argument('--runtime-reference',type=Path,required=True)
    parser.add_argument('--output',type=Path,required=True)
    parser.add_argument('--timeout',type=int,default=7200)
    args=parser.parse_args()
    print(json.dumps({'status':seal(args)['status'],'report':str(args.output)},indent=2))
