# SPDX-License-Identifier: AGPL-3.0-or-later
"""Phase 0 defect pins (docs/report-code-organization.md correctness smells).

Each test encodes the *intended* behaviour and lands failing-first with its
fix: a check that does not declare ``passed`` must never pass in an acceptance
path (smell 1); acceptance idempotency keys must not collide across ceilings,
cycles, or admissions (smell 4).
"""
from __future__ import annotations

import dataclasses
import os

import pytest

from helpers import build_run_config, experiment_authorization
from orchestrator import experiment, model_adapter, sandbox, spend
from orchestrator.controller import AcceptanceRefused, Controller
from orchestrator.executor import ScriptedExecutor
from orchestrator.model_adapter import ModelAdapter, ModelClient, ModelCompletion, ModelOutput
from orchestrator.store import EventStore

_MODEL_LIMITS = {
    "root_model_input_tokens": 32768,
    "root_model_output_tokens": 8192,
}


class _StaticClient(ModelClient):
    def __init__(self, tokens=(10, 5)):
        self.tokens = tokens

    def max_cost(self, request):
        return 0.5

    def max_tokens(self, request):
        return self.tokens

    def complete(self, request):
        return ModelCompletion(
            outputs=(ModelOutput(
                "SEMANTIC_EVALUATION",
                {"subject_reference": "x", "verdict": "PASS", "rationale": "ok"},
            ),),
            cost=0.01,
            units="COST_UNITS",
            model_id="model-x",
            model_version="1",
            input_tokens=10,
            output_tokens=5,
        )


def _controller(tmp_path, client=None, name="defects.db"):
    store = EventStore(str(tmp_path / name))
    client = client or _StaticClient()
    controller = Controller(
        store,
        ScriptedExecutor({}),
        model_executor=ModelAdapter(client, model_id="model-x", model_version="1"),
        executor_environment={"base_commit": "HEAD", "timeout_seconds": 30.0},
    )
    return store, controller


def _root(controller, run_id, limits=None):
    config = build_run_config(
        run_id, limits=dict(_MODEL_LIMITS) if limits is None else limits
    )
    return controller.submit_run(config)


def _bind_result(controller, store, run_id, root):
    attempt_id, _response = controller.run_model_review(run_id, root, 5.0)
    return f"{attempt_id}-result"


def _history(store, run_id, event_type):
    return [e for e in store.history(run_id) if e.event_type == event_type]


# --------------------------------------------------------------------------
# Smell 1: fail-open ``passed`` default in an acceptance path
# --------------------------------------------------------------------------


def test_inline_check_without_declared_pass_is_refused(tmp_path):
    """A check that does not declare ``passed`` is a malformed acceptance
    declaration and must be refused — never normalised to passing."""
    store, controller = _controller(tmp_path)
    try:
        root = _root(controller, "RUN-DEF-1")
        result_id = _bind_result(controller, store, "RUN-DEF-1", root)
        with pytest.raises(AcceptanceRefused):
            controller.validate_and_accept(
                "RUN-DEF-1", root, {"checks": [{"name": "X"}]}, result_id
            )
        assert not _history(store, "RUN-DEF-1", "ACCEPTANCE_AUTHORISED")
    finally:
        store.close()


def test_inline_check_explicit_false_still_refuses(tmp_path):
    store, controller = _controller(tmp_path, name="defects2.db")
    try:
        root = _root(controller, "RUN-DEF-2")
        result_id = _bind_result(controller, store, "RUN-DEF-2", root)
        with pytest.raises(Exception):
            controller.validate_and_accept(
                "RUN-DEF-2",
                root,
                {"checks": [{"name": "X", "passed": False}]},
                result_id,
            )
        assert not _history(store, "RUN-DEF-2", "ACCEPTANCE_AUTHORISED")
    finally:
        store.close()


class _DispatchRefusedClient(ModelClient):
    """A client whose completion is refused at dispatch with a budget error."""

    def max_cost(self, request):
        return 0.5

    def max_tokens(self, request):
        return (10, 5)

    def complete(self, request):
        raise model_adapter.ModelBudgetRefused(
            "reported usage exceeds the declared ceiling"
        )


# --------------------------------------------------------------------------
# Smell 4: idempotency-key collisions
# --------------------------------------------------------------------------


def test_budget_exhaustion_key_identifies_the_ceiling(tmp_path):
    """Two distinct run limits firing on one node must record under distinct
    idempotency keys: a bare per-node key silently deduplicated the second
    distinct ceiling (code-organisation smell 4). The derived BUDGET_EXHAUSTED
    outcome makes a second firing unreachable within one run, so the pin
    compares the keys two fresh runs produce."""
    client = _StaticClient(tokens=(10, 2))
    store, controller = _controller(tmp_path, client=client, name="defects3.db")
    keys = []
    original = controller._emit

    def recording(run_id, event_type, payload, key, **kwargs):
        if event_type == "BUDGET_EXHAUSTION_RECORDED":
            keys.append(key)
        return original(run_id, event_type, payload, key, **kwargs)

    controller._emit = recording
    limits = {
        "root_model_input_tokens": 5,
        "root_model_output_tokens": 5,
        "model_calls": 9,
        "actions": 9,
        "nodes": 8,
        "maximum_depth": 3,
        "wall_clock_seconds": 3600,
    }
    try:
        root = _root(controller, "RUN-DEF-3A", limits=limits)
        with pytest.raises(Exception):
            controller.plan_attempt("RUN-DEF-3A", root, 5.0, action_type="REVIEW")
        client.tokens = (2, 10)
        root = _root(controller, "RUN-DEF-3B", limits=limits)
        with pytest.raises(Exception):
            controller.plan_attempt("RUN-DEF-3B", root, 5.0, action_type="REVIEW")
        assert len(keys) == 2
        assert "root_model_input_tokens" in keys[0]
        assert "root_model_output_tokens" in keys[1]
        assert keys[0] != keys[1]
    finally:
        controller._emit = original
        store.close()


def test_dispatch_refusal_key_identifies_the_attempt(tmp_path):
    """The seventh exhaustion site — a commitment refusal raised during
    dispatch — also carries identity in its key, so two distinct dispatch-time
    refusals on one node cannot silently deduplicate (review residual on
    smell 4)."""

    client = _DispatchRefusedClient()
    store, controller = _controller(tmp_path, client=client, name="defects7.db")
    keys = []
    original = controller._emit

    def recording(run_id, event_type, payload, key, **kwargs):
        if event_type == "BUDGET_EXHAUSTION_RECORDED":
            keys.append(key)
        return original(run_id, event_type, payload, key, **kwargs)

    controller._emit = recording
    try:
        root = _root(controller, "RUN-DEF-7")
        attempt_id = controller.plan_attempt(
            "RUN-DEF-7", root, 5.0, action_type="REVIEW"
        )
        with pytest.raises(Exception):
            controller.dispatch_attempt("RUN-DEF-7", attempt_id, root)
        assert len(keys) == 1
        assert attempt_id in keys[0]
    finally:
        controller._emit = original
        store.close()


def test_acceptance_keys_share_one_cycle(tmp_path):
    """The validation/acceptance triple keys on one cycle value: the accept
    key cannot drop the cycle, or two cycles collide."""
    store, controller = _controller(tmp_path, name="defects4.db")
    keys = []
    original = controller._emit

    def recording(run_id, event_type, payload, key, **kwargs):
        keys.append((event_type, key))
        return original(run_id, event_type, payload, key, **kwargs)

    controller._emit = recording
    try:
        root = _root(controller, "RUN-DEF-4")
        result_id = _bind_result(controller, store, "RUN-DEF-4", root)
        controller.validate_and_accept(
            "RUN-DEF-4", root, {"checks": [{"name": "X", "passed": True}]}, result_id
        )
        triple = {
            event_type: key
            for event_type, key in keys
            if event_type
            in ("VALIDATION_STARTED", "VALIDATION_PASSED", "ACCEPTANCE_AUTHORISED")
        }
        assert set(triple) == {
            "VALIDATION_STARTED",
            "VALIDATION_PASSED",
            "ACCEPTANCE_AUTHORISED",
        }
        cycles = {key.rsplit("-", 1)[1] for key in triple.values()}
        assert len(cycles) == 1, f"acceptance keys disagree on the cycle: {triple}"
    finally:
        controller._emit = original
        store.close()


def test_inline_evidence_admissions_do_not_deduplicate(tmp_path):
    """A second inline evidence admission for one node is a second evidence
    record, not a silent reuse of the first."""
    store, controller = _controller(tmp_path, name="defects5.db")
    try:
        root = _root(controller, "RUN-DEF-5")
        first = controller._admit_inline_evidence(
            "RUN-DEF-5", root, {"checks": [{"name": "X", "passed": True}]}
        )
        second = controller._admit_inline_evidence(
            "RUN-DEF-5", root, {"checks": [{"name": "Y", "passed": True}]}
        )
        assert first != second
    finally:
        store.close()


# --------------------------------------------------------------------------
# Smell 2: _model_review bills the mutable MODEL_PROFILE global
# --------------------------------------------------------------------------


@pytest.mark.slow
@pytest.mark.timeout(300)
def test_trial_bills_its_own_model_profile(tmp_path):
    """The review attempt is committed at the *trial's* model profile, not the
    mutable ``experiment.MODEL_PROFILE`` global (code-organisation smell 2 —
    the Axis 1 dispatch path)."""
    caps = sandbox.capabilities()
    if not caps.profile_available:
        pytest.fail(f"NAMESPACE_V1 unavailable (fail-closed gate): {caps.unavailable_reason()}")
    custom = dataclasses.replace(
        experiment.MODEL_PROFILE, model_id="custom-model", cost_per_call=7.0
    )
    target = experiment.build_fixed_target(str(tmp_path))
    oracle_manifest = experiment.build_hidden_oracle(target)
    ledger = spend.open_spend_ledger(str(tmp_path), experiment_authorization())
    client = _StaticClient()
    experiment.set_model_client_factory(lambda profile, seed: client)
    try:
        metrics = experiment.run_trial(
            target,
            oracle_manifest,
            experiment.placeholder_limits(),
            custom,
            experiment.ARM_DIRECT,
            1001,
            str(tmp_path),
            spend_ledger=ledger,
        )
    finally:
        experiment.set_model_client_factory(None)
    trial_root = os.path.join(str(tmp_path), "trials", f"{experiment.ARM_DIRECT}-1001")
    store = EventStore(os.path.join(trial_root, "events.db"))
    try:
        state = store.state(metrics.run_id)
    finally:
        store.close()
    review = [a for a in state.attempts.values() if a.action_type == "REVIEW"]
    assert review, "the trial must have issued its model review"
    assert all(a.commitment == 7.0 for a in review)
    assert metrics.model_id == "custom-model"


# --------------------------------------------------------------------------
# Smell 3: one settlement formula; audited credential re-issue after restart
# --------------------------------------------------------------------------


def test_settlement_reclamation_is_one_formula():
    """Live reconciliation, recovery reconciliation, and cancellation settle
    through one formula (code-organisation smell 3). The two historical orders
    agree on every float64 input — this pin exists so a future asymmetric
    change cannot make them diverge."""
    from orchestrator.controller import _reclaimed

    assert _reclaimed(5.0, 2.0) == 3.0
    assert _reclaimed(5.0, 5.0) == 0.0
    assert _reclaimed(5.0, 6.0) == 0.0
    assert _reclaimed(5.0, 0.0) == 5.0
    assert _reclaimed(None, 0.0) == 0.0
    assert _reclaimed(0.3, 0.1) == 0.2
    for commitment, actual in ((1e-9, 5e-10), (5.0, -0.0), (5.0, 5.0000000004)):
        assert _reclaimed(commitment, actual) == round(
            max(0.0, float(commitment or 0) - float(actual)), 9
        )


def test_recovery_reissues_credentials_through_the_audited_lifecycle(tmp_path):
    """R05: after a restart the pre-crash credential cannot be restored, so
    recovery retires its stale record and issues a replacement through the
    typed CREDENTIAL_ISSUED event — never an out-of-band source registration
    (code-organisation smell 5)."""
    from orchestrator import secrets as secrets_module

    source = secrets_module.SecretsSource()
    credential = source.issue(
        "MODEL_ENDPOINT",
        credential_id="cred-pre-crash",
        ttl_seconds=3600,
        secret="secret-pre-crash",
    )
    store, controller = _controller(tmp_path, name="defects6.db")
    try:
        root = _root(controller, "RUN-DEF-6")
        controller.issue_credential("RUN-DEF-6", credential)
        # Restart: a fresh process holds a fresh, empty secrets source.
        fresh_source = secrets_module.SecretsSource()
        restarted = Controller(
            store, ScriptedExecutor({}), secrets_source=fresh_source
        )
        with pytest.raises(secrets_module.CredentialRefused):
            restarted._require_redaction_coverage("RUN-DEF-6")
        replacement = fresh_source.issue(
            "MODEL_ENDPOINT",
            credential_id="cred-recovered",
            ttl_seconds=3600,
            secret="secret-recovered",
        )
        restarted.reissue_credentials("RUN-DEF-6", [replacement])
        assert restarted._active_credential_ids("RUN-DEF-6") == {"cred-recovered"}
        restarted._require_redaction_coverage("RUN-DEF-6")
        retired = _history(store, "RUN-DEF-6", "CREDENTIAL_RETIRED")
        assert [e.payload["credential_id"] for e in retired] == ["cred-pre-crash"]
        issued = _history(store, "RUN-DEF-6", "CREDENTIAL_ISSUED")
        assert [e.payload["credential_id"] for e in issued] == [
            "cred-pre-crash",
            "cred-recovered",
        ]
        # The out-of-band restore path is gone (smell 5: zero callers or a
        # recovery hole — it is neither now).
        assert not hasattr(restarted, "restore_credentials")
    finally:
        store.close()


# --------------------------------------------------------------------------
# Recurring report #16: the sandbox gate is fail-closed, never a silent skip
# --------------------------------------------------------------------------


def test_sandbox_gate_fails_closed_instead_of_skipping():
    """Trust-boundary and acceptance coverage must not silently vanish on an
    unprovisioned host: no sandbox/cgroup gate may skip (the R08 tests used to
    skip while test_milestone3_sandbox failed — one policy now)."""
    tests_root = os.path.dirname(os.path.abspath(__file__))
    offenders = []
    for name in sorted(os.listdir(tests_root)):
        if not name.endswith(".py"):
            continue
        with open(os.path.join(tests_root, name)) as handle:
            for number, line in enumerate(handle, 1):
                if "pytest.skip" in line and any(
                    marker in line
                    for marker in (
                        "NAMESPACE_V1",
                        "no sandbox profile",
                        "no delegated cgroup",
                    )
                ):
                    offenders.append(f"{name}:{number}: {line.strip()}")
    assert not offenders, f"sandbox gates must fail closed, never skip: {offenders}"
