"""Exercise original Louie and treasure-count goals through native collection.

Real AP multidata and production companion/native endpoint; direct PlayData
collection callbacks substitute for physical carrying and the Titan encounter.
"""
from __future__ import annotations
import argparse
import copy
import asyncio
import json
import logging
import os
from pathlib import Path
import subprocess
import sys
import zipfile
from test_real_server import Native, sha, until, AP_REVISION, ROOT

async def goals(args):
    import unittest
    os.environ['AP_TEST_WORLDS']='generic'
    os.environ['SKIP_REQUIREMENTS_UPDATE']='1'
    assert sys.version_info[:2]==(3,12)
    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
    pristine_packages=copy.deepcopy(worlds.network_data_package)
    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='utf8'))
    item_by_name={i['name']:i for i in catalog['items']}
    item_by_id={i['id']:i for i in catalog['items']}
    locations={l['id']:l for l in catalog['locations'] if l['id']<=201}
    results=[]
    for fixture in args.fixtures:
        phase=output/fixture.name
        phase.mkdir()
        # Context strips name groups in-place; give each independent real
        # server its original package rather than sharing its mutated dict.
        worlds.network_data_package=copy.deepcopy(pristine_packages)
        ctx=MultiServer.Context('127.0.0.1',0,'','',0,0,False)
        multidata=next((fixture/'generated').glob('*.archipelago'))
        ctx.load(str(multidata.resolve()))
        patches={}
        for path in (fixture/'generated').glob('*.appik2'):
            with zipfile.ZipFile(path) as archive:patch=json.loads(archive.read('patch.appik2'))
            patches[patch['slot']]=(path.resolve(),patch)
        win=patches[1][1]['win_condition']
        assert win in (0,2)
        assert patches[2][1]['win_condition']==win
        native,clients,files={},{},[]
        selected={1:set(),2:set()}
        if win==0:
            king=next(l['id'] for l in locations.values() if l['name']=='DD King of Bugs')
            selected={1:{king},2:{king}}
        else:
            assert all(p['treasure_amount']==1 for _,p in patches.values())
            for receiver in (1,2):
                source=3-receiver
                location=next(loc for loc,(_,target,_) in ctx.locations[source].items() if target==receiver)
                selected[source].add(location)
        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]}'
                for slot in (1,2):
                    run=phase/f'run-{slot}'
                    prepare=await asyncio.create_subprocess_exec(str(args.client.resolve()),'prepare',str(patches[slot][0]),
                        '--endpoint',endpoint,'--run-dir',str(run),'--save',f'goal-selected-save-{slot}',
                        stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
                    out,err=await prepare.communicate()
                    assert prepare.returncode==0,err.decode(errors='replace')
                    native[slot]=await Native(args.native.resolve(),run/'profile.json',phase,slot,'goal').start()
                    row=await native[slot].command('observe')
                    assert row['goal'] is False and row['receipt_count']==0 and not row['checks']
                    stdout=(phase/f'client-{slot}.stdout.txt').open('wb')
                    stderr=(phase/f'client-{slot}.stderr.txt').open('wb')
                    files.extend([stdout,stderr])
                    clients[slot]=await asyncio.create_subprocess_exec(str(args.client.resolve()),str(run/'profile.json'),
                        '--gui-worker-smoke' if args.gui_worker else '--headless','--ticks','10000',
                        stdout=stdout,stderr=stderr,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
                await until(lambda:all(ctx.clients[0][s] for s in (1,2)),'goal initial authentication')
                await asyncio.sleep(.3)
                assert all(ctx.client_game_state[0,s]!=30 for s in (1,2)), 'absent goal reported completion'
                for source in (1,2):
                    for location in sorted(selected[source]):
                        row=locations[location]
                        physical=next(item for name,item in item_by_name.items() if row['name'].endswith(' '+name))
                        await native[source].command('pickup',text_id=physical['text_id'],cave=row['kind']!='overworld')
                await until(lambda:all(selected[s]<=ctx.location_checks[0,s] for s in (1,2)),'goal original checks')
                await until(lambda:all(ctx.client_game_state[0,s]==30 for s in (1,2)),'goal status30')
                await asyncio.sleep(.3)
                observations={s:await native[s].command('observe') for s in (1,2)}
                for slot,row in observations.items():
                    assert row['goal'] is True
                    grants=[item for source in (1,2) for loc in ctx.location_checks[0,source]
                            for item,receiver,flags in [ctx.locations[source][loc]] if receiver==slot]
                    assert row['receipt_count']==len(grants)
                    assert row['pokos']==sum(item_by_id[item]['value'] for item in grants)
                results.append({'win_condition':win,'seed':ctx.seed_name,'multidata_sha256':sha(multidata),
                    'patches':{str(s):sha(p) for s,(p,_) in patches.items()},
                    'checks':{str(s):sorted(ctx.location_checks[0,s]) for s in (1,2)},
                    'observations':observations,'absent_condition_not_reported':True,'server_status30':True})
        finally:
            for p in clients.values():
                if p.returncode is None:p.terminate()
                await p.wait()
            for n in native.values():await n.stop()
            for f in files:f.close()
    report={'boundary':'original goal conditions via real native PlayData collection with real AP MultiServer',
        'not_proved':['physical carry/collision callers','played Titan Dweevil encounter or campaign','normal save-menu/MemoryCard commit'],
        'ap_revision':revision,'client_sha256':sha(args.client),'native_sha256':sha(args.native),
        'worker':'shared GUI RunnerWorker' if args.gui_worker else 'shared headless Runner','goals':results}
    (output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')
    print(json.dumps(report,indent=2))

if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--ap-root',type=Path,required=True)
    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('--fixtures',type=Path,nargs='+',default=[ROOT/'tests/fixtures/louie-2026101502-r2',ROOT/'tests/fixtures/treasures1-2026101504'])
    parser.add_argument('--gui-worker',action='store_true')
    asyncio.run(goals(parser.parse_args()))
