"""Tests for ContentBridge adapters — ManualInput, MeetingSummary, Transcript."""

from __future__ import annotations

import json
import pytest
from pathlib import Path
from unittest.mock import patch, AsyncMock

from vastian.bridges.content_bridge.manual_input import ManualInputAdapter
from vastian.bridges.content_bridge.meeting_summary import MeetingSummaryAdapter
from vastian.bridges.content_bridge.transcript import TranscriptAdapter


class TestManualInputAdapter:
    @pytest.fixture
    def adapter(self) -> ManualInputAdapter:
        return ManualInputAdapter()

    def test_financial_content_routes_to_finley(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("Here is the financial summary", {})
        assert agents == ["finley"]

    def test_meeting_content_routes_to_charles_maya(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("The meeting went well", {})
        assert agents == ["charles", "maya"]

    def test_task_content_routes_to_arjuna_liam(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("Create a new task for the kanban board", {})
        assert agents == ["arjuna", "liam"]

    def test_explicit_target_agents_override(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("Financial report", {"target_agents": ["henry"]})
        assert agents == ["henry"]

    def test_explicit_target_agents_string(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("anything", {"target_agents": "theo"})
        assert agents == ["theo"]

    def test_unknown_content_defaults_to_charles(self, adapter: ManualInputAdapter) -> None:
        agents = adapter.get_target_agents("Hello, how are you?", {})
        assert agents == ["charles"]

    @pytest.mark.asyncio
    async def test_ingest_returns_correct_structure(self, adapter: ManualInputAdapter) -> None:
        result = await adapter.ingest("New task for the kanban board", {})
        assert result["status"] == "ingested"
        assert "routed_to" in result
        assert result["content_type"] == "task"

    def test_persist_outcomes_writes_json(
        self, adapter: ManualInputAdapter, temp_dir: Path
    ) -> None:
        with patch.object(
            type(adapter),
            "persist_outcomes",
            wraps=adapter.persist_outcomes,
        ):
            # Monkeypatch the state dir to use temp
            import vastian.bridges.content_bridge.manual_input as mod

            original = mod._get_state_dir
            mod._get_state_dir = lambda: temp_dir / "state" / "content-bridge" / "manual"
            try:
                adapter.persist_outcomes({"routed_to": ["charles"], "status": "done"})
                out_dir = temp_dir / "state" / "content-bridge" / "manual"
                files = list(out_dir.glob("*.json"))
                assert len(files) == 1
                data = json.loads(files[0].read_text(encoding="utf-8"))
                assert data["status"] == "done"
            finally:
                mod._get_state_dir = original

    def test_detect_content_type(self, adapter: ManualInputAdapter) -> None:
        assert adapter._detect_content_type("A meeting summary", {}) == "meeting"
        assert adapter._detect_content_type("Balance sheet info", {}) == "financial"
        assert adapter._detect_content_type("New kanban task", {}) == "task"
        assert adapter._detect_content_type("The strategy and roadmap", {}) == "strategy"
        assert adapter._detect_content_type("Research and knowledge base", {}) == "research"
        assert adapter._detect_content_type("Prompt drift audit results", {}) == "audit"
        assert adapter._detect_content_type("Run a scenario simulation", {}) == "simulation"
        assert adapter._detect_content_type("Hello there", {}) == "general"


class TestMeetingSummaryAdapter:
    @pytest.fixture
    def adapter(self) -> MeetingSummaryAdapter:
        return MeetingSummaryAdapter()

    def test_get_target_agents_defaults(self, adapter: MeetingSummaryAdapter) -> None:
        agents = adapter.get_target_agents("Some meeting content", {})
        assert "charles" in agents
        assert "liam" in agents
        assert "arjuna" in agents
        assert "maya" in agents

    def test_get_target_agents_adds_finley_for_financial(
        self, adapter: MeetingSummaryAdapter
    ) -> None:
        agents = adapter.get_target_agents("Meeting content", {"financial": True})
        assert "finley" in agents

    def test_explicit_target_agents(self, adapter: MeetingSummaryAdapter) -> None:
        agents = adapter.get_target_agents("Content", {"target_agents": ["henry", "theo"]})
        assert agents == ["henry", "theo"]

    @pytest.mark.asyncio
    async def test_ingest_returns_structured_result(self, adapter: MeetingSummaryAdapter) -> None:
        result = await adapter.ingest("## Decisions\n- We decided to proceed", {})
        assert result["status"] == "ingested"
        assert "routed_to" in result
        assert isinstance(result["routed_to"], list)


class TestTranscriptAdapter:
    @pytest.fixture
    def adapter(self) -> TranscriptAdapter:
        return TranscriptAdapter()

    def test_get_target_agents_defaults(self, adapter: TranscriptAdapter) -> None:
        agents = adapter.get_target_agents("Some transcript", {})
        assert "charles" in agents
        assert "liam" in agents

    def test_get_target_agents_adds_finley_for_financial(self, adapter: TranscriptAdapter) -> None:
        agents = adapter.get_target_agents("Transcript", {"financial": True})
        assert "finley" in agents

    @pytest.mark.asyncio
    async def test_ingest_returns_structured_result(self, adapter: TranscriptAdapter) -> None:
        result = await adapter.ingest("Speaker A: Hello\nSpeaker B: Hi", {"auto_summarize": False})
        assert result["status"] == "ingested"
        assert "routed_to" in result
        assert result["raw_length"] > 0

    @pytest.mark.asyncio
    async def test_ingest_without_auto_summarize(self, adapter: TranscriptAdapter) -> None:
        result = await adapter.ingest("Raw transcript text", {"auto_summarize": False})
        assert "summary" not in result
