"""Tests for Meta model and _meta dict construction for MCP responses."""

import pytest
from pydantic import ValidationError

from anima.core.schemas import AgentState, AgentStateData, Meta
from anima.shell.meta import build_meta


class TestBuildMeta:
    """Tests for build_meta function."""

    def test_minimal_meta(self) -> None:
        """build_meta with minimal AgentStateData (no persona_id)."""
        state = AgentStateData(
            instance_id="inst_xyz",
            trace_id="tr_123",
            persona_name="test",
        )
        meta = build_meta(state)
        assert meta["trace_id"] == "tr_123"
        assert meta["instance_id"] == "inst_xyz"
        assert meta["agent_id"] == "inst_xyz"  # backward compat alias
        assert "persona_id" not in meta

    def test_meta_with_persona_id(self) -> None:
        """build_meta includes persona_id when state has spec_id."""
        state = AgentStateData(
            instance_id="inst_uvw",
            trace_id="tr_456",
            persona_name="worker",
            spec_id="persona@abc123",
        )
        meta = build_meta(state)
        assert meta["trace_id"] == "tr_456"
        assert meta["instance_id"] == "inst_uvw"
        assert meta["agent_id"] == "inst_uvw"  # backward compat alias
        assert meta["persona_id"] == "persona@abc123"
        assert "spec_id" not in meta

    def test_meta_all_required_fields(self) -> None:
        """build_meta always includes required fields."""
        state = AgentStateData(
            instance_id="inst_test",
            trace_id="tr_test",
            persona_name="test-agent",
            state=AgentState.running,
        )
        meta = build_meta(state)
        # Required fields per docs/INTERFACES.md Section E
        assert "trace_id" in meta
        assert "instance_id" in meta
        assert "agent_id" in meta  # backward compat alias
        # Verify values match state
        assert meta["trace_id"] == state.trace_id
        assert meta["instance_id"] == state.instance_id
        assert meta["agent_id"] == state.instance_id  # alias equals instance_id


class TestMetaModel:
    """Tests for Meta schema field names and validation."""

    def test_constructs_without_instance_id(self) -> None:
        """Meta(trace_id) works without instance_id."""
        meta = Meta(trace_id="t")
        assert meta.instance_id is None

    def test_persona_id_allowed(self) -> None:
        """Meta accepts persona_id field."""
        meta = Meta(trace_id="t", persona_id="my-agent")
        assert meta.persona_id == "my-agent"

    def test_spec_id_rejected(self) -> None:
        """Legacy spec_id field is rejected."""
        with pytest.raises(ValidationError):
            Meta(trace_id="t", spec_id="x")

    def test_spec_digest_rejected(self) -> None:
        """Legacy spec_digest field is rejected."""
        with pytest.raises(ValidationError):
            Meta(trace_id="t", spec_digest="x")
