"""Acceptance tests for execution-kernel contract boundaries."""

from pydantic import ValidationError

from anima.core.execution import ExecutionIntent, ResolvedExecutionContract
from anima.shell.contract_compat import EXECUTION_CONTRACT_COMPATIBILITY

from tests.execution_contract_fixtures import (
    EXECUTION_INTENT,
    EXECUTION_SESSION_STATE,
    MUTABLE_AGENT_STATE,
    NON_SPAWNABLE_INLINE_CONTRACT,
    SPAWNABLE_SNAPSHOT_CONTRACT,
)


def test_execution_intent_keeps_requested_inputs_separate_from_effective_truth() -> (
    None
):
    assert isinstance(EXECUTION_INTENT, ExecutionIntent)
    assert EXECUTION_INTENT.overrides.requested_cli_tools == ("read_file", "write_file")
    assert EXECUTION_INTENT.defaults.default_project_root == "/workspace"


def test_resolved_execution_contract_distinguishes_declared_requested_and_effective_tools() -> (
    None
):
    contract = SPAWNABLE_SNAPSHOT_CONTRACT
    assert isinstance(contract, ResolvedExecutionContract)
    assert contract.tool_access.declared_persona_tools == ("read_file",)
    assert contract.tool_access.requested_cli_tools == ("read_file", "write_file")
    assert contract.tool_access.effective_tools == (
        "read_file",
        "write_file",
        "browser.snapshot",
    )


def test_spawnability_is_explicit_even_when_no_persona_ref_exists() -> None:
    provenance = NON_SPAWNABLE_INLINE_CONTRACT.persona_provenance
    assert provenance.reusable_persona_ref is None
    assert provenance.spawnability.can_spawn is False
    assert provenance.spawnability.reason is not None
    assert (
        provenance.spawnability.reason.code == "inline_persona_requires_materialization"
    )


def test_session_state_is_ephemeral_and_separate_from_mutable_agent_state() -> None:
    assert EXECUTION_SESSION_STATE.transport.stream_active is True
    assert MUTABLE_AGENT_STATE.current_turn == 0
    assert MUTABLE_AGENT_STATE.persona_ref == "worker@sha256:persona"


def test_resolved_contract_is_immutable() -> None:
    try:
        SPAWNABLE_SNAPSHOT_CONTRACT.runtime.effective_model = "other"
    except ValidationError:
        return
    except TypeError:
        return
    raise AssertionError("ResolvedExecutionContract must be frozen")


def test_shell_compatibility_policy_points_consumers_to_resolved_spawnability() -> None:
    assert (
        EXECUTION_CONTRACT_COMPATIBILITY.spawnability_source
        == "persona_provenance.spawnability"
    )
    assert EXECUTION_CONTRACT_COMPATIBILITY.legacy_spawnability_field == "persona_ref"
