"""Continue a genuinely played two-slot campaign through generated progression.

The initial route uses ordinary entry/carry/card input. Later routes disclose
scene, squad and captain setup; treasure pickup, carrying, AP delivery and native
consumers remain production code. Checkpoints use MultiServer.get_save/set_save
and the same test-owned native cards/journals, never a reset AP history.
"""
from __future__ import annotations
import asyncio
import json
import math
from pathlib import Path
import pickle
import time

from test_gameplay_real_server import make_parser, run, run_acceptance
from test_loaded_gameplay_real_server import LoadedRoute, SETUP
from test_real_server import sha, until

COURSES={'VoR':0,'AW':1,'PP':2,'WW':3}
CAVES={1952395313:0,1952395314:0,1952395315:0,1717514289:1,1717514290:1,
       1717514291:1,1717514292:1,2036281393:2,2036281394:2,2036281395:2,
       2036281396:2,1818177585:3,1818177586:3,1818177587:3}


class Progression:
    def __init__(self,session,driver,games):
        self.session,self.driver,self.games=session,driver,games
        self.routes={s:LoadedRoute(g,driver) for s,g in games.items()}
        self.rows={r['id']:r for r in session.catalog['locations'] if r['id']<=201}
        self.caves={name:int(code) for code,name in session.catalog['caves'].items()}
        self.evidence={}

    def context(self,location):
        row=self.rows[location]
        prefix=row['name'].split()[0]
        if prefix in COURSES:return COURSES[prefix],0,0
        cave=self.caves[prefix]
        return CAVES[cave],cave,row['sublevel']-1

    def source(self,recipient,item):
        candidates=[]
        for source in (1,2):
            for location,(found,target,_) in self.session.ctx.locations[source].items():
                if found==item and target==recipient:
                    row=self.rows[location]
                    candidates.append((bool('enemy' in row['kind']),row['sublevel'],source,location))
        assert candidates,f'original seed has no item {item} for slot {recipient}'
        return min(candidates)[2:]

    async def collect(self,source,location):
        session=self.session
        if location in session.ctx.location_checks[0,source]:
            await session.wait_rewards()
            return {'already_collected':True,'source':source,'location':location}
        route=self.routes[source]
        course,cave,floor=self.context(location)
        before=await asyncio.to_thread(route.scene,course,cave,floor)
        row=self.rows[location]
        if 'enemy' in row['kind']:
            enemy=next(e for e in before['loaded']['actor_audit']['enemies'] if e['location']==location)
            position=list(enemy['position']);position[0]-=50
            ground=await asyncio.to_thread(route.command,'ground_query',position=position)
            position=ground['last_result']['position'];position[1]+=5
            await asyncio.to_thread(route.command,'actor_position',actor='navi',index=0,position=position)
            await asyncio.to_thread(self.games[source].input,frames=30)
            await asyncio.to_thread(route.playable)
            await asyncio.to_thread(route.command,'actor_defeat',location=location)
            await asyncio.to_thread(route.playable)
        _,actor,binding=await asyncio.to_thread(route.physical,location,120)
        color=4 if binding['depth_max']>0 else 3 if binding['min_carriers']>100 else 1
        count=math.ceil(binding['min_carriers']/10) if color==3 else binding['min_carriers']
        await asyncio.to_thread(route.squad_at_actor,location,color,count)
        attached,_=await asyncio.to_thread(route.attach,location,binding['min_carriers'])
        arrived=await asyncio.to_thread(route.delivered,location,before)
        await asyncio.to_thread(route.playable)
        await session.wait_checks({source:[location]},timeout=60)
        await session.wait_rewards(timeout=60)
        observations={}
        for slot,game in self.games.items():
            state=await asyncio.to_thread(game.wait_state,lambda s:True)
            session.assert_native_reward_state(slot,state)
            observations[str(slot)]=state
        result={'source':source,'location':location,'original_row':row,'binding':binding,
                'attached':attached,'arrived':arrived,'observations':observations,
                'shortcuts':SETUP+(['enemy health zero; native death/drop FSM'] if 'enemy' in row['kind'] else [])}
        session.event('progression-original-generated-physical-delivery',**result)
        return result

    async def acquire(self,slot,item):
        source,location=self.source(slot,item)
        result=await self.collect(source,location)
        state=await asyncio.to_thread(self.games[slot].wait_state,lambda s:True)
        assert state['equipment']&(1<<self.session.items[item]['native_id'])
        self.evidence[f'acquire-{slot}-{item}']=result
        return result

    async def worldmap(self,slot):
        await asyncio.to_thread(self.driver.return_worldmap,self.games[slot],timeout=300)
        return await asyncio.to_thread(self.games[slot].wait_state,
            lambda s:'worldmap' in s.get('effects',{}),60,'actual rendered world-map UI')

    async def land(self,slot,course):
        state=await asyncio.to_thread(self.driver.select_course,self.games[slot],course,timeout=240)
        observed=await asyncio.to_thread(self.games[slot].wait_state,lambda s:True)
        assert observed['ready'] and observed['course']==course and observed['cave']==0
        self.session.event('generated-globe-normal-map-selection-and-landing',slot=slot,course=course,
                           route=state,observed=observed)
        return observed

    async def controller_effect(self,slot,kind):
        game=self.games[slot];route=self.routes[slot]
        await asyncio.to_thread(route.playable)
        if kind=='speed':
            await asyncio.to_thread(game.input,stick_y=127,frames=90,wait=False)
            state=await asyncio.to_thread(game.wait_state,
                lambda s:s['input_remaining']>5 and any(math.hypot(c['target_velocity'][0],c['target_velocity'][2])>100
                    for c in s.get('effects',{}).get('captains',[])),30,'actual full-stick native velocity')
            value=max(math.hypot(c['target_velocity'][0],c['target_velocity'][2]) for c in state['effects']['captains'])
        elif kind=='whistle':
            await asyncio.to_thread(game.input,buttons=self.driver.B,frames=300,wait=False)
            state=await asyncio.to_thread(game.wait_state,
                lambda s:s['input_remaining']>5 and any(c['whistle_radius']>=85 for c in s.get('effects',{}).get('captains',[])),30,
                'actual sustained whistle radius')
            value=max(c['whistle_radius'] for c in state['effects']['captains'])
        else:raise ValueError(kind)
        await asyncio.to_thread(game.input,frames=20)
        self.session.event('actual-controller-equipment-consumer',slot=slot,kind=kind,value=value,state=state)
        return value,state

    async def execute(self):
        # PP must be selectable without AW when Geographic Projection arrives
        # first. These are actual generated cross-slot sources, not receipts.
        first=await self.worldmap(1)
        assert [c['id'] for c in first['effects']['worldmap']['courses'] if c['selectable']]==[0]
        await self.collect(2,160) # P2 CoC Growshroom -> P1 Geographic Projection
        map_geo=await asyncio.to_thread(self.games[1].wait_state,
            lambda s:'worldmap' in s.get('effects',{}) and s['effects']['worldmap']['courses'][2]['selectable'],60,
            'Geographic-first actual rendered PP course')
        assert not map_geo['effects']['worldmap']['courses'][1]['selectable']
        assert map_geo['effects']['worldmap']['courses'][2]['dot_visible']
        await self.land(1,2)
        await self.collect(1,9) # original P1 EC Quenching -> P2 Spherical Atlas
        map_sphere=await self.worldmap(2)
        assert map_sphere['effects']['worldmap']['courses'][1]['selectable']
        assert map_sphere['effects']['worldmap']['courses'][1]['dot_visible']
        await self.land(2,1)
        await self.collect(2,33) # original remote FC buried Gemstar -> P1 Sphere
        both=await self.worldmap(1)
        assert all(both['effects']['worldmap']['courses'][i]['selectable'] for i in (0,1,2))
        assert not both['effects']['worldmap']['courses'][3]['selectable'],'unpaid debt must still gate WW'
        await self.land(1,1)
        self.evidence['worldmap']={'initial':first,'geographic_first':map_geo,'sphere':map_sphere,'both_before_debt':both}
        # Target velocity and whistle radius are sampled during actual PAD
        # intervals before and after real generated native getItem effects.
        speed_before=await self.controller_effect(2,'speed')
        await self.acquire(2,508)
        speed_after=await self.controller_effect(2,'speed')
        assert speed_after[0]>speed_before[0]*1.15
        whistle_before=await self.controller_effect(1,'whistle')
        await self.acquire(1,503)
        whistle_after=await self.controller_effect(1,'whistle')
        assert whistle_after[0]>whistle_before[0]+20
        self.evidence['controller_effects']={'speed_before':speed_before,'speed_after':speed_after,
            'whistle_before':whistle_before,'whistle_after':whistle_after}
        await self.acquire(2,513)
        await self.worldmap(2)
        title=await asyncio.to_thread(self.driver.return_title,self.games[2],timeout=180)
        state=await asyncio.to_thread(self.games[2].wait_state,lambda s:True)
        assert state['effects']['global_challenge'] and state['effects']['title_menu_opens']>=2
        self.evidence['key_title']={'route':title,'state':state}
        # Do not promote the broad gate from only a subset of its consumers.
        self.session.mark_gate('progression',False,self.evidence,SETUP,
            remaining='remaining admitted equipment consumers, Key title restart, and earned debt/WW route need actual gameplay evidence')
        raise AssertionError('partial progression retained; remaining native consumers are not yet accepted')


async def restore(session,driver,checkpoint):
    """Resume only this harness's trusted local checkpoint, using AP's API."""
    metadata=json.loads(checkpoint.read_text(encoding='utf8'))
    assert metadata['native_sha256']==sha(session.args.native)
    assert metadata['client_sha256']==sha(session.args.client)
    assert metadata['patches']=={str(s):sha(p) for s,(p,_) in session.patches.items()}
    saved=checkpoint.parent/metadata['server_save']
    assert sha(saved)==metadata['server_save_sha256']
    session.ctx.set_save(pickle.loads(saved.read_bytes()))
    games={}
    for slot in (1,2):
        configured={k:Path(v) if k!='slot' else v for k,v in metadata['runs'][str(slot)].items()}
        session.runs[slot]=configured
        process=await asyncio.create_subprocess_exec(str(session.args.client.resolve()),'prepare',
            str(session.patches[slot][0]),'--endpoint',session.endpoint,'--run-dir',str(configured['directory']),
            '--save',f'gameplay-selected-save-{slot}',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)
        out,err=await process.communicate();assert process.returncode==0,err.decode(errors='replace')
        game=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
            session.output/f'resume-control-{slot}',configured['save'],session.output/f'resume-native-{slot}.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='official-ap-save-resume')
        route=await asyncio.to_thread(driver.boot_day1,game,timeout=300)
        session.event('official-ap-history-and-selected-native-card-resumed',slot=slot,route=route,
                      checkpoint=str(checkpoint),checkpoint_sha256=sha(checkpoint))
    await session.wait_rewards(timeout=90)
    return games


async def accept(session,driver):
    games={}
    try:
        if session.args.resume_checkpoint:
            games=await restore(session,driver,session.args.resume_checkpoint.resolve())
        else:
            games=await run_acceptance(session,driver)
        await Progression(session,driver,games).execute()
    finally:
        # Freeze live peers before serializing their *real* AP history. Native
        # saves are genuine prior MemoryCard writes; no component serialization.
        for slot in list(session.clients):await session.stop_client(slot)
        for game in games.values():await asyncio.to_thread(game.shutdown)
        payload=pickle.dumps(session.ctx.get_save(),protocol=pickle.HIGHEST_PROTOCOL)
        path=session.output/'real-server.apsave-input';path.write_bytes(payload)
        metadata={'format':'pikmin2-gameplay-continuation-v1','server_save':path.name,'server_save_sha256':sha(path),
            'native_sha256':sha(session.args.native),'client_sha256':sha(session.args.client),
            'patches':{str(s):sha(p) for s,(p,_) in session.patches.items()},
            'runs':{str(s):{k:str(v) if isinstance(v,Path) else v for k,v in row.items()} for s,row in session.runs.items()},
            'gates':session.gates}
        (session.output/'continuation.json').write_text(json.dumps(metadata,indent=2)+'\n',encoding='utf8')


if __name__=='__main__':
    parser=make_parser(__doc__)
    parser.add_argument('--resume-checkpoint',type=Path)
    args=parser.parse_args()
    asyncio.run(run(args,acceptance=accept,scope_gates=('normal_entry','carrying','card_save_load_restart','progression'),
                   acceptance_kind='normal_gameplay',boundary=__doc__))
