# SPDX-License-Identifier: AGPL-3.0-or-later
"""Boundary mutation table for every validation surface.

Each table is derived from the authoritative definition — the ``FieldSpec`` list
for harness schemas, the ``EventSpec`` list for events — so a newly added field
is covered without editing this file. A field whose validator is not
categorised fails the coverage test, forcing a conscious decision rather than
silent drift.

For every field the table injects booleans, non-finite numbers, negatives,
``None``, strings-where-numbers, scalars-where-collections,
collections-where-scalars, unknown enum values, and unknown references, and
asserts rejection. The event table additionally asserts that a rejected
admission persists nothing.
"""
from __future__ import annotations

from typing import Any

import pytest

from orchestrator import events, schemas
from orchestrator.executor_protocol import (
    RESPONSE_SCHEMA_VERSION,
    ProtocolViolation,
    ResolvedInput,
    build_request,
    validate_request,
    validate_response,
)
from orchestrator.glossary import executor_response_statuses
from orchestrator.model import BudgetRecord, Ledger, LedgerStateError, OvercommitmentError
from orchestrator.store import EventStore

BAD_STRINGS = [None, "", 0, [], {}, True]
BAD_MAPPINGS = [None, [], "x", 0, True]
BAD_NUMERIC = [True, False, float("nan"), float("inf"), float("-inf"), -1, None, "1", [], {}]
BAD_POSITIVE_INT = [True, 0, -1, 1.5, None, "1", [], {}]
BAD_BUDGETS = [
    None,
    [],
    "x",
    0,
    {},
    {"MODEL_COST": True},
    {"MODEL_COST": float("nan")},
    {"MODEL_COST": float("inf")},
    {"MODEL_COST": -1},
    {"MODEL_COST": 0},
    {"UNKNOWN_DIMENSION": 1.0},
]
BAD_RUN_LIMITS = [
    None,
    [],
    "x",
    {"actions": True},
    {"actions": float("nan")},
    {"actions": float("inf")},
    {"actions": -1},
    {"unknown_limit": 1},
]
BAD_NESTED = [None, "x", [], 1, {}, True]
BAD_ENUM = ["lower_case", "UNKNOWN", 1, None, [], {}]
# Nested enum fields currently treat an explicit ``None`` as "absent" and skip
# validation; that gap is pinned by test_nested_enum_rejects_none below, so the
# general table does not include it here.
BAD_ENUM_NO_NONE = ["lower_case", "UNKNOWN", 1, [], {}]
BAD_LAMBDA = [None, -1, "1", 1.5, {}]
# ``True`` is deliberately excluded: it currently passes the version check
# because ``True == 1``. That gap is pinned by test_schema_version_rejects_boolean.
BAD_SCHEMA_VERSION = [0, -1, 1.5, None, "1", [], {}]


def _bad_values_for(field: schemas.FieldSpec):
    if field.enum_values is not None:
        return BAD_ENUM
    validator = field.validator
    if validator is schemas._non_empty_str:
        return BAD_STRINGS
    if validator is schemas._mapping:
        return BAD_MAPPINGS
    if validator in (schemas._positive_number, schemas._non_negative_number):
        return BAD_NUMERIC
    if validator is schemas._positive_int:
        return BAD_POSITIVE_INT
    if validator is schemas._budgets:
        return BAD_BUDGETS
    if validator is schemas._run_limits:
        return BAD_RUN_LIMITS
    name = getattr(validator, "__name__", "")
    if name == "validator":
        return BAD_NESTED
    if name == "<lambda>":
        return BAD_LAMBDA
    raise AssertionError(f"uncategorised validator for {field.name!r}; add it to the table")


SCHEMA_BASELINES: dict[str, dict[str, Any]] = {
    "RunConfiguration": {
        "schema_version": 1,
        "run_id": "run-1",
        "root_contract": {},
        "executor_profile": "profile",
        "budgets": {"MODEL_COST": 1.0},
        "limits": {"actions": 1},
        "policy_version": 1,
        "project_kernel": {
            "schema_version": 1,
            "kernel_id": "k",
            "repository_commit": "c",
            "frozen_at": "t",
        },
        "experiment_manifest": {
            "schema_version": 1,
            "manifest_id": "m",
            "manifest_hash": "h",
        },
    },
    "ProjectKernelReference": {
        "schema_version": 1,
        "kernel_id": "k",
        "repository_commit": "c",
        "frozen_at": "t",
    },
    "ExperimentManifestReference": {
        "schema_version": 1,
        "manifest_id": "m",
        "manifest_hash": "h",
    },
    "ProgressRecord": {
        "schema_version": 1,
        "run_id": "run-1",
        "node_id": "node-1",
        "node_state": "READY",
        "graph_version": 0,
    },
    "RunResult": {
        "schema_version": 1,
        "run_id": "run-1",
        "total_cost": 0.0,
    },
    "EvidenceRetrieval": {
        "schema_version": 1,
        "run_id": "run-1",
        "node_id": "node-1",
        "evidence": [],
    },
}


def test_every_schema_is_in_the_mutation_table():
    assert set(schemas.ALL_SCHEMAS) == set(SCHEMA_BASELINES)


def test_schema_baselines_are_valid():
    for name, document in SCHEMA_BASELINES.items():
        schemas.validate(name, document)


def test_schema_fields_reject_malformed_values():
    for name, schema in schemas.ALL_SCHEMAS.items():
        baseline = SCHEMA_BASELINES[name]
        for field in schema.fields:
            for bad in _bad_values_for(field):
                document = dict(baseline)
                document[field.name] = bad
                with pytest.raises(schemas.SchemaValidationError):
                    schemas.validate(name, document)
        for bad in BAD_SCHEMA_VERSION:
            document = dict(baseline)
            document["schema_version"] = bad
            with pytest.raises(schemas.SchemaValidationError):
                schemas.validate(name, document)


def test_schema_rejects_missing_required_and_unexpected_fields():
    for name, schema in schemas.ALL_SCHEMAS.items():
        baseline = SCHEMA_BASELINES[name]
        for field in schema.fields:
            if not field.required:
                continue
            document = dict(baseline)
            del document[field.name]
            with pytest.raises(schemas.SchemaValidationError):
                schemas.validate(name, document)
        document = dict(baseline)
        document["unexpected_field"] = 1
        with pytest.raises(schemas.SchemaValidationError):
            schemas.validate(name, document)


def _event_payload(spec: events.EventSpec) -> dict[str, Any]:
    payload: dict[str, Any] = {field: "x" for field in spec.required_fields}
    for field, allowed in spec.enum_fields.items():
        payload[field] = allowed()[0]
    for path, allowed in spec.nested_enum_fields.items():
        parts = path.split(".")
        container: Any = payload
        for part in parts[:-1]:
            if not isinstance(container.get(part), dict):
                container[part] = {}
            container = container[part]
        container[parts[-1]] = allowed()[0]
    return payload


def _baseline_event(spec: events.EventSpec) -> events.Event:
    return events.make_event(spec.name, _event_payload(spec), source=spec.expected_source)


def test_event_baselines_validate():
    for spec in events.EVENT_CATALOGUE.values():
        events.validate_event(_baseline_event(spec))


def test_event_boundary_rejects_malformed_admissions():
    for spec in events.EVENT_CATALOGUE.values():
        baseline = _event_payload(spec)

        for field in spec.required_fields:
            payload = dict(baseline)
            del payload[field]
            with pytest.raises(events.MissingPayloadField):
                events.validate_event(
                    events.make_event(spec.name, payload, source=spec.expected_source)
                )

        payload = dict(baseline)
        payload["unexpected_field"] = 1
        with pytest.raises(events.AdmissionError):
            events.validate_event(
                events.make_event(spec.name, payload, source=spec.expected_source)
            )

        for field in spec.enum_fields:
            for bad in BAD_ENUM:
                payload = dict(baseline)
                payload[field] = bad
                with pytest.raises(events.InvalidEnumValue):
                    events.validate_event(
                        events.make_event(spec.name, payload, source=spec.expected_source)
                    )

        for path in spec.nested_enum_fields:
            for bad in BAD_ENUM_NO_NONE:
                payload = _event_payload(spec)
                parts = path.split(".")
                container: Any = payload
                for part in parts[:-1]:
                    container = container[part]
                container[parts[-1]] = bad
                with pytest.raises(events.InvalidEnumValue):
                    events.validate_event(
                        events.make_event(spec.name, payload, source=spec.expected_source)
                    )

        wrong_source = "not-the-catalogued-source"
        if wrong_source != spec.expected_source:
            with pytest.raises(events.InvalidSourceAuthority):
                events.validate_event(
                    events.make_event(spec.name, _event_payload(spec), source=wrong_source)
                )

        with pytest.raises(events.UnsupportedSchemaVersion):
            events.validate_event(
                events.make_event(
                    spec.name, _event_payload(spec), schema_version=99, source=spec.expected_source
                )
            )
        with pytest.raises(events.UnsupportedPolicyVersion):
            events.validate_event(
                events.make_event(
                    spec.name, _event_payload(spec), policy_version=99, source=spec.expected_source
                )
            )


def test_rejected_event_admission_persists_nothing(tmp_path):
    spec = events.EVENT_CATALOGUE["NODE_PROPOSED"]
    payload = _event_payload(spec)
    del payload["cause"]
    event = events.make_event(spec.name, payload)
    store = EventStore(str(tmp_path / "events.db"))
    try:
        before = store.state("run-1").nodes
        with pytest.raises(events.MissingPayloadField):
            store.admit("run-1", event)
        assert store.history("run-1") == []
        assert store.state("run-1").nodes == before
    finally:
        store.close()


def _ledger() -> Ledger:
    ledger = Ledger()
    ledger.register_budget(BudgetRecord("budget", "node-1", {"MODEL_COST": 10.0}))
    return ledger


def test_ledger_rejects_malformed_amounts():
    for bad in BAD_NUMERIC:
        with pytest.raises((LedgerStateError, OvercommitmentError)):
            _ledger().reserve("e1", "budget", bad, "MODEL_COST", "attempt-1", "node-1")

    ledger = _ledger()
    ledger.reserve("e1", "budget", 5.0, "MODEL_COST", "attempt-1", "node-1")
    for bad in BAD_NUMERIC:
        with pytest.raises((LedgerStateError, OvercommitmentError)):
            ledger.commit_reservation("attempt-1", bad, "MODEL_COST")

    ledger = _ledger()
    ledger.reserve("e1", "budget", 5.0, "MODEL_COST", "attempt-1", "node-1")
    ledger.commit_reservation("attempt-1", 5.0, "MODEL_COST")
    for bad in BAD_NUMERIC:
        with pytest.raises((LedgerStateError, OvercommitmentError)):
            ledger.settle("attempt-1", bad, 0.0)


def _valid_request() -> dict:
    return 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=[ResolvedInput("input-1", 1, "hash-1")],
        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",
    )


def test_valid_request_passes_its_own_validator():
    validate_request(_valid_request(), expected_token="token-1")


def test_request_rejects_malformed_boundaries():
    baseline = _valid_request()
    for bad in BAD_NUMERIC:
        request = dict(baseline)
        request["timeout_seconds"] = bad
        with pytest.raises(ProtocolViolation):
            validate_request(request, expected_token="token-1")

    for field in ("amount", "hard_limit"):
        for bad in BAD_NUMERIC:
            request = dict(baseline)
            request["budget_commitment"] = {**baseline["budget_commitment"], field: bad}
            with pytest.raises(ProtocolViolation):
                validate_request(request, expected_token="token-1")

    for bad in (None, "x", [], 0.0):
        request = dict(baseline)
        request["owned_scope"] = bad
        with pytest.raises(ProtocolViolation):
            validate_request(request, expected_token="token-1")

    request = dict(baseline)
    request["output_schema_version"] = RESPONSE_SCHEMA_VERSION + 1
    with pytest.raises(ProtocolViolation):
        validate_request(request, expected_token="token-1")

    request = dict(baseline)
    del request["run_id"]
    with pytest.raises(ProtocolViolation):
        validate_request(request, expected_token="token-1")

    request = dict(baseline)
    request["resolved_inputs"] = [{"version": 1, "content_hash": "h"}]
    with pytest.raises(ProtocolViolation):
        validate_request(request, expected_token="token-1")

    request = dict(baseline)
    request["attempt_token"] = "different"
    with pytest.raises(ProtocolViolation):
        validate_request(request, expected_token="token-1")

    for bad in (True, -1, "1", None):
        request = {**baseline, "max_input_tokens": bad}
        with pytest.raises(ProtocolViolation):
            validate_request(request, expected_token="token-1")


def _valid_response() -> dict:
    return {
        "run_id": "run-1",
        "action_id": "action-1",
        "attempt_id": "attempt-1",
        "attempt_token": "token-1",
        "self_reported_status": executor_response_statuses()[0],
        "artefacts": [],
        "observations": [],
        "changed_paths": [],
        "cost_report": {"committed": 1.0, "actual": 1.0, "units": "USD"},
        "started_at": 0.0,
        "finished_at": 1.0,
        "executor_version": "executor-1",
        "response_schema_version": RESPONSE_SCHEMA_VERSION,
    }


def test_valid_response_passes_its_own_validator():
    validate_response(_valid_request(), _valid_response(), expected_token="token-1", producer_authority="executor")


def test_response_rejects_malformed_boundaries():
    request = _valid_request()
    baseline = _valid_response()

    for field in ("committed", "actual"):
        for bad in BAD_NUMERIC:
            response = {**baseline, "cost_report": {**baseline["cost_report"], field: bad}}
            with pytest.raises(ProtocolViolation):
                validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {**baseline, "self_reported_status": "NOT_A_STATUS"}
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {**baseline, "response_schema_version": RESPONSE_SCHEMA_VERSION + 1}
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {**baseline, "run_id": "other"}
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {
        **baseline,
        "artefacts": [{"type": "NOT_A_TYPE", "reference": "r", "content_hash": "h"}],
    }
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {
        **baseline,
        "observations": [
            {"type": "NOT_A_TYPE", "command_id": "c", "exit_code": 0, "stdout_hash": "h", "stderr_hash": "h"}
        ],
    }
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")

    response = {**baseline, "changed_paths": ["outside/**"]}
    with pytest.raises(ProtocolViolation):
        validate_response(request, response, expected_token="token-1", producer_authority="executor")


# --------------------------------------------------------------------------
# Defect pins (registered in tests/open_defects.yaml). These tests encode the
# intended rejection; their status there is authoritative. Do not weaken them
# to green without fixing the boundary — the open-defect registry meta-test
# forbids silent weakening.
# --------------------------------------------------------------------------


@pytest.mark.parametrize("schema_name", sorted(schemas.ALL_SCHEMAS))
def test_bug_schema_version_accepts_boolean(schema_name):
    """BUG: ``schema_version=True`` passes ``True == 1`` and is accepted."""
    document = dict(SCHEMA_BASELINES[schema_name])
    document["schema_version"] = True
    with pytest.raises(schemas.SchemaValidationError):
        schemas.validate(schema_name, document)


@pytest.mark.parametrize("field", ["schema_version", "policy_version"])
def test_bug_event_version_accepts_boolean(field):
    """BUG: a boolean event version passes ``True == 1`` and is accepted."""
    spec = events.EVENT_CATALOGUE["NODE_PROPOSED"]
    event = events.make_event(
        spec.name, _event_payload(spec), source=spec.expected_source, **{field: True}
    )
    with pytest.raises(events.AdmissionError):
        events.validate_event(event)


NESTED_ENUM_CASES = [
    (name, path)
    for name, spec in events.EVENT_CATALOGUE.items()
    for path in spec.nested_enum_fields
]


@pytest.mark.parametrize("event_name,path", NESTED_ENUM_CASES)
def test_bug_nested_enum_accepts_none(event_name, path):
    """BUG: an explicit ``None`` nested enum is treated as absent and skipped."""
    spec = events.EVENT_CATALOGUE[event_name]
    payload = _event_payload(spec)
    parts = path.split(".")
    container: Any = payload
    for part in parts[:-1]:
        container = container[part]
    container[parts[-1]] = None
    event = events.make_event(spec.name, payload, source=spec.expected_source)
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(event)
