"""Orchestrate real native gameplay against the untouched-world two-slot server.

The gameplay driver must use the native PAD control harness. This server layer
never calls native reward/check methods, manufactures AP packets or changes seed
placements. Missing gameplay gates remain failures in its evidence index.
"""
from __future__ import annotations
import argparse
import asyncio
import copy
import importlib.util
import json
import logging
import os
from pathlib import Path
import subprocess
import sys
import time
import zipfile
from test_real_server import AP_REVISION, ROOT, sha, until

PRISTINE_PACKAGES = None

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

class RealAPSession:
    """AP/companion lifecycle and evidence; gameplay belongs to the PAD driver."""
    def __init__(self, args, ctx, endpoint, patches, output):
        self.args, self.ctx, self.endpoint, self.patches, self.output = args, ctx, endpoint, patches, output
        self.runs = {s: {'directory':output/f'run-{s}', 'profile':output/f'run-{s}/profile.json',
                         'save':output/f'run-{s}/save', 'slot':s} for s in (1,2)}
        self.clients = {}
        self.logs = []
        self.log_tasks = []
        self.cleanups = []
        self.events = []
        self.gates = {name:{'passed':False, 'evidence':[], 'shortcuts':[],
                            'remaining':'not exercised by the production gameplay driver'} for name in GATES}
        self.catalog = json.loads((ROOT/'contract.json').read_text(encoding='utf8'))
        self.items = {i['id']:i for i in self.catalog['items']}
        self.started = time.monotonic()

    def event(self, label, **data):
        row={'seconds':round(time.monotonic()-self.started,3), 'label':label, **data}
        self.events.append(row)
        with (self.output/'orchestration.jsonl').open('a',encoding='utf8') as stream:
            stream.write(json.dumps(row)+'\n')

    def mark_gate(self, name, passed, evidence, shortcuts=(), remaining=None):
        if name not in self.gates:
            raise ValueError(f'unknown acceptance gate {name}')
        if passed and not evidence:
            raise ValueError(f'{name} requires concrete retained evidence')
        self.gates[name]={'passed':bool(passed), 'evidence':evidence, 'shortcuts':list(shortcuts),
                          'remaining':remaining if not passed else None}
        self.event('gate', name=name, result=self.gates[name])

    async def prepare(self):
        for slot,run in self.runs.items():
            run['save'].mkdir(parents=True)
            process=await asyncio.create_subprocess_exec(str(self.args.client.resolve()), 'prepare',
                str(self.patches[slot][0]), '--endpoint',self.endpoint,'--run-dir',str(run['directory']),
                '--save',f'gameplay-selected-save-{slot}',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
            out,err=await process.communicate()
            (self.output/f'prepare-{slot}.stdout.txt').write_bytes(out)
            (self.output/f'prepare-{slot}.stderr.txt').write_bytes(err)
            if process.returncode:
                raise AssertionError(err.decode(errors='replace'))
            prepared=json.loads((run['directory']/'bridge/runtime-config.json').read_text(encoding='utf8'))
            assert prepared['patch']==self.patches[slot][1]
            self.event('prepared-original-patch',slot=slot,patch_sha256=sha(self.patches[slot][0]))

    async def _client_log(self, slot, phase, process):
        # RunnerWorker emits a full view model every tick. Retain meaningful
        # changes without generating gigabytes of duplicate location lists.
        path=self.output/f'client-{slot}-{phase}.jsonl'
        last=None
        with path.open('w',encoding='utf8') as stream:
            while data:=await process.stdout.readline():
                raw=data.decode(errors='replace').rstrip()
                try:
                    row=json.loads(raw)
                    projected={k:row.get(k) for k in ('ap','delivery','delivery_detail','goal','process','ledger',
                                                     'receive_cursor','gameplay_ready','blocked','locations','seed')}
                    activity=row.get('activity',[])
                    projected['last_activity']=activity[-1] if activity else None
                except ValueError:
                    projected={'text':raw}
                if projected!=last:
                    stream.write(json.dumps(projected)+'\n')
                    stream.flush()
                    last=projected

    async def start_client(self, slot, phase='initial'):
        assert slot not in self.clients
        error=(self.output/f'client-{slot}-{phase}.stderr.txt').open('wb')
        self.logs.append(error)
        mode='--gui-worker-smoke' if self.args.gui_worker else '--headless'
        command=[str(self.args.client.resolve()),str(self.runs[slot]['profile']),mode]
        if self.args.gui_worker:
            command+=['--ticks',str(int(self.args.timeout*40)+2000)]
        process=await asyncio.create_subprocess_exec(*command,stdout=asyncio.subprocess.PIPE,stderr=error,
            limit=2**20,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
        self.clients[slot]=process
        self.log_tasks.append(asyncio.create_task(self._client_log(slot,phase,process)))
        self.event('companion-started',slot=slot,phase=phase,pid=process.pid)

    async def stop_client(self, slot):
        process=self.clients.pop(slot,None)
        if process and process.returncode is None:
            process.terminate()
            await process.wait()
        self.event('companion-stopped',slot=slot)

    async def reconnect(self):
        previous={s:set(self.ctx.clients[0][s]) for s in (1,2)}
        assert all(previous.values()),'both slots must be authenticated before interruption'
        await asyncio.gather(*(ep.socket.close() for ep in list(self.ctx.endpoints)))
        await until(lambda:all(any(c not in previous[s] for c in self.ctx.clients[0][s]) for s in (1,2)),
                    'both actual AP socket reconnections',timeout=20)
        self.event('both-ap-slots-reconnected')

    def expected_rewards(self):
        rewards={1:[],2:[]}
        for source in (1,2):
            for location in sorted(self.ctx.location_checks[0,source]):
                item,receiver,flags=self.ctx.locations[source][location]
                rewards[receiver].append({'item_id':item,'name':self.items[item]['name'],
                    'source':source,'location':location,'value':self.items[item]['value']})
        return rewards

    def native_journal(self, slot):
        return json.loads((self.runs[slot]['directory']/'bridge/native-state.json').read_text(encoding='utf8'))

    def client_journal(self, slot):
        return json.loads((self.runs[slot]['directory']/'journal.json').read_text(encoding='utf8'))

    async def wait_checks(self, checks, timeout=30):
        await until(lambda:all(set(locations)<=self.ctx.location_checks[0,int(slot)] for slot,locations in checks.items()),
                    'actual gameplay checks on AP server',timeout=timeout)
        self.event('server-checks',checks={str(s):sorted(self.ctx.location_checks[0,s]) for s in (1,2)})

    async def wait_rewards(self, timeout=30):
        def delivered():
            expected=self.expected_rewards()
            try:
                for slot in (1,2):
                    state=self.native_journal(slot)
                    actual=sorted(r['payload']['item_id'] for r in state['receipts'].values())
                    if actual!=sorted(r['item_id'] for r in expected[slot]):return False
            except (OSError,KeyError,ValueError):return False
            return True
        await until(delivered,'real generated native receipts',timeout=timeout)
        self.event('native-generated-receipts',rewards=self.expected_rewards())

    def assert_native_reward_state(self, slot, observation):
        """Requires actual native getter readback supplied by the gameplay harness."""
        state=self.native_journal(slot)
        expected=self.expected_rewards()[slot]
        assert observation['pokos']==state.get('base_pokos',0)+state.get('corpse_pokos',0)+sum(r['value'] for r in expected)
        mask=0
        for reward in expected:
            item=self.items[reward['item_id']]
            if item['explorer_kit']:mask|=1<<item['native_id']
        assert observation['equipment']==mask
        assert set(state['checks'])==self.ctx.location_checks[0,slot]

    def register_cleanup(self, callback):
        self.cleanups.append(callback)

    async def close(self):
        for callback in reversed(self.cleanups):
            try:
                result=callback()
                if result is not None:await result
            except Exception as error:
                self.event('gameplay-cleanup-error',error=f'{type(error).__name__}: {error}')
        for slot in list(self.clients):await self.stop_client(slot)
        await asyncio.gather(*self.log_tasks,return_exceptions=True)
        for stream in self.logs:stream.close()

async def run_acceptance(session, driver):
    """Start with the normal first-day route; extend only with proved actions."""
    games={}
    entry={}
    carrying={}
    for slot,run in session.runs.items():
        game=driver.GameplayClient(session.args.native.resolve(), session.args.assets.resolve(),
            run['profile'],run['directory']/'gameplay-control',run['save'],
            session.output/f'gameplay-{slot}.log')
        games[slot]=game
        session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        session.event('native-normal-engine-started',slot=slot)
        entry_route=await asyncio.to_thread(driver.boot_day1,game,timeout=240)
        state=entry_route["state"]
        assert state['ready'] is True and state['course']==0 and state['cave']==0
        assert state['navi'] and state['pellets'] and state['onyons'], 'real loaded actor managers are required'
        entry[str(slot)]=entry_route
    session.mark_gate('normal_entry',True,entry,
        shortcuts=['scripted normal PAD inputs; no controller hardware or visual-usability judgment'])
    for slot,game in games.items():
        before=await asyncio.to_thread(game.wait_state,lambda s:s.get('ready'),30,'live first-day actors')
        carry_route=await asyncio.to_thread(driver.carry_courage,game,timeout=900)
        after=carry_route['state']
        native=session.native_journal(slot)
        assert after['delivery_count']>before['delivery_count'], 'real Onyon delivery caller must run'
        if 'physical_deliveries' in after:
            assert after['physical_deliveries'].get('1',0)>before.get('physical_deliveries',{}).get('1',0)
        else:
            assert after['last_delivery_location']==1, 'unrelated delivery cannot stand in for Courage delivery'
        assert 1 in native['checks'] and not native['receipts']
        assert after['pokos']==native.get('base_pokos',0)+native.get('corpse_pokos',0), 'vanilla randomized value escaped suppression'
        carrying[str(slot)]={'before':before,'after':after,'native_checks':native['checks'],
                             'route':carry_route,'input_trace':str(session.output/f'gameplay-{slot}.log')}
    session.mark_gate('carrying',True,carrying,
        shortcuts=['scripted PAD steering; actual captain/Pikmin/pellet simulation and Onyon delivery'])
    for slot in (1,2):await session.start_client(slot)
    await session.wait_checks({1:[1],2:[1]},timeout=60)
    await session.wait_rewards(timeout=60)
    local={}
    for slot,game in games.items():
        state=await asyncio.to_thread(game.wait_state,lambda s:True)
        session.assert_native_reward_state(slot,state)
        local[str(slot)]={'state':state,'generated_rewards':session.expected_rewards()[slot]}
    session.event('actual-first-day-local-rewards',evidence=local)
    # Remote cave delivery and progression have separate routes. Local first-day
    # receipts alone cannot fill that combined gate.
    session.mark_gate('local_remote_delivery',False,{'local':local},
        remaining='generated remote gameplay route not yet exercised')
    saves={}
    for slot,game in games.items():
        assert hasattr(driver,'finish_day_and_save'),'normal card route requires actual menu policy'
        saves[str(slot)]=await asyncio.to_thread(driver.finish_day_and_save,game,timeout=240)
        state=saves[str(slot)]['state']
        assert state['card_saves']>0 and not state['card_failures'] and state['game_state']==1
    persisted={s:session.native_journal(s) for s in (1,2)}
    for slot,game in games.items():
        await session.stop_client(slot)
        await asyncio.to_thread(game.shutdown)
    resumed={}
    for slot,configured in session.runs.items():
        game=driver.GameplayClient(session.args.native.resolve(),session.args.assets.resolve(),
            configured['profile'],configured['directory']/'gameplay-control-resume',configured['save'],
            session.output/f'gameplay-{slot}-resume.log')
        games[slot]=game
        session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        await session.start_client(slot,phase='ordinary-card-resume')
        route=await asyncio.to_thread(driver.boot_day1,game,timeout=240)
        state=route['state']
        assert state['card_loads']>0 and not state['card_failures'], 'normal native file-select/card load must finish'
        assert state['native_save_count']>=saves[str(slot)]['state']['native_save_count']>0
        assert state['day']>=saves[str(slot)]['state']['day'], 'ordinary loaded campaign day regressed'
        assert not any(p['location_id']==1 for p in state['pellets']), 'ordinary saved physical Courage pickup was lost'
        journal=session.native_journal(slot)
        assert journal['receipts']==persisted[slot]['receipts'] and journal['checks']==persisted[slot]['checks']
        assert journal.get('corpse_pokos',0)==persisted[slot].get('corpse_pokos',0)
        session.assert_native_reward_state(slot,state)
        resumed[str(slot)]={'route':route,'journal':journal}
    session.mark_gate('card_save_load_restart',True,dict(actual_card_saves=saves,resumed=resumed),
        shortcuts=['scripted normal menu/controller input; real MemoryCard save and file-select load, native/companion process restart'])
    return games

async def run(args, acceptance=run_acceptance, scope_gates=GATES, boundary=None, acceptance_kind='normal_gameplay'):
    global PRISTINE_PACKAGES
    import unittest  # AP's isolated test-world filter
    os.environ['AP_TEST_WORLDS']='generic'
    os.environ['SKIP_REQUIREMENTS_UPDATE']='1'
    assert sys.version_info[:2]==(3,12),'use the pinned AP Python3.12 environment'
    revision=subprocess.check_output(['git','-C',str(args.ap_root),'rev-parse','HEAD'],text=True).strip()
    assert revision==AP_REVISION
    sys.path.insert(0,str(args.ap_root.resolve()))
    import MultiServer
    import websockets
    import worlds
    if PRISTINE_PACKAGES is None:PRISTINE_PACKAGES=copy.deepcopy(worlds.network_data_package)
    worlds.network_data_package=copy.deepcopy(PRISTINE_PACKAGES)
    output=args.output.resolve()
    output.mkdir(parents=True,exist_ok=False)
    logging.basicConfig(filename=output/'server.log',level=logging.INFO)
    multidata=next(args.fixture.glob('*.archipelago'))
    ctx=MultiServer.Context('127.0.0.1',0,'','',0,0,False)
    ctx.load(str(multidata.resolve()))
    assert {s:i.name for s,i in ctx.slot_info.items()}=={1:'P2Pilot1',2:'P2Pilot2'}
    patches={}
    for path in args.fixture.glob('*.appik2'):
        with zipfile.ZipFile(path) as archive:patch=json.loads(archive.read('patch.appik2'))
        patches[patch['slot']]=(path.resolve(),patch)
    assert set(patches)=={1,2}
    assert all(p['seed']==ctx.seed_name for _,p in patches.values())
    route_manifest=json.loads(args.route_manifest.read_text(encoding='utf8'))
    assert route_manifest['format']=='pikmin2-production-gameplay-route-v1'
    assert route_manifest['primary_seed']==ctx.seed_name
    assert set(route_manifest['required_gates'])==set(GATES)
    generation_path=args.fixture.parent/'generation-report.json'
    generation=json.loads(generation_path.read_text(encoding='utf8'))
    assert generation['ap_revision']==revision
    assert generation['apworld_sha256']==route_manifest['apworld_sha256']
    original_world=ROOT.parent/'sources/upstream-apworld/pikmin2-v0.9.1.apworld'
    assert sha(original_world)==generation['apworld_sha256'],'original APWorld bytes changed'
    implementation_paths={Path(__file__).resolve(),Path(sys.modules[acceptance.__module__].__file__).resolve()}
    for module_name in ('test_real_server','test_loaded_gameplay_real_server'):
        module=sys.modules.get(module_name)
        if module is not None:implementation_paths.add(Path(module.__file__).resolve())
    implementation_hashes={str(path):sha(path) for path in sorted(implementation_paths)}
    source_snapshot=output/'executed-orchestration'
    source_snapshot.mkdir()
    for path in implementation_paths:(source_snapshot/path.name).write_bytes(path.read_bytes())
    driver_source=args.driver.resolve()
    frozen_driver=output/'executed-driver.py'
    frozen_driver.write_bytes(driver_source.read_bytes())
    initial_hashes={'native':sha(args.native),'client':sha(args.client),'driver':sha(frozen_driver),'route':sha(args.route_manifest)}
    native_runtime={path.name:sha(path) for path in args.native.parent.glob('*.dll')}
    (output/'executed-route.json').write_bytes(args.route_manifest.read_bytes())
    spec=importlib.util.spec_from_file_location('p2_production_gameplay_driver',frozen_driver)
    driver=importlib.util.module_from_spec(spec)
    sys.modules[spec.name]=driver
    spec.loader.exec_module(driver)
    if not all(hasattr(driver,name) for name in ('GameplayClient','boot_day1','carry_courage')):
        raise RuntimeError('PAD driver must expose GameplayClient, boot_day1 and carry_courage')
    session=None
    failure=None
    try:
        async with websockets.serve(lambda socket,path:MultiServer.server(socket,path,ctx=ctx),'127.0.0.1',0) as server:
            ctx.server=server
            endpoint=f'ws://127.0.0.1:{server.sockets[0].getsockname()[1]}'
            session=RealAPSession(args,ctx,endpoint,patches,output)
            await session.prepare()
            async with asyncio.timeout(args.timeout):
                await acceptance(session,driver)
    except BaseException as error:
        failure=f'{type(error).__name__}: {error}'
        raise
    finally:
        if session:
            await session.close()
            unchanged={key:sha(path)==initial_hashes[key] for key,path in (('native',args.native),('client',args.client),('driver',frozen_driver),('route',args.route_manifest))}
            unchanged['orchestration']=all(sha(Path(path))==digest for path,digest in implementation_hashes.items())
            unchanged['native_runtime']=native_runtime=={path.name:sha(path) for path in args.native.parent.glob('*.dll')}
            if not all(unchanged.values()):failure=failure or 'execution inputs changed during acceptance run'
            report={'status':'passed' if not failure and all(session.gates[g]['passed'] for g in scope_gates) else 'failed',
                'scope_gates':list(scope_gates),'acceptance_kind':acceptance_kind,
                'orchestration_sha256':implementation_hashes,
                'native_sha256':initial_hashes['native'],'client_sha256':initial_hashes['client'],'ap_revision':revision,
                'native_runtime_sha256':native_runtime,
                'toolkit_revision':'ac39b39f296b073553ecd4f9c486b9d14beda9eb','multidata_sha256':sha(multidata),
                'apworld_sha256':generation['apworld_sha256'],'generation_report_sha256':sha(generation_path),
                'catalog_sha256':sha(ROOT/'contract.json'),'driver_sha256':initial_hashes['driver'],
                'driver_source':str(driver_source),'executed_driver':str(frozen_driver),
                'route_manifest_sha256':initial_hashes['route'],'execution_inputs_unchanged':unchanged,
                'patches':{str(s):sha(path) for s,(path,_) in patches.items()},
                'boundary':boundary or 'real original-world AP server, production companion and real native engine controlled through normal PAD and virtual SDL-controller input',
                'shortcuts':'enumerated per gameplay gate; earlier direct-callback fixtures are historical only',
                'gates':session.gates,'events':session.events,'failure':failure,
                'worker':'GUI RunnerWorker' if args.gui_worker else 'headless Runner'}
            (output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')
            print(json.dumps({'status':report['status'],'gates':{k:v['passed'] for k,v in report['gates'].items()},
                              'report':str(output/'report.json'),'failure':failure},indent=2))
    if session and report['status']!='passed':
        raise AssertionError('production gameplay acceptance remains incomplete; see report gates')
    return report

def make_parser(description=__doc__):
    parser=argparse.ArgumentParser(description=description)
    parser.add_argument('--ap-root',type=Path,required=True)
    parser.add_argument('--fixture',type=Path,default=ROOT/'tests/fixtures/pokos280-2026101503/generated')
    parser.add_argument('--client',type=Path,required=True)
    parser.add_argument('--native',type=Path,required=True)
    parser.add_argument('--assets',type=Path,required=True,help='private working directory containing the extracted assets/ tree')
    default_driver=ROOT/'tools/test_gameplay_control.py'
    if not default_driver.is_file():default_driver=ROOT.parent/'native/tools/test_gameplay_control.py'
    parser.add_argument('--driver',type=Path,default=default_driver)
    parser.add_argument('--output',type=Path,required=True)
    parser.add_argument('--route-manifest',type=Path,default=ROOT/'tests/gameplay-acceptance-route.json')
    parser.add_argument('--timeout',type=int,default=1800)
    parser.add_argument('--gui-worker',action='store_true')
    return parser

if __name__=='__main__':
    asyncio.run(run(make_parser().parse_args(),scope_gates=('normal_entry','carrying','card_save_load_restart')))
