"""Exercise eleven non-globe equipment consumers after actual generated rewards.

World-map globe consumers have their own earned-debt/WW scope. Later scene/squad/
captain setup is explicit. Hazard probes invoke real interaction/damage consumers
with a bounded disclosed stimulus; their collision callers are outside this scope.
"""
from __future__ import annotations
import asyncio
import json
import math
import pickle
from pathlib import Path
import time
from test_gameplay_real_server import make_parser,run
from test_progression_gameplay_real_server import Progression
from test_gameplay_settled_route import SettledRoute
from test_gameplay_tutorial import initial_red_intro
from test_real_server import sha,until

CONSUMERS=tuple(range(501,511))+(513,)
HELPERS=[Path(__file__).with_name(n) for n in ('test_progression_gameplay_real_server.py','test_loaded_gameplay_recruitment.py',
    'test_gameplay_routes.py','test_gameplay_settled_route.py','test_gameplay_tutorial.py')]


class Equipment(Progression):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={s:SettledRoute(g,driver) for s,g in games.items()}

    async def collect(self,source,location):
        if location in self.session.ctx.location_checks[0,source]:
            await self.session.wait_rewards();return {'already_collected':True,'source':source,'location':location}
        route=self.routes[source];game=self.games[source]
        before=await asyncio.to_thread(route.scene,*self.context(location));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(game.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,180)
        required=row['pikmin_required']
        color=0 if 'blue' in required else 4 if binding['depth_max']>0 or 'white' in required else 2 if 'yellow' in required else 1
        if binding['min_carriers']>100:color=3
        minimum=math.ceil(binding['min_carriers']/10) if color==3 else binding['min_carriers']
        # Consumer tests use spare real carriers; exact minimum/maximum weight
        # assertions belong to the separately isolated physical route.
        count=min(100,max(2,minimum*2))
        await asyncio.to_thread(route.squad_at_actor,location,color,count)
        attached,_=await asyncio.to_thread(route.attach,location,binding['min_carriers'])
        after=await asyncio.to_thread(route.delivered,location,before,240)
        await asyncio.to_thread(route.playable)
        await self.session.wait_checks({source:[location]},timeout=60);await self.session.wait_rewards(timeout=60)
        result=dict(source=source,location=location,row=row,binding=binding,color=color,count=count,attached=attached,after=after)
        self.session.event('equipment-generated-physical-delivery',**result)
        return result

    async def empty_overworld(self,slot):
        route=self.routes[slot];game=self.games[slot]
        await asyncio.to_thread(route.scene,0)
        await asyncio.to_thread(game.input,frames=180)
        return await asyncio.to_thread(route.playable)

    async def worldmap(self,slot):
        game=self.games[slot]
        await asyncio.to_thread(self.routes[slot].playable)
        await asyncio.to_thread(game.press,self.driver.START,frames=12)
        menu=await asyncio.to_thread(game.wait_state,lambda s:s.get('ui_scene') in (10010,10013),30,
            'actual native pause page, with or without the unlocked Radar')
        if menu['ui_scene']==10013:
            await asyncio.to_thread(game.input,frames=45)
            await asyncio.to_thread(game.press,self.driver.R,frames=12)
            await asyncio.to_thread(game.wait_state,lambda s:s.get('ui_scene')==10010,30,'ordinary pause menu')
        await asyncio.to_thread(game.input,frames=60)
        await asyncio.to_thread(game.press,self.driver.DOWN,frames=8)
        await asyncio.to_thread(game.press,self.driver.A,frames=12)
        await asyncio.to_thread(game.input,frames=60)
        await asyncio.to_thread(game.press,self.driver.UP,frames=8)
        await asyncio.to_thread(game.press,self.driver.A,frames=12)
        saved=await asyncio.to_thread(self.driver.finish_day_and_save,game,timeout=300)
        assert saved['state']['card_saves']>0
        return await asyncio.to_thread(game.wait_state,lambda s:'worldmap' in s.get('effects',{}),60,'actual rendered world map')

    async def recovered(self,slot,captain=0):
        game=self.games[slot];route=self.routes[slot]
        deadline=time.monotonic()+60
        while time.monotonic()<deadline:
            state=await asyncio.to_thread(route.playable)
            row=next(c for c in state['effects']['captains'] if c['index']==captain)
            if row['state']==0:
                await asyncio.to_thread(game.input,frames=240)
                state=await asyncio.to_thread(route.playable)
                if next(c for c in state['effects']['captains'] if c['index']==captain)['state']==0:return state
            await asyncio.to_thread(game.input,frames=30)
        raise TimeoutError('real captain did not naturally recover to Walk')

    async def hazard(self,consumer):
        await self.recovered(2)
        state=await asyncio.to_thread(self.routes[2].command,'effect_consumer_probe',consumer=consumer,captain=0,damage=2.0)
        result=state['last_result'];self.session.event('equipment-bounded-native-consumer',result=result,state=state)
        await self.recovered(2)
        return result

    async def punch(self):
        game=self.games[2];await self.empty_overworld(2)
        for _ in range(18):await asyncio.to_thread(game.press,self.driver.A,frames=4)
        state=await asyncio.to_thread(game.wait_state,lambda s:True)
        value=max(c['punch_combo_max_observed'] for c in state['effects']['captains'])
        await asyncio.to_thread(game.input,frames=90)
        return value,state

    async def napsack(self,enabled):
        await self.empty_overworld(2);game=self.games[2]
        await asyncio.to_thread(game.input,buttons=self.driver.X,frames=180,wait=False)
        if enabled:
            state=await asyncio.to_thread(game.wait_state,
                lambda s:any(c['state']==23 for c in s.get('effects',{}).get('captains',[])),30,'real held-X Napsack state')
        else:
            await asyncio.to_thread(game.wait_state,lambda s:s['input_remaining']==0,30,'baseline held-X interval')
            state=await asyncio.to_thread(game.wait_state,lambda s:True)
            assert all(c['state']!=23 for c in state['effects']['captains'])
        await asyncio.to_thread(game.input,frames=8);await asyncio.to_thread(game.press,self.driver.A,frames=8)
        await self.recovered(2)
        return state

    async def sprouts(self):
        """Create no seeds: deliver an authored number pellet to the real Onion."""
        route=self.routes[2];game=self.games[2]
        state=await asyncio.to_thread(route.scene,0)
        onion=next(o for o in state['onyons'] if o['type']==1)
        heads=[p for p in state['pellets'] if p['kind']==0]
        assert heads,'authored number pellets required for real reproduction'
        head=min(heads,key=lambda p:self.driver.distance(p['position'],onion['position']))
        position=list(head['position']);position[0]-=90;position[1]+=10
        await asyncio.to_thread(route.command,'actor_position',actor='navi',index=0,position=position)
        await asyncio.to_thread(game.input,frames=20);await asyncio.to_thread(route.playable)
        await asyncio.to_thread(route.command,'squad_replace',color=1,count=3,captain=0,position=position)
        await asyncio.to_thread(self.driver.whistle_here,game,frames=120)
        await asyncio.to_thread(route.playable)
        await asyncio.to_thread(self.driver.aim_at,game,head['position'],radius=15)
        for _ in range(6):await asyncio.to_thread(game.press,self.driver.A,frames=8)
        deadline=time.monotonic()+180
        while time.monotonic()<deadline:
            state=await asyncio.to_thread(route.playable)
            if state['sprouts']:break
            await asyncio.to_thread(game.input,frames=60)
        else:raise TimeoutError('actual number-pellet delivery did not produce native sprouts')
        center=[sum(p['position'][i] for p in state['sprouts'])/len(state['sprouts']) for i in range(3)]
        await asyncio.to_thread(self.driver.walk_to,game,center,radius=65,timeout=60)
        await asyncio.to_thread(self.driver.aim_at,game,center,radius=15)
        return state,center

    async def whistle_sprouts(self,enabled):
        before,center=await self.sprouts();game=self.games[2]
        assert not before['effects']['whistle_pluck'],'negative control requires original upstream whistle-pluck setting off'
        await asyncio.to_thread(game.input,buttons=self.driver.B,frames=240)
        await asyncio.to_thread(game.input,frames=90)
        after=await asyncio.to_thread(self.routes[2].playable)
        retained=[seed for seed in before['sprouts'] if any(self.driver.distance(seed['position'],other['position'])<20
            for other in after['sprouts'])]
        # Real number-pellet arrivals may create additional seeds during the
        # whistle interval. Match the pre-existing planted positions instead
        # of mistaking legitimate reproduction for a failed negative control.
        if enabled:
            assert len(retained)<len(before['sprouts'])
            assert len(after['pikis'])>len(before['pikis'])
        else:assert len(retained)==len(before['sprouts'])
        return dict(before=before,after=after,retained_original_sprouts=retained,actual_sprout_centroid=center)


async def execute(session,driver):
    helpers={str(p):sha(p) for p in HELPERS};games={}
    session.equipment_games=games
    checkpoint=session.args.resume_checkpoint
    if checkpoint:
        metadata=json.loads(checkpoint.read_text(encoding='utf8'))
        assert metadata['native_sha256']==sha(session.args.native) and metadata['client_sha256']==sha(session.args.client)
        assert metadata['native_runtime_sha256']=={p.name:sha(p) for p in session.args.native.parent.glob('*.dll')}
        assert metadata['patches']=={str(s):sha(p) for s,(p,_) in session.patches.items()}
        payload=checkpoint.parent/metadata['server_save'];assert sha(payload)==metadata['server_save_sha256']
        session.ctx.set_save(pickle.loads(payload.read_bytes()))
        session.consumer_state=metadata['consumer_state']
        for slot in (1,2):
            cfg={k:Path(v) if k!='slot' else v for k,v in metadata['runs'][str(slot)].items()}
            session.runs[slot]=cfg
            process=await asyncio.create_subprocess_exec(str(session.args.client.resolve()),'prepare',str(session.patches[slot][0]),
                '--endpoint',session.endpoint,'--run-dir',str(cfg['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')
        session.event('equipment-official-ap-history-resume',checkpoint=str(checkpoint),sha256=sha(checkpoint))
    else:session.consumer_state={'evidence':{},'baselines':{}}
    for slot,cfg in session.runs.items():
        game=driver.GameplayClient(session.args.native,session.args.assets,cfg['profile'],session.output/f'slot-{slot}/equipment-control',
            cfg['save'],session.output/f'equipment-native-{slot}.log')
        games[slot]=game;session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        session.event('equipment-normal-entry',slot=slot,route=await asyncio.to_thread(initial_red_intro,game,driver))
        await session.start_client(slot)
    await until(lambda:all(session.ctx.clients[0][s] for s in (1,2)),'both equipment slots authenticated')
    equipment=Equipment(session,driver,games);evidence=session.consumer_state['evidence']
    baseline=session.consumer_state['baselines']
    if not {'speed','whistle','punch','sleep','electric','fire','damage','sprouts','key'}<=baseline.keys():
        baseline.clear()
        await equipment.empty_overworld(2)
        baseline['speed']=await equipment.controller_effect(2,'speed')
        baseline['whistle']=await equipment.controller_effect(2,'whistle')
        baseline['punch']=await equipment.punch()
        baseline['sleep']=await equipment.napsack(False)
        baseline['electric']=await equipment.hazard('electric');assert baseline['electric']['accepted'] is True
        baseline['fire']=await equipment.hazard('fire');assert baseline['fire']['accepted'] is True
        baseline['damage']=await equipment.hazard('damage');assert baseline['damage']['damage_observed']>0
        baseline['sprouts']=await equipment.whistle_sprouts(False)
        baseline['key']=(await asyncio.to_thread(games[1].wait_state,lambda s:True))['effects']
        assert baseline['key']['title_challenge_state']==0 and not baseline['key']['global_challenge']
    before_speed,before_whistle,before_punch,before_sleep,before_electric,before_fire,before_damage,before_sprouts=(
        baseline[k] for k in ('speed','whistle','punch','sleep','electric','fire','damage','sprouts'))
    if '501' not in evidence:
        await equipment.acquire(2,501);after=await equipment.punch()
        assert after[0]>=2 and after[0]>before_punch[0];evidence['501']={'before':before_punch,'after':after}
        session.event('equipment-consumer-completed',item_id=501,evidence=evidence['501'])
    if '502' not in evidence:
        await equipment.acquire(2,502);after=await equipment.hazard('electric')
        assert after['accepted'] is False;evidence['502']={'before':before_electric,'after':after}
        session.event('equipment-consumer-completed',item_id=502,evidence=evidence['502'])
    if '503' not in evidence:
        await equipment.acquire(2,503);after=await equipment.controller_effect(2,'whistle')
        assert after[0]>before_whistle[0]+20;evidence['503']={'before':before_whistle,'after':after}
        session.event('equipment-consumer-completed',item_id=503,evidence=evidence['503'])
    if '504' not in evidence:
        await equipment.acquire(2,504);after=await equipment.whistle_sprouts(True)
        evidence['504']={'before':before_sprouts,'after':after}
        session.event('equipment-consumer-completed',item_id=504,evidence=evidence['504'])
    if '505' not in evidence:
        if 'light_before' not in baseline:baseline['light_before']=await asyncio.to_thread(equipment.routes[1].scene,0,1952395313,1)
        # Some authored caves keep their main cutoff identical across both
        # light settings. An explicitly retained same-scene pre-item sample
        # can select a meaningful output without replacing original baselines.
        light_before=baseline.get('light_consumer_before',baseline['light_before'])
        assert light_before['effects']['light']['stellar_increment']==0
        await equipment.acquire(1,505);await asyncio.to_thread(games[1].input,frames=180)
        light_after=await asyncio.to_thread(games[1].wait_state,lambda s:True)
        assert light_after['effects']['light']['stellar_increment']>.9 and light_after['effects']['light']['color_ratio']>.9
        assert light_after['effects']['light']['main_cutoff']!=light_before['effects']['light']['main_cutoff']
        evidence['505']={'before':light_before,'after':light_after}
        session.event('equipment-consumer-completed',item_id=505,evidence=evidence['505'])
    if '506' not in evidence:
        await equipment.acquire(2,506);after=await equipment.hazard('damage')
        if 'damage_consumer_before' in baseline:
            before_damage=baseline['damage_consumer_before']
            assert before_damage['slot']==after['slot'], 'damage consumer baseline and earned effect must use the same original slot'
        assert 0<after['damage_observed']<before_damage['damage_observed']
        evidence['506']={'before':before_damage,'after':after}
        session.event('equipment-consumer-completed',item_id=506,evidence=evidence['506'])
    if '507' not in evidence:
        await equipment.acquire(2,507);after=await equipment.hazard('fire')
        assert after['accepted'] is False;evidence['507']={'before':before_fire,'after':after}
        session.event('equipment-consumer-completed',item_id=507,evidence=evidence['507'])
    if '508' not in evidence:
        await equipment.acquire(2,508);after=await equipment.controller_effect(2,'speed')
        if 'speed_consumer_before' in baseline:
            before_speed=baseline['speed_consumer_before']['sample']
            assert baseline['speed_consumer_before']['slot']==equipment.speed_consumer_slot
        assert after[0]>before_speed[0]*1.15;evidence['508']={'before':before_speed,'after':after}
        evidence['508']['slot']=getattr(equipment,'speed_consumer_slot',2)
        session.event('equipment-consumer-completed',item_id=508,evidence=evidence['508'])
    if '509' not in evidence:
        if 'hud_before' not in baseline:baseline['hud_before']=await asyncio.to_thread(equipment.routes[2].scene,0,1952395313,0)
        hud_before=baseline['hud_before']
        assert not hud_before['effects']['cave_hud']['draw_sensor']
        await equipment.acquire(2,509)
        hud_after=await asyncio.to_thread(games[2].wait_state,lambda s:s.get('effects',{}).get('cave_hud',{}).get('draw_sensor'),45,
            'actual Prototype Detector cave HUD')
        evidence['509']={'before':hud_before,'after':hud_after}
        session.event('equipment-consumer-completed',item_id=509,evidence=evidence['509'])
    if '510' not in evidence:
        await equipment.acquire(2,510);evidence['510']={'before':before_sleep,'after':await equipment.napsack(True)}
        session.event('equipment-consumer-completed',item_id=510,evidence=evidence['510'])
    if '513' not in evidence:
        key_slot=getattr(equipment,'key_consumer_slot',1)
        await equipment.acquire(key_slot,513)
        key_before=baseline.get('key_consumer_before',baseline['key'])
        assert not key_before['global_challenge']
        if 'key_consumer_before' in baseline:assert key_before['slot']==key_slot
        await equipment.empty_overworld(key_slot)
        await asyncio.to_thread(equipment.routes[key_slot].command,'squad_setup',color=1,count=1,captain=0)
        await equipment.worldmap(key_slot)
        title=await asyncio.to_thread(driver.return_title,games[key_slot],timeout=180)
        title_state=await asyncio.to_thread(games[key_slot].wait_state,lambda s:True)
        assert title_state['effects']['global_challenge'] and title_state['effects']['title_menu_opens']>0
        assert title_state['effects']['title_challenge_state']==1,'actual rendered Title Challenge row must be enabled'
        await session.stop_client(key_slot);await asyncio.to_thread(games[key_slot].shutdown)
        cfg=session.runs[key_slot]
        restored=driver.GameplayClient(session.args.native,session.args.assets,cfg['profile'],cfg['directory']/'key-restart-control',
            cfg['save'],session.output/'key-restart-native.log')
        games[key_slot]=restored;session.register_cleanup(lambda:asyncio.to_thread(restored.shutdown))
        await asyncio.to_thread(restored.start)
        reopened=await asyncio.to_thread(driver.boot_title,restored,timeout=180)
        actual=await asyncio.to_thread(restored.wait_state,lambda s:True)
        assert actual['effects']['global_challenge'],'actual saved common Key capability lost on native restart'
        assert actual['effects']['title_menu_opens']>0 and actual['effects']['title_challenge_state']==1
        evidence['513']={'slot':key_slot,'before':key_before,'actual_title':title,'restart_title':reopened,'state':actual}
        session.event('equipment-consumer-completed',item_id=513,evidence=evidence['513'])
    assert set(evidence)=={str(i) for i in CONSUMERS}
    assert all(sha(Path(p))==digest for p,digest in helpers.items())
    session.event('equipment-consumers-scope-passed',passed=True,consumer_item_ids=list(CONSUMERS),evidence=evidence,
        helper_sha256=helpers,boundary=__doc__)


async def accept(session,driver):
    pins={str(p):sha(p) for p in HELPERS}
    try:
        await execute(session,driver)
    finally:
        for slot in list(session.clients):await session.stop_client(slot)
        for game in getattr(session,'equipment_games',{}).values():await asyncio.to_thread(game.shutdown)
        payload=session.output/'real-server.apsave-input'
        payload.write_bytes(pickle.dumps(session.ctx.get_save(),protocol=pickle.HIGHEST_PROTOCOL))
        metadata={'format':'pikmin2-equipment-continuation-v1','server_save':payload.name,'server_save_sha256':sha(payload),
            'native_sha256':sha(session.args.native),'client_sha256':sha(session.args.client),
            'native_runtime_sha256':{p.name:sha(p) for p in session.args.native.parent.glob('*.dll')},
            '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()},
            'consumer_state':getattr(session,'consumer_state',{'evidence':{},'baselines':{}}),
            'helper_sha256':pins,'executed_driver_sha256':sha(session.output/'executed-driver.py')}
        (session.output/'continuation.json').write_text(json.dumps(metadata,indent=2)+'\n',encoding='utf8')
        assert all(sha(Path(p))==digest for p,digest in pins.items()),'equipment helpers changed during scope'


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--resume-checkpoint',type=Path)
    args=parser.parse_args()
    async def main():
        report=await run(args,acceptance=accept,scope_gates=(),acceptance_kind='loaded_scene',boundary=__doc__)
        event=next(e for e in report['events'] if e['label']=='equipment-consumers-scope-passed')
        report['subgates']={'equipment_consumers':{k:event[k] for k in ('passed','consumer_item_ids','evidence','boundary','helper_sha256')}}
        report['broad_progression_gate_claimed']=False
        (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')
    asyncio.run(main())
