"""Synthetic support-first arbitration using public KVRM; no external effects.

Pinned core: 85fe4dc8a4f5a7010dd19f98bd8a934554fb8663.
Scores are hand-authored, not model measurements or calibrated probabilities.
No Jev API, policy-engine integration, or production executor is used.
"""
from __future__ import annotations
import json
from kvrm_core.types import ActionSpec, RegistrySpec, DecisionInput, DecisionCandidate, ExecutionResult, ExecutionStatus
from kvrm_core.selectors import EvidenceFusionHybridSelector
from kvrm_core.runtime import KVRMRuntime
from kvrm_core.validation import DeterministicValidator

PUBLIC_REVISION = '85fe4dc8a4f5a7010dd19f98bd8a934554fb8663'

class FixedEvidence:
    def __init__(self, rows, name):
        self.rows, self.name = rows, name
    def select(self, decision_input):
        return [DecisionCandidate(action_id=action, confidence=score, source=self.name) for action, score in self.rows]

class SimulationOnly:
    def __init__(self):
        self.calls = []
    def execute(self, candidate):
        self.calls.append(candidate.action_id)
        return ExecutionResult(status=ExecutionStatus.SUCCESS, action_id=candidate.action_id,
                               output={'simulation_only': True, 'external_effects': False})

def make_registry(version):
    def condition(feature):
        return {'feature': feature, 'op': 'eq', 'value': True}
    rollback = condition('rollback_ready')
    if version == '2':
        rollback = {'all': [rollback, condition('incident_commander_approval')]}
    return RegistrySpec(registry_name='support-first-example', version=version, actions=[
        ActionSpec(action_id='rollback', name='Rollback', description='Simulated rollback', support_spec=rollback),
        ActionSpec(action_id='restart', name='Restart', description='Simulated restart', support_spec=condition('restart_ready')),
        ActionSpec(action_id='human_review', name='Review', description='Simulated handoff', tags=['fallback'],
                   parameters_schema={'type': 'object', 'properties': {'reason': {'type': 'string'}}},
                   support_spec=condition('reviewer_available')),
    ])

CASES = [
    ('high_score_unsupported', '1', {'rollback_ready': False, 'restart_ready': True, 'reviewer_available': False}, ['restart']),
    ('both_supported', '1', {'rollback_ready': True, 'restart_ready': True, 'reviewer_available': False}, ['rollback']),
    ('new_contract_same_proposals', '2', {'rollback_ready': True, 'restart_ready': True, 'reviewer_available': False}, ['restart']),
    ('supported_handoff', '1', {'rollback_ready': False, 'restart_ready': False, 'reviewer_available': True}, ['human_review']),
    ('handoff_unavailable', '1', {'rollback_ready': False, 'restart_ready': False, 'reviewer_available': False}, []),
]

def evaluate_case(case):
    name, version, features, expected = case
    reg = make_registry(version)
    # Identical proposal sources and scores in every case. No retraining occurs.
    selector = EvidenceFusionHybridSelector(
        registry=reg,
        retrieval_selector=FixedEvidence([('rollback', .99)], 'retrieval'),
        rule_selector=FixedEvidence([('restart', .90)], 'rule'),
        prototype_selector=FixedEvidence([('restart', .86)], 'prototype'),
        fallback_action_id='human_review',
    )
    executor = SimulationOnly()
    runtime = KVRMRuntime(reg, selector, DeterministicValidator(reg), executor, fallback_action_id='human_review')
    result = runtime.decide_and_execute(DecisionInput(case_id=name, features=features))
    return {'case': name, 'registry_version': version, 'features': features,
            'expected_simulated_calls': expected, 'simulated_calls': executor.calls,
            'final_status': result.final_status.value,
            'selected_evidence': result.audit_record.selected_evidence,
            'passed': executor.calls == expected}

def run():
    rows = [evaluate_case(case) for case in CASES]
    return {'synthetic': True, 'production_writes': 0, 'public_core_revision': PUBLIC_REVISION,
            'proposal_scores': {'retrieval_rollback': .99, 'rule_restart': .90, 'prototype_restart': .86},
            'scope': 'Fixed synthetic proposals; in-memory executor; not a Jev comparison or customer benchmark. Registry version 2 is loaded into a newly constructed runtime, not hot-reloaded.',
            'passed': sum(row['passed'] for row in rows), 'total': len(rows), 'cases': rows}

if __name__ == '__main__':
    result = run(); print(json.dumps(result, indent=2))
    raise SystemExit(0 if result['passed'] == result['total'] else 1)
