"""Exercise all three unchanged original goals with real loaded-game actors.

These targeted routes bypass campaign travel and squad acquisition, and set a
real enemy's health to zero for Titan's death/drop path. They never call a
treasure, goal, reward or AP check callback. Normal card/campaign proof is separate.
"""
from __future__ import annotations
import asyncio
import copy
import json
from pathlib import Path
import sys
import time
from test_gameplay_real_server import GATES, make_parser, run
from test_loaded_gameplay_real_server import LoadedRoute, SETUP
from test_real_server import AP_REVISION, ROOT, sha, until

FIXTURES={0:('louie-2026101502-r2','64277725796957322899'),
          1:('pokos280-2026101503','05072816437034409919'),
          2:('treasures1-2026101504','85356692560853543606')}


def case_acceptance(win):
    async def accept(session,driver):
        games={}
        routes={}
        for slot,configured in session.runs.items():
            assert session.patches[slot][1]['win_condition']==win
            game=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
                configured['directory']/'goal-control',configured['save'],session.output/f'goal-{slot}.log')
            games[slot]=game
            session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
            await asyncio.to_thread(game.start)
            entry=await asyncio.to_thread(driver.boot_day1,game,timeout=240)
            session.event('goal-normal-boot',slot=slot,state=entry['state'])
            routes[slot]=LoadedRoute(game,driver)
            await session.start_client(slot)
        await until(lambda:all(session.ctx.clients[0][s] for s in (1,2)), 'both original-goal slots authenticated')
        assert all(session.ctx.client_game_state[0,s]!=30 for s in (1,2))
        assert all(not session.native_journal(s)['receipts'] and not session.native_journal(s)['louie'] for s in (1,2))
        session.event('absent-original-condition-not-completed',goal=win)

        async def carry(slot,course,cave,floor,location,color=1,buried=False,boss=False):
            route=routes[slot]
            await asyncio.to_thread(route.scene,course,cave,floor)
            if boss:
                before=await asyncio.to_thread(games[slot].wait_state,lambda s:True)
                enemy=next(e for e in before['loaded']['actor_audit']['enemies'] if e['location']==location)
                captured=next(a for a in before['loaded']['actor_audit']['actors'] if a['location']==location)
                assert enemy['health']>0 and captured['captured_now'] and captured['collision_model_matches']
                assert enemy['held_pellet']==captured['address']
                position=list(enemy['position'])
                position[0]-=max(10,min(50,enemy['private_radius']*0.25))
                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)
                deadline=time.monotonic()+120
                while True:
                    await asyncio.to_thread(games[slot].input,frames=20)
                    awake=await asyncio.to_thread(route.playable)
                    enemy=next(e for e in awake['loaded']['actor_audit']['enemies'] if e['location']==location)
                    if enemy['state']!=1:break  # real Titan Stay requires proximity before health matters
                    if time.monotonic()>deadline:raise TimeoutError('real Titan never entered its boot-up/Land lifecycle')
                session.event('real-titan-proximity-boot-up',slot=slot,state=awake)
                session.event('real-titan-before-controlled-defeat',slot=slot,enemy=enemy)
                await asyncio.to_thread(route.command,'actor_defeat',location=location)
                # Health-only setup can be acknowledged while a discovery movie
                # is active. Advance its ordinary UI before waiting for the FSM.
                await asyncio.to_thread(route.playable)
            _,actor,binding=await asyncio.to_thread(route.physical,location,180 if boss else 30)
            if boss:
                released=next(a for a in (await asyncio.to_thread(games[slot].wait_state,lambda s:True))['loaded']['actor_audit']['actors'] if a['location']==location)
                assert released['address']==captured['address'] and not released['captured_now'] and released['collision_model_matches']
                session.event('same-captured-louie-released-by-native-death',before=captured,after=released)
            if buried:assert binding['depth']>0 and binding['depth_max']>0
            baseline=await asyncio.to_thread(games[slot].wait_state,lambda s:True)
            await asyncio.to_thread(route.squad_at_actor,location,color,binding['min_carriers'])
            attached,_=await asyncio.to_thread(route.attach,location,binding['min_carriers'])
            after=await asyncio.to_thread(route.delivered,location,baseline)
            session.event('original-goal-actual-actor-delivery',slot=slot,goal=win,location=location,
                          binding=binding,attached=attached,after=after,trace=route.trace.copy())
            await session.wait_checks({slot:[location]},timeout=60)

        if win==0:
            for slot in (1,2):await carry(slot,3,1818177587,13,201,boss=True)
        elif win==1:
            await carry(1,0,0,0,1)
            await carry(1,1,0,0,43,color=4,buried=True)
            await carry(1,0,1952395313,1,10)
            await carry(1,0,1952395313,0,9)
            await carry(2,0,0,0,1)
        else:
            for slot in (1,2):await carry(slot,0,0,0,1)
        await session.wait_rewards(timeout=60)
        await until(lambda:all(session.ctx.client_game_state[0,s]==30 for s in (1,2)),
                    'actual original-goal AP status30 for both slots',timeout=60)
        observations={}
        for slot in (1,2):
            observation=await asyncio.to_thread(games[slot].wait_state,lambda s:True)
            session.assert_native_reward_state(slot,observation)
            journal=session.native_journal(slot)
            if win==0:assert journal['louie'] and 201 in journal['checks']
            elif win==1:assert observation['pokos']>=session.patches[slot][1]['poko_amount']
            else:assert len(journal['receipts'])>=session.patches[slot][1]['treasure_amount']
            observations[str(slot)]={'native':observation,'journal':journal,'server_status':30}
        session.event('original-goal-case-passed',win_condition=win,observations=observations,
                      shortcuts=SETUP+(['Titan health set0; actual FSM death/drop/animation then carrying; battle input bypassed'] if win==0 else []))
    return accept


async def run_goals(args):
    output=args.output.resolve()
    output.mkdir(parents=True,exist_ok=False)
    base_manifest=json.loads(args.route_manifest.read_text(encoding='utf8'))
    helper_modules=('test_gameplay_real_server','test_real_server','test_loaded_gameplay_real_server',__name__)
    helpers={str(Path(sys.modules[name].__file__).resolve()):sha(Path(sys.modules[name].__file__)) for name in helper_modules}
    original_pair={'native':sha(args.native),'client':sha(args.client)}
    original_runtime={path.name:sha(path) for path in args.native.parent.glob('*.dll')}
    cases=[]
    try:
        for win,(directory,seed) in FIXTURES.items():
            assert all(sha(Path(path))==digest for path,digest in helpers.items()), 'goal helper changed between original-goal cases'
            assert sha(args.native)==original_pair['native'] and sha(args.client)==original_pair['client']
            assert original_runtime=={path.name:sha(path) for path in args.native.parent.glob('*.dll')}
            case=copy.copy(args)
            case.fixture=ROOT/'tests/fixtures'/directory/'generated'
            case.output=output/f'goal-{win}'
            manifest=copy.deepcopy(base_manifest)
            manifest['primary_seed']=seed
            manifest['goal_case']=win
            case.route_manifest=output/f'goal-{win}-route.json'
            case.route_manifest.write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf8')
            # Empty broad scope is deliberate: a single goal case is not a
            # passing original_goals gate and the aggregator rejects it alone.
            report=await run(case,acceptance=case_acceptance(win),scope_gates=(),
                acceptance_kind='loaded_scene',boundary=__doc__)
            assert any(e['label']=='original-goal-case-passed' for e in report['events'])
            cases.append({'win_condition':win,'report':str(case.output/'report.json'),
                          'sha256':sha(case.output/'report.json'),'result':report})
    finally:
        outer_unchanged=all(sha(Path(path))==digest for path,digest in helpers.items())
        outer_unchanged=outer_unchanged and sha(args.native)==original_pair['native'] and sha(args.client)==original_pair['client']
        outer_unchanged=outer_unchanged and original_runtime=={path.name:sha(path) for path in args.native.parent.glob('*.dll')}
        all_passed=len(cases)==3 and outer_unchanged and all(c['result']['status']=='passed' for c in cases)
        gates={name:{'passed':False,'evidence':[],'shortcuts':[], 'remaining':'outside this all-goals scope'} for name in GATES}
        gates['original_goals']={'passed':all_passed,'evidence':cases,
            'shortcuts':SETUP+['Titan health set0 then actual native death/drop/carry; battle input bypassed'],
            'remaining':None if all_passed else 'one or more original native gameplay goals not proved'}
        result={'format':'pikmin2-original-gameplay-goals-v1','status':'passed' if all_passed else 'failed',
            'scope_gates':['original_goals'],'acceptance_kind':'loaded_scene',
            'ap_revision':AP_REVISION,'toolkit_revision':'ac39b39f296b073553ecd4f9c486b9d14beda9eb',
            'apworld_sha256':base_manifest['apworld_sha256'],'catalog_sha256':sha(ROOT/'contract.json'),
            'native_sha256':original_pair['native'],'client_sha256':original_pair['client'],
            'native_runtime_sha256':original_runtime,'orchestration_sha256':helpers,
            'execution_inputs_unchanged':{'outer_scope':outer_unchanged,'all_goal_cases':all_passed and all(all(c['result']['execution_inputs_unchanged'].values()) for c in cases)},
            'gates':gates,'boundary':__doc__,'source_reports':[{k:c[k] for k in ('win_condition','report','sha256')} for c in cases]}
        (output/'report.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf8')
    return result


if __name__=='__main__':
    asyncio.run(run_goals(make_parser(__doc__).parse_args()))
