"""Earn equipment through the untouched seed's alternate original slots.

The original slot2 damage baseline remains retained. Before earning slot1's
still-unowned Justice Alloy, measure a new slot1 stimulus, then collect its
original generated FC Joy Receptacle reward and repeat that same native
consumer on slot1. Boots similarly use a new slot1 speed control; Key uses
slot2's genuine negative Title callback and its own card/title/restart path.
The positive Key route has40 real Yellow workers for its ordinary return path;
the independent exact carrier-threshold cases remain unchanged. No placement,
AP history, item or health is assigned.
"""
import asyncio
import json
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_survivor_setup import SurvivorEquipment, SurvivorRoute, EXTRA, SOURCE
from test_gameplay_real_server import make_parser, run


class OriginalAlternateRoute(SurvivorRoute):
    def squad_at_actor(self,location,color,count):
        if location==87:count=max(count,40)
        return super().squad_at_actor(location,color,count)


class OriginalAlternateEquipment(SurvivorEquipment):
    speed_consumer_slot=1
    key_consumer_slot=2

    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={slot:OriginalAlternateRoute(game,driver) for slot,game in games.items()}
        for route in self.routes.values():route.session=session

    async def controller_effect(self,slot,kind):
        return await super().controller_effect(1 if kind=='speed' else slot,kind)

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

    async def acquire(self, recipient, item):
        if item == 506:
            assert self.source(1,506)==(2,30), 'alternate must use the unchanged original P2 FC30 to P1 Justice placement'
            baseline=self.session.consumer_state['baselines']
            if 'damage_consumer_before' not in baseline:
                await self.empty_overworld(1)
                before=await self.hazard('damage')
                assert before['slot']==1 and not before['justice_alloy'] and before['damage_observed']>0
                baseline['damage_consumer_before']=before
                self.session.event('equipment-alternate-original-slot-baseline',item_id=item,
                    slot=1,before=before,boundary=__doc__)
            recipient=1
        elif item==508:
            assert self.source(1,508)==(2,102), 'alternate must preserve original P2 CoS102 to P1 Boots placement'
            baseline=self.session.consumer_state['baselines']
            if 'speed_consumer_before' not in baseline:
                await self.empty_overworld(1)
                before=await self.controller_effect(1,'speed')
                assert not before[1]['equipment'] & (1 << (508-501))
                baseline['speed_consumer_before']={'slot':1,'sample':before}
                self.session.event('equipment-alternate-original-slot-baseline',item_id=item,slot=1,before=before,boundary=__doc__)
            recipient=1
        elif item==513:
            assert self.source(2,513)==(2,87), 'alternate must preserve original P2 PP87 to P2 Key placement'
            baseline=self.session.consumer_state['baselines']
            if 'key_consumer_before' not in baseline:
                state=await asyncio.to_thread(self.games[2].wait_state,lambda s:True)
                before=dict(state['effects'],slot=2)
                assert not before['global_challenge'] and before['title_menu_opens']>0 and before['title_challenge_state']==0
                baseline['key_consumer_before']=before
                self.session.event('equipment-alternate-original-slot-baseline',item_id=item,slot=2,before=before,
                    boundary='fresh readback of this same native process original TitleMenu callback before its still-unowned Key; no flag assignment')
            recipient=2
        return await super().acquire(recipient,item)


async def main(args):
    equipment.Equipment=OriginalAlternateEquipment
    equipment.HELPERS.extend(Path(__file__).with_name(n) for n in EXTRA)
    equipment.HELPERS.extend(Path(__file__).with_name(n) for n in (
        'test_equipment_practical.py','test_gameplay_arrival_policy.py','test_equipment_charged.py',
        'test_equipment_resupply.py','test_equipment_capacity.py','test_equipment_lift.py',
        'test_equipment_glint_press.py','test_equipment_worker_recovery.py','test_equipment_lighting_route.py',
        'test_equipment_gate_route.py','test_equipment_dirigibug.py','test_equipment_survivor_setup.py',
        'test_equipment_original_alternate.py'))
    equipment.HELPERS.append(SOURCE)
    report=await run(args,acceptance=equipment.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')


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--resume-checkpoint',type=Path)
    asyncio.run(main(parser.parse_args()))
