"""Earn original Debt100 and exercise the actual both-globe Wistful Wild gate.

This standalone sub-scope uses an untouched original-world fixture with a valid
lower debt option. Scene/day/squad/captain setup is disclosed; carrying, AP
receipt, repayment/ending, map selection and final landing stay game-owned.
"""
from __future__ import annotations
import asyncio
import json
import math
from pathlib import Path
import time
import zipfile
from test_gameplay_real_server import make_parser, run
from test_progression_gameplay_real_server import Progression
from test_real_server import sha, until
from test_loaded_gameplay_real_server import SETUP
from test_gameplay_settled_route import SettledRoute

PROGRESSION_FILE=Path(__file__).with_name('test_progression_gameplay_real_server.py')
ROUTE_FILES=[Path(__file__).with_name(name) for name in
    ('test_gameplay_routes.py','test_loaded_gameplay_recruitment.py','test_gameplay_settled_route.py')]

class WWRoute(SettledRoute):
    def squad_at_actor(self,location,color,count):
        _,actor,binding=self.physical(location)
        position=list(actor['position'])
        position[2]-=30
        position[1]+=10
        self.command('actor_position',actor='navi',index=0,position=position)
        self.game.input(frames=20)
        self.playable()
        born=self.command('squad_replace',color=color,count=count,captain=0,position=position)
        assert born['last_result']['born']==count
        for _ in range(3):
            state=self.playable()
            center=[sum(p['position'][i] for p in state['pikis'])/len(state['pikis']) for i in range(3)]
            self.driver.aim_at(self.game,center,radius=15)
            self.game.input(buttons=self.driver.B,frames=120)
            self.game.input(frames=8)
        owner=self.driver.active_navi(self.game.wait_state(lambda s:True))['actor_id']
        state=self.game.wait_state(lambda s:len(s.get('pikis',[]))==count
            and all(p['kind']==color and p['action']==0 and p['navi_id']==owner for p in s['pikis']),
            20,'actual whistled WW Formation Pikmin')
        self.record('ww-declared-near-actor-captain-squad-setup',state,position=position,color=color,count=count)
        return actor,binding

class WWProgression(Progression):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={slot:WWRoute(game,driver) for slot,game in games.items()}

    async def land(self,slot,course):
        route=await asyncio.to_thread(self.driver.choose_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('ww-normal-map-selection-and-landing',slot=slot,course=course,route=route,observed=observed)
        return observed

    async def collect(self,source,location):
        route=self.routes[source]
        before=await asyncio.to_thread(route.scene,*self.context(location))
        row=self.rows[location]
        assert 'enemy' not in row['kind'], 'WW selected sources must not bypass enemy drops'
        _,actor,binding=await asyncio.to_thread(route.physical,location,120)
        # Preserve the factual source route's required water access. A remote
        # marble is unburied, but it does not make Red Pikmin water-resistant.
        required=binding['min_carriers']
        color=3 if required>100 else 0 if 'blue' in row['pikmin_required'] else 4 if binding['depth_max']>0 or 'white' in row['pikmin_required'] else 1
        count=math.ceil(required/10)+5 if color==3 else min(60,actor['maximum'])
        await asyncio.to_thread(route.squad_at_actor,location,color,count)
        attached,_=await asyncio.to_thread(route.attach,location,required)
        arrived=await asyncio.to_thread(route.delivered,location,before,240)
        await self.session.wait_checks({source:[location]},timeout=60)
        await self.session.wait_rewards(timeout=60)
        result={'source':source,'location':location,'original_row':row,'binding':binding,
            'color':color,'count':count,'required':required,'attached':attached,'arrived':arrived,'shortcuts':SETUP}
        self.session.event('ww-original-generated-physical-delivery',**result)
        return result

def start_landing(game,driver,course,timeout=90):
    """Return after actual Land starts loading, before repayment can take over."""
    deadline=time.monotonic()+timeout; trace=[]
    while time.monotonic()<deadline:
        state=game.wait_state(lambda s:True); world=state.get('effects',{}).get('worldmap')
        trace.append({k:state.get(k) for k in ('retrace','game_state','course','effects')})
        if state.get('game_state')!=1:return {'state':state,'trace':trace}
        if not world:game.input(frames=20);continue
        assert world['courses'][course]['selectable']
        if world['state']==2 and world['selected']!=course:
            selected=world['selected']
            if selected==0 and course==2:game.press(driver.UP,frames=12)
            elif selected==2 and course==0:game.press(driver.DOWN,frames=12)
            else:raise RuntimeError(f'unplanned ordinary map edge {selected}->{course}')
        elif world['state'] in (2,9):game.press(driver.A,frames=12)
        else:game.input(frames=20)
    raise TimeoutError('normal Land did not leave world map')

def finish_earned_debt(game,driver,timeout=600):
    deadline=time.monotonic()+timeout; trace=[]; last=None; ending=False
    while time.monotonic()<deadline:
        state=game.wait_state(lambda s:True)
        projection={k:state.get(k) for k in ('game_state','course','day','ui_scene','movie','movie_state','movie_pause','paused','save_menu','card_saves','pokos')}
        if projection!=last:trace.append(projection);last=projection
        ending|=state.get('game_state')==11
        world=state.get('effects',{}).get('worldmap')
        if ending and state.get('game_state')==1 and world and world['state']==2:
            return {'ending_state_11_observed':True,'state':state,'trace':trace,
                    'boundary':'actual native repayment/EndingState and normal controller responses; no debt/story flag assignment'}
        menu=state.get('save_menu',{})
        if menu.get('state')==8:raise RuntimeError(f'actual MemoryCard error: {menu}')
        if menu.get('state') in (1,2):
            if not menu.get('selected_option',True):game.input(stick_y=90,frames=4)
            game.press(driver.A,frames=8)
        elif state.get('game_state')==11 or state.get('movie_pause') or state.get('movie_state'):
            game.press(driver.A,frames=8);game.input(frames=20)
        elif state.get('paused') or state.get('ui_scene') not in (10000,None):
            game.press(driver.A,frames=8)
        else:game.input(frames=20)
    raise TimeoutError(f'earned debt ending unfinished: {trace[-16:]}')

async def accept_ww(session,driver):
    helper_hash=sha(PROGRESSION_FILE)
    session.event('ww-helper-pin',file=str(PROGRESSION_FILE),sha256=helper_hash)
    games={}
    for slot,configured in session.runs.items():
        assert session.patches[slot][1]['debt']==100
        game=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
            configured['directory']/'ww-control',configured['save'],session.output/f'ww-native-{slot}.log')
        games[slot]=game;session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        boot=await asyncio.to_thread(driver.boot_day1,game,timeout=300)
        session.event('ww-normal-story-boot',slot=slot,state=boot['state'])
        initial_route=WWRoute(game,driver)
        initial=await asyncio.to_thread(initial_route.playable)
        assert len(initial['pikis'])==5 and all(p['kind']==1 for p in initial['pikis'])
        center=[sum(p['position'][i] for p in initial['pikis'])/5 for i in range(3)]
        await asyncio.to_thread(driver.walk_to,game,center,radius=50,timeout=45)
        await asyncio.to_thread(driver.aim_at,game,center,radius=15)
        await asyncio.to_thread(game.input,buttons=driver.B,frames=120)
        intro=await asyncio.to_thread(initial_route.playable)
        session.event('ww-genuine-initial-red-intro-before-any-scene-setup',slot=slot,state=intro)
        await session.start_client(slot)
    await until(lambda:all(session.ctx.clients[0][s] for s in (1,2)),'both original debt100 slots authenticated')
    progression=WWProgression(session,driver,games)
    recipient=1
    route=progression.routes[recipient];game=games[recipient]
    await asyncio.to_thread(route.scene,0)
    await asyncio.to_thread(route.command,'squad_setup',color=1,count=1,captain=0)
    await asyncio.to_thread(game.input,buttons=driver.B,frames=120)
    initial=await asyncio.to_thread(game.wait_state,lambda s:True)
    assert initial['courses']==1 and initial['equipment']==0 and initial['pokos']==0
    session.event('ww-before-earned-condition-blocked',state=initial,
        boundary='native unopened course flags before receipts; actual blocked world-map consumer is checked after earned debt')
    assert progression.source(recipient,512)==(2,10)
    geo=await progression.collect(2,10)
    first=await asyncio.to_thread(game.wait_state,
        lambda s:s.get('pokos',0)>=100 and s.get('equipment',0)&(1<<11),60,
        'actual native Geographic Projection and earned Pokos after durable delivery')
    assert first['pokos']>=100 and first['equipment']&(1<<11) and not first['equipment']&(1<<10)
    session.event('ww-geographic-only-earned-pokos',state=first,delivery=geo)
    # Native GameState::needRepayDemo notices the real AP Poko value itself;
    # no initial Sunset/menu setup or fake tutorial/story flags are needed.
    ending=await asyncio.to_thread(finish_earned_debt,game,driver)
    paid=ending['state'];world=paid['effects']['worldmap']
    assert paid['pokos']>=100 and paid['equipment']&(1<<11) and not paid['equipment']&(1<<10)
    assert not world['courses'][3]['selectable'] and not world['courses'][3]['dot_visible']
    session.event('ww-actual-earned-debt-ending-still-blocked-without-atlas',ending=ending)
    # Exercise the actual loaded-map poll, without leaving the map or calling
    # the bridge/native tick from the test. Model20 stopped its heartbeat here.
    snapshot_path=session.runs[recipient]['directory']/'bridge/snapshot.json'
    heartbeat_before=json.loads(snapshot_path.read_text(encoding='utf8'))['heartbeat']
    await until(lambda:json.loads(snapshot_path.read_text(encoding='utf8'))['heartbeat']>heartbeat_before,
        'actual world-map bridge heartbeat advancing without gameplay update',timeout=10)
    map_before_atlas=await asyncio.to_thread(game.wait_state,lambda s:True)
    assert map_before_atlas['game_state']==1 and map_before_atlas['effects']['worldmap']['state']==2
    session.event('ww-loaded-map-native-poll-advances',heartbeat_before=heartbeat_before,
        heartbeat_after=json.loads(snapshot_path.read_text(encoding='utf8'))['heartbeat'],state=map_before_atlas)
    assert progression.source(recipient,511)==(2,44)
    atlas=await progression.collect(2,44)
    opened=await asyncio.to_thread(game.wait_state,
        lambda s:'worldmap' in s.get('effects',{}) and s['effects']['worldmap']['courses'][3]['selectable']
            and s['effects']['worldmap']['courses'][3]['dot_visible'],60,'actual earned-debt/both-globe Wistful Wild map')
    assert opened['game_state']==1, 'late globe must apply while still on actual world map'
    assert opened['equipment']&(1<<10) and opened['equipment']&(1<<11)
    session.event('ww-earned-debt-and-both-generated-globes-visible-selectable',state=opened,delivery=atlas)
    landed=await progression.land(recipient,3)
    assert landed['game_state']==3 and landed['course']==3 and landed['cave']==0 and landed['movie_state']==0
    assert sha(PROGRESSION_FILE)==helper_hash,'shared Progression helper changed during WW scope'
    session.event('ww-debt-consumer-scope-passed',passed=True,recipient=recipient,initial=initial,geographic_only=first,
        earned_debt=ending,without_atlas=paid,with_both=opened,landed=landed,
        helper_sha256=helper_hash,shortcuts=SETUP+['original supported Debt100 option; primary debt10000 campaign pacing not claimed'])

async def main():
    args=make_parser(__doc__).parse_args()
    # Test route metadata follows the untouched generated seed; never modify
    # the APWorld, multidata, .appik2 placements or server slot fields.
    patch_path=next(args.fixture.glob('*.appik2'))
    with zipfile.ZipFile(patch_path) as archive:
        seed=json.loads(archive.read('patch.appik2'))['seed']
    route=json.loads(args.route_manifest.read_text(encoding='utf8'))
    route['primary_seed']=seed;route['ww_subscope']='earned_debt_both_globes_and_wistful_wild'
    args.route_manifest=args.output.parent/(args.output.name+'-route.json')
    assert not args.route_manifest.exists()
    args.route_manifest.write_text(json.dumps(route,indent=2)+'\n',encoding='utf8')
    helper=sha(PROGRESSION_FILE)
    route_hashes={str(path.resolve()):sha(path) for path in ROUTE_FILES}
    caught=None
    try:
        report=await run(args,acceptance=accept_ww,scope_gates=(),acceptance_kind='loaded_scene',boundary=__doc__)
    except BaseException as error:
        caught=error
        if not (args.output/'report.json').exists():raise
        report=json.loads((args.output/'report.json').read_text(encoding='utf8'))
    event=next((e for e in report['events'] if e['label']=='ww-debt-consumer-scope-passed'),None)
    report['subgates']={'earned_debt_both_globes_and_wistful_wild':{'passed':bool(event and event['passed'] and not caught),
        'event':'ww-debt-consumer-scope-passed','evidence':event,
        'broad_progression_gate_claimed':False}}
    report['orchestration_sha256'][str(PROGRESSION_FILE.resolve())]=helper
    report['execution_inputs_unchanged']['progression_helper']=sha(PROGRESSION_FILE)==helper
    report['orchestration_sha256'].update(route_hashes)
    report['execution_inputs_unchanged']['ww_route_helpers']=all(sha(Path(path))==digest for path,digest in route_hashes.items())
    if not report['execution_inputs_unchanged']['ww_route_helpers']:report['status']='failed'
    if not report['execution_inputs_unchanged']['progression_helper']:report['status']='failed'
    (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')
    print(json.dumps({'status':report['status'],'subgates':report['subgates'],'report':str(args.output/'report.json'),'failure':report['failure']},indent=2))
    if caught:raise caught
    if report['status']!='passed':raise AssertionError('WW execution input or subscope validation failed')

if __name__=='__main__':asyncio.run(main())
