# SPDX-License-Identifier: AGPL-3.0-or-later
"""Conformance entries for the fourth milestone's events and boundaries.

Per AGENTS.md#change-rules every new event carries a catalogue entry, a
transition entry or explicit side-effect-only row, and a conformance entry:
``MODEL_OUTPUT_ADMITTED`` / ``MODEL_OUTPUT_CONSUMED`` (model-output machine,
source authority, unknown-enum rules, and the seven admission-validation
rules), the side-effect-only ``EVIDENCE_ADMITTED`` and ``FAILURE_RECORDED``,
and the model response envelope validation. The resolution-level cross-check in
tests/test_tables_agree_with_scripts.py covers the new machine automatically.
"""

from __future__ import annotations

import copy

import pytest

from orchestrator import events, executor_protocol, model_adapter, reducer, tables
from orchestrator.model import RunState
from orchestrator.reducer import ReducerError


def _event(event_type, payload, idem="k", source="controller"):
    return events.make_event(event_type, payload, idempotency_key=idem, source=source)


def _model_attempt_state(prompt_hash="sha256:prompt"):
    state = RunState(run_id="r1")
    state, _ = reducer.reduce(
        state,
        _event(
            "NODE_PROPOSED",
            {"node_id": "n1", "contract": {"budgets": {"MODEL_COST": 100}, "owned_scope": ["src/**"]}, "cause": "ROOT"},
        ),
    )
    state, _ = reducer.reduce(
        state,
        _event("ATTEMPT_PLANNED", {"attempt_id": "a1", "node_id": "n1", "cause": "INITIAL", "action_type": "REVIEW"}),
    )
    state, _ = reducer.reduce(
        state, _event("ACTION_RESERVED", {"attempt_id": "a1", "commitment": 5}, source="scheduler")
    )
    state, _ = reducer.reduce(
        state, _event("ATTEMPT_COMMITMENT_OPENED", {"attempt_id": "a1", "commitment": 5})
    )
    state, _ = reducer.reduce(
        state,
        _event(
            "ACTION_DISPATCHED",
            {"attempt_id": "a1", "executor": "model-adapter", "action_type": "REVIEW",
             "model_id": "model-x", "prompt_hash": prompt_hash},
        ),
    )
    state, _ = reducer.reduce(
        state, _event("DISPATCH_ACKNOWLEDGED", {"attempt_id": "a1", "token": "t"}, source="executor")
    )
    return state


def _valid_output(prompt_hash="sha256:prompt", **overrides):
    payload = {
        "output_id": "o1",
        "attempt_id": "a1",
        "output_type": "SEMANTIC_EVALUATION",
        "output": {"subject_reference": "src/app.txt", "verdict": "PASS", "rationale": "ok"},
        "provenance": {
            "model_id": "model-x",
            "model_version": "1",
            "call_id": "a1",
            "prompt_hash": prompt_hash,
            "policy_version": 1,
        },
    }
    payload.update(overrides)
    return payload


# -- event admission rules ------------------------------------------------------


def test_model_output_source_authority_is_model_only():
    wrong = events.make_event("MODEL_OUTPUT_ADMITTED", _valid_output(), source="controller")
    with pytest.raises(events.InvalidSourceAuthority):
        events.validate_event(wrong)
    events.validate_event(events.make_event("MODEL_OUTPUT_ADMITTED", _valid_output(), source="model"))


def test_model_output_unknown_enum_and_missing_fields_are_rejected():
    with pytest.raises(events.MissingPayloadField):
        events.validate_event(_event("MODEL_OUTPUT_ADMITTED", {"output_id": "o1"}, source="model"))
    bad_type = _valid_output(output_type="NOT_A_TYPE")
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(events.make_event("MODEL_OUTPUT_ADMITTED", bad_type, source="model"))
    bad_verdict = _valid_output()
    bad_verdict["output"]["verdict"] = "MAYBE"
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(events.make_event("MODEL_OUTPUT_ADMITTED", bad_verdict, source="model"))


def test_model_output_machine_admits_and_consumes():
    table = tables.model_output_table()
    assert table.resolve(None, "MODEL_OUTPUT_ADMITTED").target == "ADMITTED"
    assert table.resolve("ADMITTED", "MODEL_OUTPUT_CONSUMED").target == "CONSUMED"
    with pytest.raises(tables.UnknownTransition):
        table.resolve("CONSUMED", "MODEL_OUTPUT_CONSUMED")


def test_evidence_check_class_enum_and_unknown_node():
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            _event("EVIDENCE_ADMITTED", {"evidence_id": "e1", "node_id": "n1", "check_class": "MAYBE", "checks": []})
        )
    state = _model_attempt_state()
    with pytest.raises(ReducerError):
        reducer.reduce(
            state,
            _event("EVIDENCE_ADMITTED", {"evidence_id": "e1", "node_id": "ghost", "check_class": "VISIBLE", "checks": []}),
        )


def test_failure_recorded_appends_fingerprints():
    state = _model_attempt_state()
    for index in (1, 2):
        state, _ = reducer.reduce(
            state,
            _event(
                "FAILURE_RECORDED",
                {"node_id": "n1", "action_type": "EXECUTE", "fingerprint": "sha256:f",
                 "resolution_strategy_id": "DEFAULT"},
                idem=f"f{index}",
            ),
        )
    assert state.failure_fingerprints["n1"] == ["sha256:f", "sha256:f"]
    assert state.failure_strategies["n1"] == ["DEFAULT", "DEFAULT"]


# -- reducer re-validation of the seven rules -----------------------------------


def test_reducer_revalidates_every_output_rule():
    state = _model_attempt_state()
    reducer.reduce(state, _event("MODEL_OUTPUT_ADMITTED", _valid_output(), idem="ok", source="model"))

    def reduced(payload, idem):
        with pytest.raises(ReducerError):
            reducer.reduce(
                state, _event("MODEL_OUTPUT_ADMITTED", payload, idem=idem, source="model")
            )

    # schema
    reduced(_valid_output(output={"subject_reference": "x"}), "schema")
    # producer authority
    bad = _valid_output()
    bad["provenance"]["model_id"] = "other"
    reduced(bad, "authority")
    # provenance (prompt binding)
    bad = _valid_output()
    bad["provenance"]["prompt_hash"] = "sha256:other"
    reduced(bad, "provenance")
    # delegated scope
    bad = _valid_output()
    bad["output"] = {"subject": "s", "statement": "x", "observed_references": [],
                     "paths": ["secrets/leak.txt"]}
    bad["output_type"] = "OBSERVATION"
    reduced(bad, "scope")
    # input versions
    reduced(_valid_output(input_versions={"missing": 1}), "versions")
    # artefact hashes
    reduced(_valid_output(artefact_hashes={"missing": "sha256:x"}), "hashes")
    # policy compatibility
    bad = _valid_output()
    bad["provenance"]["policy_version"] = 99
    reduced(bad, "policy")


def test_model_output_duplicate_and_consumed_terminal_semantics():
    state = _model_attempt_state()
    state, _ = reducer.reduce(
        state, _event("MODEL_OUTPUT_ADMITTED", _valid_output(), idem="o1", source="model")
    )
    state, effects = reducer.reduce(
        state, _event("MODEL_OUTPUT_ADMITTED", _valid_output(), idem="o1", source="model")
    )
    assert effects == [reducer.Effect("late_event_retained", {"output_id": "o1"})]
    state, _ = reducer.reduce(
        state, _event("MODEL_OUTPUT_CONSUMED", {"output_id": "o1", "bound_by": "n1"}, idem="c1")
    )
    assert state.model_outputs["o1"].state == "CONSUMED"
    state, effects = reducer.reduce(
        state, _event("MODEL_OUTPUT_CONSUMED", {"output_id": "o1", "bound_by": "n1"}, idem="c2")
    )
    assert effects == [reducer.Effect("late_event_retained", {"output_id": "o1"})]


# -- model response envelope ----------------------------------------------------


def test_model_response_envelope_validates_identity_and_enums():
    token = "tok-1"
    request = executor_protocol.build_request(
        run_id="RUN-1", action_id="ACTION-1", attempt_id="ATTEMPT-1", attempt_token=token,
        node_id="NODE-1", node_contract_version=1, action_type="REVIEW", resolved_inputs=(),
        owned_scope_include=["src/**"], owned_scope_exclude=[".git/**"], base_commit="base",
        worktree_id="WT-1", timeout_seconds=60, cancellation_token="c1",
        budget_commitment={"dimension": "MODEL_COST", "hard_limit": 5},
        environment_version="fixture-v1",
    )
    response = {
        "run_id": "RUN-1", "action_id": "ACTION-1", "attempt_id": "ATTEMPT-1",
        "attempt_token": token, "self_reported_status": "COMPLETED", "artefacts": [],
        "observations": [], "changed_paths": [], "model_outputs": [],
        "cost_report": {"committed": 5, "actual": 3, "units": "COST_UNITS"},
        "started_at": "t0", "finished_at": "t1", "executor_version": "model-adapter/1",
        "response_schema_version": 1,
    }
    executor_protocol.validate_response(
        request, response, expected_token=token, producer_authority="model-adapter"
    )
    broken = copy.deepcopy(response)
    broken["attempt_token"] = "forged"
    with pytest.raises(executor_protocol.ProtocolViolation):
        executor_protocol.validate_response(
            request, broken, expected_token=token, producer_authority="model-adapter"
        )


def test_model_adapter_reports_overrun_without_clipping():
    from orchestrator.model_adapter import ModelAdapter, ModelCompletion, ModelOutput, ScriptedModelClient

    client = ScriptedModelClient(
        {"NODE-1": ModelCompletion(outputs=(ModelOutput("OBSERVATION", {
            "subject": "s", "statement": "x", "observed_references": []}),),
            cost=9.0, units="COST_UNITS", model_id="m", model_version="1")},
        max_costs={"NODE-1": 5.0},
    )
    adapter = ModelAdapter(client, model_id="m", model_version="1")
    token = adapter.issue_token("ATTEMPT-1")
    response = adapter.dispatch({
        "run_id": "R", "action_id": "A", "attempt_id": "ATTEMPT-1", "attempt_token": token,
        "node_id": "NODE-1", "action_type": "REVIEW", "resolved_inputs": [],
        "budget_commitment": {"dimension": "MODEL_COST", "hard_limit": 5},
        "policy_version": 1, "prompt_hash": "sha256:p",
    })
    # The reported spend is preserved rather than clipped at the commitment, and
    # the excess is explicit overrun liability (R02).
    assert response["self_reported_status"] == "FAILED"
    assert response["cost_report"]["actual"] == 9.0
    assert response["cost_report"]["overrun"] == 4.0
    assert response["model_outputs"] == []
    assert response["cost_report"]["budget_exhausted"] is True

    # A non-monetary commitment is refused before any client invocation.
    adapter2 = ModelAdapter(client, model_id="m", model_version="1")
    token2 = adapter2.issue_token("ATTEMPT-2")
    calls = []
    original = client.max_cost
    client.max_cost = lambda request: (calls.append(request), original(request))[1]
    with pytest.raises(model_adapter.ModelBudgetRefused):
        adapter2.dispatch({
            "run_id": "R", "action_id": "A", "attempt_id": "ATTEMPT-2", "attempt_token": token2,
            "node_id": "NODE-1", "action_type": "REVIEW", "resolved_inputs": [],
            "budget_commitment": {"dimension": "MODEL_TOKENS", "hard_limit": 5},
            "policy_version": 1, "prompt_hash": "sha256:p",
        })
    assert calls == []
