"""Original Poko/count goals through real cave treasure delivery, without bag shortcuts.

Later scene/squad/captain setup is disclosed. The already passing original Louie
case is retained separately; this tool does not claim all original goals alone.
"""
from __future__ import annotations
import asyncio
import copy
import json
from pathlib import Path
from test_gameplay_real_server import make_parser,run
from test_progression_gameplay_real_server import Progression
from test_real_server import ROOT,sha,until

HELPER=Path(__file__).with_name('test_progression_gameplay_real_server.py')


async def accept(session,driver):
    helper=sha(HELPER);games={}
    goal=session.args.goal
    for slot,cfg in session.runs.items():
        assert session.patches[slot][1]['win_condition']==goal
        game=driver.GameplayClient(session.args.native,session.args.assets,cfg['profile'],
            cfg['directory']/'goal-control',cfg['save'],session.output/f'goal-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('goal-normal-story-entry',slot=slot,route=await asyncio.to_thread(driver.boot_day1,game,timeout=300))
        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'] for s in (1,2))
    session.event('absent-original-condition-not-completed',goal=goal)
    progression=Progression(session,driver,games)
    if goal==1:
        # Actual untouched primary placements: P1 gets100+90+100=290,
        # P2 gets its own Mirrored Element300. No starting paper bag bypass.
        cases=((1,10),(2,10),(1,49),(2,9))
    else:
        # The original generated count1 seed needs one indexed receipt for
        # each recipient. Prefer authored loose EC actors to later hazards.
        cases=[]
        for recipient in (1,2):
            candidates=[]
            for source in (1,2):
                for location,(item,target,_) in session.ctx.locations[source].items():
                    row=progression.rows.get(location)
                    if target==recipient and row and row['kind']=='cave' and row['name'].startswith('EC '):
                        candidates.append((row['sublevel'],source,location))
            assert candidates
            _,source,location=min(candidates)
            cases.append((source,location))
    deliveries=[]
    for source,location in cases:
        deliveries.append(await progression.collect(source,location))
    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,game in games.items():
        state=await asyncio.to_thread(game.wait_state,lambda s:True);session.assert_native_reward_state(slot,state)
        journal=session.native_journal(slot)
        if goal==1:assert state['pokos']>=session.patches[slot][1]['poko_amount']
        else:assert len(journal['receipts'])>=session.patches[slot][1]['treasure_amount']
        observations[str(slot)]={'native':state,'journal':journal,'server_status':30}
    assert sha(HELPER)==helper,'Progression collector changed during goal execution'
    session.event('original-goal-case-passed',win_condition=goal,observations=observations,
        deliveries=deliveries,helper_sha256=helper,
        shortcuts=['normal story entry; later real cave scene/squad/captain setup; actual carry/AP/native goal consumers'])


async def main(args):
    original=args.route_manifest
    directory,seed={1:('pokos280-2026101503','05072816437034409919'),
                    2:('treasures1-2026101504','85356692560853543606')}[args.goal]
    args.fixture=ROOT/'tests/fixtures'/directory/'generated'
    manifest=json.loads(original.read_text(encoding='utf8'));manifest['primary_seed']=seed;manifest['goal_case']=args.goal
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.route_manifest=args.output.parent/(args.output.name+'-route.json')
    assert not args.route_manifest.exists()
    args.route_manifest.write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf8')
    report=await run(args,acceptance=accept,scope_gates=(),acceptance_kind='loaded_scene',boundary=__doc__)
    assert any(e['label']=='original-goal-case-passed' for e in report['events'])
    return report


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--goal',type=int,choices=(1,2),required=True)
    asyncio.run(main(parser.parse_args()))
