"""Synthetic, non-executing KVRM approval-boundary example.

Run with kvrm-core on PYTHONPATH. The published example is checked against
public commit 85fe4dc8a4f5a7010dd19f98bd8a934554fb8663. No network or real
posting executor is present. This is not a learned-selector benchmark.
"""
from __future__ import annotations
import json
from kvrm_core.types import ActionSpec, RegistrySpec, DecisionInput, DecisionCandidate, ExecutionResult, ExecutionStatus
from kvrm_core.runtime import KVRMRuntime
from kvrm_core.validation import DeterministicValidator

PUBLIC_REVISION = '85fe4dc8a4f5a7010dd19f98bd8a934554fb8663'

class ProposedAction:
    def __init__(self, action, confidence, parameters):
        self.action, self.confidence, self.parameters = action, confidence, parameters
    def select(self, decision_input):
        return [DecisionCandidate(action_id=self.action, confidence=self.confidence,
                                  parameters=self.parameters, source='synthetic_proposal')]

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 registry():
    return RegistrySpec(registry_name='synthetic-approval-boundary', version='1.0.0',
        context_schema={'approved': {'type': 'boolean'}, 'window_open': {'type': 'boolean'}},
        actions=[
            ActionSpec(action_id='publish_draft', name='Simulated publish', description='Records only an in-memory call.',
                parameters_schema={'type': 'object', 'properties': {'draft_id': {'type': 'string', 'enum': ['demo-1']}}, 'required': ['draft_id']},
                support_spec={'all': [{'feature': 'approved', 'op': 'eq', 'value': True},
                                      {'feature': 'window_open', 'op': 'eq', 'value': True}]}),
            ActionSpec(action_id='hold_draft', name='Simulated hold', description='Records only an in-memory hold.'),
        ])

CASES = [
    ('approval_present', 'publish_draft', {'approved': True, 'window_open': True}, {'draft_id': 'demo-1'}, .99, True),
    ('approval_absent', 'publish_draft', {'approved': False, 'window_open': True}, {'draft_id': 'demo-1'}, .99, False),
    ('approval_missing', 'publish_draft', {'window_open': True}, {'draft_id': 'demo-1'}, .99, False),
    ('window_closed', 'publish_draft', {'approved': True, 'window_open': False}, {'draft_id': 'demo-1'}, .99, False),
    ('unregistered_action', 'publish_anything', {'approved': True, 'window_open': True}, {'draft_id': 'demo-1'}, .99, False),
    ('invalid_parameter', 'publish_draft', {'approved': True, 'window_open': True}, {'draft_id': 123}, .99, False),
    ('low_confidence', 'publish_draft', {'approved': True, 'window_open': True}, {'draft_id': 'demo-1'}, .1, False),
    ('hold_without_approval', 'hold_draft', {'approved': False, 'window_open': False}, {}, .99, True),
]

def simple_rules(action, features, parameters, confidence):
    """Independent baseline for this small, deliberately simple contract."""
    if confidence < .5:
        return False
    if action == 'hold_draft':
        return True
    return (action == 'publish_draft' and features.get('approved') is True
            and features.get('window_open') is True and parameters.get('draft_id') == 'demo-1')

def validator(reg):
    # The pinned public core does not fully validate parameter types/enums.
    # Enforce the exact demo target explicitly; this is a domain-authored guard.
    return DeterministicValidator(reg, preconditions={
        'publish_draft': lambda params: type(params.get('draft_id')) is str and params['draft_id'] == 'demo-1',
    })

def run():
    rows = []
    for name, action, features, parameters, confidence, expected in CASES:
        reg = registry(); executor = SimulationOnly()
        runtime = KVRMRuntime(reg, ProposedAction(action, confidence, parameters),
                              validator(reg), executor, threshold=.5, fallback_action_id=None)
        result = runtime.decide_and_execute(DecisionInput(case_id=name, features=features))
        allowed = bool(executor.calls)
        baseline = simple_rules(action, features, parameters, confidence)
        rows.append({'case': name, 'expected_allowed': expected, 'kvrm_allowed': allowed,
                     'rules_allowed': baseline, 'status': result.final_status.value,
                     'reason': result.validation_reason, 'simulated_executor_calls': len(executor.calls),
                     'passed': allowed == expected == baseline and len(executor.calls) <= 1})
    return {'synthetic': True, 'production_writes': 0, 'public_core_revision': PUBLIC_REVISION,
            'scope': 'Eight hand-authored cases; fixed proposals; in-memory executor; not a production or learned-model benchmark.',
            'conclusion': 'KVRM and simple rules agree on all cases if checks pass. This demonstrates a boundary, not superiority.',
            'passed': sum(row['passed'] for row in rows), 'total': len(rows), 'cases': rows}

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