"""Grounded loaded/goal routes; physical thresholds stay exact, burial uses spare real carriers."""
import asyncio
from pathlib import Path
import test_gameplay_actor_cases as cases
from test_equipment_survivors import NearConsumerRoute
from test_gameplay_settled_route import SettledRoute
from test_gameplay_real_server import make_parser


class HeldAwarePhysical:
    def physical(self,location,timeout=30):
        def released(s):
            loaded=s.get('loaded',{});bindings=[b for b in loaded.get('physical',[]) if b['location']==location]
            if not bindings or not any(p['location_id']==location for p in s.get('pellets',[])):return False
            audit=loaded.get('actor_audit',{});held={e.get('held_pellet',0) for e in audit.get('enemies',[])}-{0}
            buried=bindings[0]['depth_max']>0
            return not any(a['location']==location and (a['pool_flags']&0x65 or
                (a.get('captured_now',False) and (not buried or a['address'] in held)))
                for a in audit.get('actors',[]))
        state=self.game.wait_state(released,timeout,f'authored loose/ground-buried pellet {location}, not enemy-held')
        actor=next(p for p in state['pellets'] if p['location_id']==location)
        binding=next(b for b in state['loaded']['physical'] if b['location']==location)
        assert binding['collision_model_matches'] and actor['minimum']==binding['min_carriers']
        return state,actor,binding


class GroundedGoalRoute(HeldAwarePhysical,NearConsumerRoute):
    def squad_at_actor(self,location,color,count):
        return super().squad_at_actor(location,color,min(100,max(2,count*2)))


class GroundedLoadedRoute(HeldAwarePhysical,NearConsumerRoute):
    def squad_at_actor(self,location,color,count):
        _,_,binding=self.physical(location)
        if binding['depth_max']>0:
            # This is a positive digging/carry case. The earlier4/5 and19/20
            # native weight cases below retain exact sizes and assertions.
            return super().squad_at_actor(location,color,min(100,max(2,count*2)))
        return SettledRoute.squad_at_actor(self,location,color,count)


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--case',choices=('loaded','poko','count'),required=True)
    args=parser.parse_args()
    cases.GoalRoute=GroundedGoalRoute
    cases.StableRoute=GroundedLoadedRoute
    cases.EXTRA.extend(Path(__file__).with_name(n) for n in ('test_gameplay_grounded_cases.py',
        'test_gameplay_carriers.py','test_equipment_survivors.py','test_equipment_gameplay_real_server.py'))
    asyncio.run(cases.main(args))
