"""Continue equipment with a retained pre-Orb sample from the same WFG scene.

EC's authored main cutoff stays30 in both settings. WFG5's actual pre-item
cutoff45 is retained from the real earlier location61 arrival; its authored
Stellar main cutoff30 provides a directly observed production light output.
Original baselines, acquired items and server history remain unchanged.
"""
import asyncio
import hashlib
import json
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_worker_recovery import RecoveryEquipment, EXTRA
from test_gameplay_real_server import make_parser, run


SOURCE = Path(__file__).resolve().parents[1] / 'output/gameplay-equipment-model22-12/report.json'
WFG = (1, 1717514290, 4)


def retained_light_baseline(report):
    candidates = [e for e in report['events'] if e['label'] == 'equipment-generated-physical-delivery'
                  and e['source'] == 1 and e['location'] == 61]
    assert len(candidates) == 1, 'one actual pre-Orb WFG arrival sample required'
    event = candidates[0]; state = event['after']
    assert (state['course'], state['cave'], state['floor']) == WFG
    assert state['physical_deliveries']['61'] > 0
    assert not state['equipment'] & (1 << 4), 'retained baseline must precede actual Stellar Orb'
    light = state['effects']['light']
    assert light['stellar_increment'] == 0 and light['color_ratio'] == 0
    assert light['main_cutoff'] == 45
    return state, event


class LightingEquipment(RecoveryEquipment):
    def __init__(self, session, driver, games):
        super().__init__(session, driver, games)
        source = json.loads(SOURCE.read_text())
        assert source['native_sha256'] == equipment.sha(session.args.native)
        assert source['client_sha256'] == equipment.sha(session.args.client)
        assert all(source['execution_inputs_unchanged'].values())
        before, event = retained_light_baseline(source)
        baselines = session.consumer_state['baselines']
        if 'light_consumer_before' in baselines:
            assert baselines['light_consumer_before'] == before
        else:
            baselines['light_consumer_before'] = before
        session.event('equipment-retained-native-light-baseline', source_report=str(SOURCE),
            source_report_sha256=hashlib.sha256(SOURCE.read_bytes()).hexdigest(),
            event_label=event['label'], event_seconds=event['seconds'], source=1, location=61,
            scene=list(WFG), before=before,
            boundary='genuine prior same-runtime/same-slot WFG state before earned505; original EC baseline retained unchanged')

    async def acquire(self, recipient, item):
        result = await super().acquire(recipient, item)
        if item == 505:
            assert recipient == 1
            await asyncio.to_thread(self.routes[1].scene, *WFG)
        return result


async def main(args):
    equipment.Equipment = LightingEquipment
    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'))
    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()))
