# SPDX-License-Identifier: AGPL-3.0-or-later
"""Schema-library decision gate.

Adopting a validation library (pydantic v2 behind a facade, or a small strict
types module) is gated on two things: a coercion matrix that pins exactly which
cross-type values are accepted, and a cost budget for the hot path. This module
is that gate. It also pins the descriptor surface a facade must preserve.

A pydantic migration must keep every row below unchanged; a row that flips is a
silent strictness change. Cases that currently fail are reported defects, not
migration requirements.
"""
from __future__ import annotations

import time

import pytest

from orchestrator import executor_protocol, schemas

from test_boundary_mutations import SCHEMA_BASELINES


def _accepts_schema(schema_name: str, field: str, value) -> bool:
    document = dict(SCHEMA_BASELINES[schema_name])
    document[field] = value
    try:
        schemas.validate(schema_name, document)
    except schemas.SchemaValidationError:
        return False
    return True


SCHEMA_COERCION_MATRIX = [
    # identifiers: scalar strings accepted, everything else rejected
    ("RunConfiguration", "run_id", "run-1", True),
    ("RunConfiguration", "run_id", "", False),
    ("RunConfiguration", "run_id", 1, False),
    ("RunConfiguration", "run_id", True, False),
    # mappings: subclasses accepted, scalars and lists rejected
    ("RunConfiguration", "root_contract", {}, True),
    ("RunConfiguration", "root_contract", {"k": 1}, True),
    ("RunConfiguration", "root_contract", [], False),
    ("RunConfiguration", "root_contract", "x", False),
    # budgets: int and float limits accepted, booleans and strings rejected
    ("RunConfiguration", "budgets", {"MODEL_COST": 1}, True),
    ("RunConfiguration", "budgets", {"MODEL_COST": 1.0}, True),
    ("RunConfiguration", "budgets", {"MODEL_COST": True}, False),
    ("RunConfiguration", "budgets", {"MODEL_COST": "1"}, False),
    ("RunConfiguration", "budgets", {}, False),
    # limits: zero and reals accepted, booleans rejected
    ("RunConfiguration", "limits", {"actions": 0}, True),
    ("RunConfiguration", "limits", {"actions": 1.0}, True),
    ("RunConfiguration", "limits", {"actions": True}, False),
    # policy_version: int only, floats and strings rejected
    ("RunConfiguration", "policy_version", 1, True),
    ("RunConfiguration", "policy_version", 1.0, False),
    ("RunConfiguration", "policy_version", "1", False),
    ("RunConfiguration", "policy_version", True, False),
    # schema_version: int only (boolean row is reported by the boundary table)
    ("RunConfiguration", "schema_version", 1, True),
    ("RunConfiguration", "schema_version", 1.0, False),
    ("RunConfiguration", "schema_version", "1", False),
    # enums: catalogue members accepted, case variants rejected
    ("ProgressRecord", "node_state", "READY", True),
    ("ProgressRecord", "node_state", "ready", False),
    ("ProgressRecord", "node_state", 1, False),
    # graph_version: non-negative int only
    ("ProgressRecord", "graph_version", 0, True),
    ("ProgressRecord", "graph_version", 3, True),
    ("ProgressRecord", "graph_version", 0.0, False),
    ("ProgressRecord", "graph_version", True, False),
    ("ProgressRecord", "graph_version", -1, False),
    ("ProgressRecord", "graph_version", "0", False),
    # total_cost: non-negative finite reals only
    ("RunResult", "total_cost", 0, True),
    ("RunResult", "total_cost", 0.0, True),
    ("RunResult", "total_cost", -0.0, True),
    ("RunResult", "total_cost", 1.5, True),
    ("RunResult", "total_cost", True, False),
    ("RunResult", "total_cost", float("nan"), False),
    ("RunResult", "total_cost", float("inf"), False),
    ("RunResult", "total_cost", -1, False),
    ("RunResult", "total_cost", "0", False),
    # evidence: a list accepted, a tuple rejected, scalars rejected
    ("EvidenceRetrieval", "evidence", [], True),
    ("EvidenceRetrieval", "evidence", [{"check": "BUILD"}], True),
    ("EvidenceRetrieval", "evidence", (), False),
    ("EvidenceRetrieval", "evidence", "x", False),
    ("EvidenceRetrieval", "evidence", {}, False),
]


@pytest.mark.parametrize(
    "schema_name,field,value,accepted",
    SCHEMA_COERCION_MATRIX,
    ids=[
        f"{schema}.{field}={value!r}"
        for schema, field, value, _ in SCHEMA_COERCION_MATRIX
    ],
)
def test_schema_coercion_matrix_is_unchanged(schema_name, field, value, accepted):
    assert _accepts_schema(schema_name, field, value) is accepted


@pytest.mark.parametrize(
    "field,value,accepted",
    [
        ("timeout_seconds", 0, True),
        ("timeout_seconds", 1, True),
        ("timeout_seconds", 1.0, True),
        ("timeout_seconds", True, False),
        ("timeout_seconds", "1", False),
        ("timeout_seconds", float("nan"), False),
        ("timeout_seconds", -1, False),
    ],
)
def test_request_numeric_coercion_matrix_is_unchanged(field, value, accepted):
    request = executor_protocol.build_request(
        run_id="run-1",
        action_id="action-1",
        attempt_id="attempt-1",
        attempt_token="token-1",
        node_id="node-1",
        node_contract_version=1,
        action_type="EXECUTE",
        resolved_inputs=[],
        owned_scope_include=["src/**"],
        owned_scope_exclude=[],
        base_commit="commit-1",
        worktree_id="worktree-1",
        timeout_seconds=1.0,
        cancellation_token="cancel-1",
        budget_commitment={"amount": 1.0, "hard_limit": 1.0, "dimension": "MODEL_COST"},
        environment_version="env-1",
    )
    request[field] = value
    try:
        executor_protocol.validate_request(request, expected_token="token-1")
    except executor_protocol.ProtocolViolation:
        assert not accepted
    else:
        assert accepted


def test_public_schema_surface_is_available_for_a_facade():
    assert schemas.ALL_SCHEMAS
    for name, schema in schemas.ALL_SCHEMAS.items():
        assert schema.name == name
        assert isinstance(schema.schema_version, int)
        for field in schema.fields:
            assert isinstance(field, schemas.FieldSpec)
            assert field.name
    assert issubclass(schemas.SchemaValidationError, Exception)


def test_hot_path_validation_cost_stays_within_budget():
    document = SCHEMA_BASELINES["RunConfiguration"]
    iterations = 2000
    started = time.perf_counter()
    for _ in range(iterations):
        schemas.validate("RunConfiguration", document)
    average = (time.perf_counter() - started) / iterations
    # Generous baseline budget: the gate is a decision input for a facade
    # migration, not a micro-optimisation target.
    assert average < 1e-3, f"average validation cost {average * 1e6:.1f}us exceeds the budget"
