# SPDX-License-Identifier: AGPL-3.0-or-later
"""A8 categorical field completeness.

Every authority-bearing categorical value — relation type, acceptance check
class, budget dimension, run outcome, and completion units — must be a member
of a catalogue, and a non-member must be rejected. Each acceptance is proven
first so a rejection is attributable to the mutation.

Completion units are catalogued in the Glossary and enforced at the adapter
boundary, so an unknown or token-shaped unit is refused rather than billed as
money.
"""
from __future__ import annotations

import pytest

from orchestrator import events, glossary, model_adapter, schemas
from orchestrator.controller import BudgetExhausted, WorkflowError

from test_boundary_mutations import SCHEMA_BASELINES, _event_payload
from test_milestone8_readiness import _CountingModelClient, _token_controller

CATALOGUES = (
    ("node_states", glossary.node_states),
    ("attempt_states", glossary.attempt_states),
    ("artefact_states", glossary.artefact_states),
    ("accounting_states", glossary.accounting_states),
    ("freshness_values", glossary.freshness_values),
    ("run_outcomes", glossary.run_outcomes),
    ("budget_dimensions", glossary.budget_dimensions),
    ("node_proposal_causes", glossary.node_proposal_causes),
    ("revalidation_reasons", glossary.revalidation_reasons),
    ("executor_artefact_types", glossary.executor_artefact_types),
    ("executor_response_statuses", glossary.executor_response_statuses),
    ("executor_observation_types", glossary.executor_observation_types),
    ("reasoning_output_types", glossary.reasoning_output_types),
    ("model_output_states", glossary.model_output_states),
    ("acceptance_check_classes", glossary.acceptance_check_classes),
    ("completion_units", glossary.completion_units),
    ("semantic_verdicts", glossary.semantic_verdicts),
    ("approval_subjects", glossary.approval_subjects),
    ("credential_scopes", glossary.credential_scopes),
    ("relation_types", glossary.relation_types),
    ("conflict_types", glossary.conflict_types),
    ("conflict_severities", glossary.conflict_severities),
    ("conflict_resolution_policies", glossary.conflict_resolution_policies),
)

EVENT_CATEGORIES = (
    ("RELATION_RECORDED", "relation_type"),
    ("EVIDENCE_ADMITTED", "check_class"),
)


def test_every_catalogue_is_non_empty_and_unique():
    for name, catalogue in CATALOGUES:
        values = catalogue()
        assert values, f"{name} is empty"
        assert len(values) == len(set(values)), f"{name} has duplicate values"


@pytest.mark.parametrize("event_type,field", EVENT_CATEGORIES)
def test_event_categorical_field_accepts_members_and_rejects_non_members(event_type, field):
    spec = events.EVENT_CATALOGUE[event_type]
    catalogue = spec.enum_fields[field]

    accepted = _event_payload(spec)
    accepted[field] = catalogue()[0]
    events.validate_event(events.make_event(event_type, accepted, source=spec.expected_source))

    rejected = _event_payload(spec)
    rejected[field] = "NOT_A_CATALOGUE_MEMBER"
    with pytest.raises(events.InvalidEnumValue):
        events.validate_event(
            events.make_event(event_type, rejected, source=spec.expected_source)
        )


def test_budget_dimension_catalogue_bounds_run_budgets():
    member = glossary.budget_dimensions()[0]
    accepted = dict(SCHEMA_BASELINES["RunConfiguration"])
    accepted["budgets"] = {member: 1.0}
    schemas.validate("RunConfiguration", accepted)

    rejected = dict(SCHEMA_BASELINES["RunConfiguration"])
    rejected["budgets"] = {"NOT_A_DIMENSION": 1.0}
    with pytest.raises(schemas.SchemaValidationError):
        schemas.validate("RunConfiguration", rejected)


def test_run_outcome_catalogue_bounds_results():
    accepted = dict(SCHEMA_BASELINES["RunResult"])
    accepted["outcome"] = glossary.run_outcomes()[0]
    schemas.validate("RunResult", accepted)

    rejected = dict(SCHEMA_BASELINES["RunResult"])
    rejected["outcome"] = "NOT_AN_OUTCOME"
    with pytest.raises(schemas.SchemaValidationError):
        schemas.validate("RunResult", rejected)


def _completion(units: str):
    return model_adapter.ModelCompletion(
        outputs=(),
        cost=1.0,
        units=units,
        model_id="model-x",
        model_version="1",
        input_tokens=1,
        output_tokens=1,
    )


def _review(tmp_path, run_id: str, units: str):
    client = _CountingModelClient(_completion(units), max_cost=1.0, max_tokens=(1, 1))
    store, controller, root = _token_controller(
        tmp_path,
        run_id,
        client,
        limits={
            "root_model_input_tokens": 1000,
            "root_model_output_tokens": 1000,
            "model_calls": 10,
        },
    )
    try:
        controller.run_model_review(run_id, root, 1.0)
    finally:
        store.close()
    return client


def test_known_monetary_unit_is_billed(tmp_path):
    client = _review(tmp_path, "RUN-A8-UNITS-OK", "COST_UNITS")
    assert len(client.requests) == 1


def test_bug_unknown_completion_unit_is_billed_as_money(tmp_path):
    """A shape-valid but non-monetary unit is neither in a catalogue nor
    refused, so it is billed against a monetary commitment."""
    with pytest.raises((BudgetExhausted, model_adapter.ModelBudgetRefused, WorkflowError)):
        _review(tmp_path, "RUN-A8-UNITS-BAD", "BANANAS")
