"""Run isolated actor/goal cases with the stable normal appraisal input policy.

Explicit route composition keeps earlier executing helpers byte-identical.
Non-check Snow Bulborbs may receive a disclosed health-zero setup stimulus to
isolate exact carrier requirements; native death and all treasure delivery remain
production events. No combat, ordinary campaign travel or acquisition claim.
"""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
import test_loaded_gameplay_recruitment as loaded
import test_gameplay_remaining_goals as goals
from test_gameplay_settled_route import SettledRoute as StableRoute
from test_gameplay_tutorial import initial_red_intro
from test_progression_gameplay_real_server import Progression
from test_gameplay_real_server import make_parser,run
from test_real_server import ROOT,sha

EXTRA=[Path(__file__).with_name(n) for n in ('test_loaded_gameplay_recruitment.py',
    'test_gameplay_remaining_goals.py','test_gameplay_routes.py','test_progression_gameplay_real_server.py',
    'test_gameplay_settled_route.py','test_gameplay_tutorial.py')]
SHORTCUT='unrelated non-check Snow Bulborb health zero followed by actual native death; combat bypassed for precise carrier isolation'


class GoalRoute(StableRoute):
    def squad_at_actor(self,location,color,count):
        # Goals test actual delivery and completion, with spare real carriers.
        # The loaded branch below retains its exact-threshold squad sizes.
        return super().squad_at_actor(location,color,min(100,max(2,count*2)))


class StableProgression(Progression):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={s:GoalRoute(game,driver) for s,game in games.items()}


async def accept(session,driver):
    pins={str(p):sha(p) for p in EXTRA}
    session.event('composed-actor-route-inputs',orchestration_sha256=pins,boundary=__doc__)
    original_game=driver.GameplayClient
    class PreparedGame(original_game):
        def start(self):
            super().start()
            self.first_red_intro=initial_red_intro(self,driver)
            return self
    driver.GameplayClient=PreparedGame
    try:
        if session.args.case=='loaded':
            # Route factory injection only in this isolated test process; all
            # inherited carrying/AP assertions remain the original runner's.
            loaded.RecruitingRoute=StableRoute
            await loaded.accept(session,driver)
            for gate in session.gates.values():
                if gate['passed']:gate['shortcuts'].append(SHORTCUT)
        else:
            goals.Progression=StableProgression
            await goals.accept(session,driver)
            session.events[-1]['shortcuts'].append(SHORTCUT)
    finally:
        assert all(sha(Path(p))==digest for p,digest in pins.items()),'composed actor helper changed during execution'


async def main(args):
    goal={'poko':1,'count':2}.get(args.case)
    if goal:
        args.goal=goal
        directory,seed={1:('pokos280-2026101503','05072816437034409919'),
                        2:('treasures1-2026101504','85356692560853543606')}[goal]
        args.fixture=ROOT/'tests/fixtures'/directory/'generated'
        manifest=json.loads(args.route_manifest.read_text(encoding='utf8'));manifest['primary_seed']=seed
        manifest['goal_case']=goal
        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')
    pins={str(p):sha(p) for p in EXTRA}
    report=await run(args,acceptance=accept,scope_gates=('physical_replacements','local_remote_delivery','reconnect')
        if args.case=='loaded' else (),acceptance_kind='loaded_scene',boundary=__doc__)
    assert all(sha(Path(p))==digest for p,digest in pins.items())
    report['orchestration_sha256'].update(pins);report['execution_inputs_unchanged']['composed_helpers']=True
    (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8')


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--case',choices=('loaded','poko','count'),required=True)
    asyncio.run(main(parser.parse_args()))
