"""Real generated two-slot AP server, production companion and native methods.

No packets, placements, received histories or acknowledgements are fabricated.
Native fixture substitutes world storage and invokes actual PlayData collection;
collision/carry/menu/MemoryCard commit and rendered gameplay remain unproved.
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
from pathlib import Path
import subprocess
import sys
import zipfile

ROOT = Path(__file__).resolve().parents[1]
AP_REVISION = '2fb9bdadd4726b404fc0d790887390b66b07df16'

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

async def until(predicate, label, timeout=20):
    try:
        async with asyncio.timeout(timeout):
            while not predicate():
                await asyncio.sleep(.05)
    except TimeoutError as error:
        raise AssertionError(f'timed out waiting for {label}') from error

class Native:
    def __init__(self, executable, profile, output, slot, phase):
        self.executable, self.profile = executable, profile
        self.output, self.slot, self.phase = output, slot, phase
        self.process = None
        self.trace = []

    async def start(self):
        self.error_file = (self.output / f'native-{self.slot}-{self.phase}.stderr.txt').open('wb')
        self.process = await asyncio.create_subprocess_exec(str(self.executable), '--ap-fixture', '--ap-profile',
            str(self.profile), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=self.error_file,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
        async with asyncio.timeout(30):
            while True:
                row = await self.line()
                if row and row.get('fixture_ready'):
                    return self

    async def line(self):
        data = await self.process.stdout.readline()
        if not data:
            raise RuntimeError(f'native slot{self.slot} closed output, returncode={self.process.returncode}')
        text = data.decode(errors='replace').rstrip()
        self.trace.append(text)
        try:
            value = json.loads(text)
        except ValueError:
            return None
        if isinstance(value, dict) and 'error' in value:
            raise AssertionError(value)
        return value if isinstance(value, dict) else None

    async def command(self, op, **fields):
        self.process.stdin.write((json.dumps(dict(op=op, **fields))+'\n').encode())
        await self.process.stdin.drain()
        async with asyncio.timeout(15):
            while True:
                row = await self.line()
                if row and row.get('op') == op:
                    assert row['failed'] is False, row
                    return row

    async def stop(self):
        if not self.process:
            return
        if self.process.returncode is None:
            try:
                self.process.stdin.write(b'{"op":"quit"}\n')
                await self.process.stdin.drain()
                self.process.stdin.close()
                await asyncio.wait_for(self.process.wait(), 10)
            except (BrokenPipeError, ConnectionResetError, TimeoutError):
                self.process.kill()
                await self.process.wait()
        self.error_file.close()
        (self.output / f'native-{self.slot}-{self.phase}.stdout.txt').write_text('\n'.join(self.trace)+'\n', encoding='utf-8')
        assert self.process.returncode == 0, f'native exit {self.process.returncode}'

async def smoke(args):
    import unittest  # AP explicit test-world loading filter
    os.environ['AP_TEST_WORLDS'] = 'generic'
    os.environ['SKIP_REQUIREMENTS_UPDATE'] = '1'
    if sys.version_info[:2] != (3,12):
        raise RuntimeError('use pinned Python3.12 AP 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
    output=args.output.resolve()
    output.mkdir(parents=True,exist_ok=False)
    logging.basicConfig(filename=output/'server.log',level=logging.INFO)
    catalog=json.loads((ROOT/'contract.json').read_text(encoding='utf-8'))
    items={i['id']:i for i in catalog['items']}
    locations={l['id']:l for l in catalog['locations'] if l['id']<=201}
    by_name={i['name']:i for i in items.values()}
    ctx=MultiServer.Context('127.0.0.1',0,'','',0,0,False)
    multidata=next(args.fixture.glob('*.archipelago'))
    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'))
        assert patch['win_condition']==1 and patch['poko_amount']==280
        patches[patch['slot']]=(path.resolve(),patch)
    assert set(patches)=={1,2}
    for slot in patches:
        assert not ctx.start_inventory[slot]
        assert set(ctx.locations[slot])==set(locations)
    native, clients, client_files={}, {}, []
    observations={}
    selected={1:{1,145},2:{1}}  # original VoR Courage Reactor; first ordinary route anchor
    # Exercise generated remote rewards and at least one globe's actual openCourse.
    remote_globes=[]
    for source in (1,2):
        for location, (item,receiver,flags) in ctx.locations[source].items():
            if source != receiver and item in (511,512):
                remote_globes.append((source,location,item,receiver))
                selected[source].add(location)
    assert remote_globes, 'seed must contain a generated remote globe'
    for target in (1,2):
        candidates=[(items[item]['value'],source,location) for source in (1,2)
                    for location,(item,receiver,flags) in ctx.locations[source].items()
                    if receiver==target and source!=target]
        _,source,location=max(candidates)
        selected[source].add(location)
    def expected():
        reward={1:[],2:[]}
        for source in (1,2):
            for location in ctx.location_checks[0,source]:
                item,receiver,flags=ctx.locations[source][location]
                reward[receiver].append((item,source,location))
        return reward
    def completed():
        reward=expected()
        for slot in (1,2):
            path=output/f'run-{slot}/bridge/native-state.json'
            try: state=json.loads(path.read_text(encoding='utf-8'))
            except (OSError,ValueError): return False
            if len(state['receipts'])!=len(reward[slot]): return False
        return True
    async def observe_all(phase):
        rows={slot:await native[slot].command('observe') for slot in (1,2)}
        for slot,row in rows.items():
            received=expected()[slot]
            assert row['pokos']==sum(items[item]['value'] for item,_,_ in received), (phase,slot,row,received)
            mask=0
            courses=1
            for item,_,_ in received:
                if items[item]['explorer_kit']:
                    mask|=1<<items[item]['native_id']
                    if item==511:courses|=2
                    if item==512:courses|=4
            assert row['equipment']==mask, (phase,slot,row,mask)
            assert row['courses']==courses, (phase,slot,row,courses)
            assert set(row['checks'])==ctx.location_checks[0,slot], (phase,slot,row)
            assert row['receipt_count']==len(received)
        observations[phase]=rows
        return rows
    async def start_client(slot,phase):
        stdout=(output/f'client-{slot}-{phase}.stdout.txt').open('wb')
        stderr=(output/f'client-{slot}-{phase}.stderr.txt').open('wb')
        client_files.extend([stdout,stderr])
        mode='--gui-worker-smoke' if args.gui_worker else '--headless'
        clients[slot]=await asyncio.create_subprocess_exec(str(args.client.resolve()),str(output/f'run-{slot}/profile.json'),
            mode,'--ticks','20000',stdout=stdout,stderr=stderr,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
    async def stop_client(slot):
        p=clients.pop(slot,None)
        if p and p.returncode is None:
            p.terminate()
            await p.wait()
    async def pickup(slot,location):
        name=locations[location]['name']
        physical=next(i for n,i in by_name.items() if name.endswith(' '+n))
        return await native[slot].command('pickup',text_id=physical['text_id'],cave=locations[location]['kind']!='overworld')
    async def check_delivery(label):
        await until(lambda: all(selected[s]<=ctx.location_checks[0,s] for s in (1,2)),label+' checks')
        await until(completed,label+' native receipts')
        await asyncio.sleep(.2)
        return await observe_all(label)
    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]}'
            # Reject private malformed selections against authentic server data;
            # neither packets nor the server's original slot fields are altered.
            async def rejected_selection(label, mutate, diagnostic):
                wrong_patch=output/f'rejection-only-{label}.appik2'
                with zipfile.ZipFile(patches[1][0]) as original, zipfile.ZipFile(wrong_patch,'w') as altered:
                    for name in original.namelist():
                        data=original.read(name)
                        if name=='patch.appik2':
                            doc=json.loads(data)
                            mutate(doc)
                            data=json.dumps(doc).encode()
                        altered.writestr(name,data)
                wrong_run=output/f'{label}-run'
                p=await asyncio.create_subprocess_exec(str(args.client.resolve()),'prepare',str(wrong_patch),
                    '--endpoint',endpoint,'--run-dir',str(wrong_run),'--save','selected-negative-control',
                    stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
                out,err=await p.communicate()
                assert p.returncode==0,err.decode(errors='replace')
                p=await asyncio.create_subprocess_exec(str(args.client.resolve()),str(wrong_run/'profile.json'),
                    '--headless','--ticks','100',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
                out,err=await p.communicate()
                (output/f'{label}-client.stdout.txt').write_bytes(out)
                (output/f'{label}-client.stderr.txt').write_bytes(err)
                assert p.returncode==0
                assert diagnostic.encode() in out, out.decode(errors='replace')
                assert not (wrong_run/'bridge/session.json').exists()
                assert not (wrong_run/'journal.json').exists()
                assert all(not ctx.location_checks[0,s] for s in (1,2))
                assert all(ctx.client_game_state[0,s]!=30 for s in (1,2))
            await rejected_selection('wrong-seed',lambda p:p.update(seed='different-seed-negative-control'),
                                     'AP game/seed/slot differs')
            def move_buried(p):
                first=next(loc for loc,item in p['items'].items() if item in catalog['buried_treasure'])
                second=next(loc for loc,item in p['items'].items() if item=='Remote')
                p['items'][first],p['items'][second]=p['items'][second],p['items'][first]
            await rejected_selection('wrong-buried',move_buried,'AP buried treasure locations differ')
            for slot in (1,2):
                run=output/f'run-{slot}'
                result=await asyncio.create_subprocess_exec(str(args.client.resolve()),'prepare',str(patches[slot][0]),
                    '--endpoint',endpoint,'--run-dir',str(run),'--save',f'pilot-selected-save-{slot}',
                    stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
                out,err=await result.communicate()
                assert result.returncode==0,err.decode(errors='replace')
                native[slot]=await Native(args.native.resolve(),run/'profile.json',output,slot,'initial').start()
                row=await native[slot].command('observe')
                assert row['pokos']==0 and row['goal'] is False and row['receipt_count']==0
                if slot==1:
                    rejected=await native[slot].command('pickup',text_id='fue_pullout',cave=True,
                        context={'course':2,'cave':2036281396,'floor':0})
                    assert rejected['checks']==[] and rejected['receipt_count']==0
                    assert rejected['pokos']==0 and rejected['equipment']==0
                    observations['incidental-noisemaker-floor-rejected']={slot:rejected}
                row=await pickup(slot,1)
                assert row['pokos']==0 and row['equipment']==0 and row['receipt_count']==0, 'physical reward must be suppressed before AP delivery'
                assert row['checks']==[1]
                await start_client(slot,'initial')
            for source in (1,2):
                for location in sorted(selected[source]-{1}):await pickup(source,location)
            initial=await check_delivery('initial-generated-delivery')
            assert all(r['pokos']>=280 for r in initial.values())
            await until(lambda:all(ctx.client_game_state[0,s]==30 for s in (1,2)),'original Poko goal')
            for source in (1,2):
                for location in sorted(selected[source]):await pickup(source,location)
            duplicate=await check_delivery('duplicate-checks')
            assert duplicate==initial
            old={s:set(ctx.clients[0][s]) for s in (1,2)}
            assert all(old.values())
            await asyncio.gather(*(ep.socket.close() for ep in list(ctx.endpoints)))
            await until(lambda:all(any(c not in old[s] for c in ctx.clients[0][s]) for s in (1,2)),'both automatic reconnects')
            assert await check_delivery('socket-reconnect')==initial
            serialized={}
            for slot in (1,2):
                saved=await native[slot].command('save',path=str(output/f'component-save-{slot}.bin'))
                serialized[slot]={key:saved[key] for key in ('pokos','equipment','courses')}
                loaded=await native[slot].command('load',path=str(output/f'component-save-{slot}.bin'),reset_before_load=True)
                assert loaded['native_before_reconcile']==serialized[slot], 'native deserialize must restore after clear before journal repair'
            # Withhold slot1's real native endpoint while AP delivers another real
            # generated reward. A server check alone must not create native state.
            await native[1].stop()
            before=(output/'run-1/bridge/native-state.json').read_bytes()
            extra=next(loc for loc,(_,receiver,_) in ctx.locations[2].items() if receiver==1 and loc not in selected[2])
            selected[2].add(extra)
            await pickup(2,extra)
            await until(lambda:extra in ctx.location_checks[0,2],'missing endpoint remote check')
            await asyncio.sleep(2)
            assert (output/'run-1/bridge/native-state.json').read_bytes()==before
            pending_journal=json.loads((output/'run-1/journal.json').read_text(encoding='utf-8'))
            records=pending_journal['snapshot']['records']
            assert len(records)==len(expected()[1]), 'real AP reward must reach the client queue'
            assert sum(r['state']=='Completed' for r in records)==len(json.loads(before)['receipts']), 'missing native effect falsely completed'
            assert records[-1]['state']!='Completed'
            (output/'missing-endpoint-journal.json').write_text(json.dumps(pending_journal,indent=2)+'\n',encoding='utf-8')
            native[1]=await Native(args.native.resolve(),output/'run-1/profile.json',output,1,'endpoint-return').start()
            loaded=await native[1].command('load',path=str(output/'component-save-1.bin'),reset_before_load=True)
            assert loaded['native_before_reconcile']==serialized[1]
            await check_delivery('endpoint-return')
            for slot in (1,2):
                saved=await native[slot].command('save',path=str(output/f'component-save-{slot}.bin'))
                serialized[slot]={key:saved[key] for key in ('pokos','equipment','courses')}
                await stop_client(slot)
                await native[slot].stop()
            before_restart={s:json.loads((output/f'run-{s}/bridge/native-state.json').read_text(encoding='utf-8')) for s in (1,2)}
            for slot in (1,2):
                native[slot]=await Native(args.native.resolve(),output/f'run-{slot}/profile.json',output,slot,'restart').start()
                loaded=await native[slot].command('load',path=str(output/f'component-save-{slot}.bin'),reset_before_load=True)
                assert loaded['native_before_reconcile']==serialized[slot]
                await start_client(slot,'restart')
            await until(lambda:all(ctx.clients[0][s] for s in (1,2)),'restart authentication')
            await asyncio.sleep(1)
            await check_delivery('process-restart-history')
            for slot in (1,2):
                assert json.loads((output/f'run-{slot}/bridge/native-state.json').read_text(encoding='utf-8'))==before_restart[slot]
            report={'boundary':'real original-world MultiServer + production companion/file bridge + actual native PlayData/equipment methods with substituted world storage',
                'not_proved':['walking/collision/carry caller','scene resources or rendered gameplay','walking between contexts (fixture substitutes section storage)','normal save-menu/MemoryCard commit callback','Louie goal','treasure-count goal'],
                'ap_revision':revision,'python':sys.version,'multidata_sha256':sha(multidata),
                'client_sha256':sha(args.client),'native_sha256':sha(args.native),'catalog_sha256':sha(ROOT/'contract.json'),
                'patches':{str(s):{'file':p.name,'sha256':sha(p)} for s,(p,_) in patches.items()},
                'checks':{str(s):sorted(ctx.location_checks[0,s]) for s in (1,2)},'generated_remote_globes':remote_globes,
                'observations':observations,'passed':['authentic server rejects wrong selected seed and buried mapping before pairing',
                'incidental Noisemaker floor rejected; original boss floor maps check145','original reward suppression before AP delivery','real generated remote permanent rewards',
                'native Poko/equipment readback','globe original getItem->openCourse capability','duplicate physical callbacks',
                'per-slot socket interruption/reconnect','missing native endpoint negative control','raw native component deserialize after reset before journal repair',
                'client/native process restart and indexed history replay','original Poko280 goal status30'],
                'worker':'shared GUI RunnerWorker' if args.gui_worker else 'shared headless Runner'}
            (output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
            print(json.dumps(report,indent=2))
    finally:
        for slot in list(clients):await stop_client(slot)
        for instance in native.values():await instance.stop()
        for f in client_files:f.close()

if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    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('--output',type=Path,required=True)
    parser.add_argument('--gui-worker',action='store_true')
    asyncio.run(smoke(parser.parse_args()))
