from __future__ import annotations

import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch

from src import agent_core


class AgentCoreTests(unittest.TestCase):
    def test_run_returns_error_when_deep_agent_unavailable(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            artifacts = Path(tmp)
            with patch.object(agent_core, "ARTIFACTS", artifacts), patch.object(
                agent_core, "_get_deep_agent", return_value=(None, "missing")
            ):
                result = agent_core.run("mode=overview")

        self.assertIn("Deep Agent initialization failed", result)
        self.assertIn("fallback pipeline has been intentionally disabled", result)

    def test_run_uses_deep_agent_output_when_available(self) -> None:
        dummy_agent = Mock()
        dummy_agent.invoke.return_value = {"messages": [{"role": "assistant", "content": "deep-output"}]}

        with tempfile.TemporaryDirectory() as tmp:
            artifacts = Path(tmp)
            with patch.object(agent_core, "ARTIFACTS", artifacts), patch.object(
                agent_core, "_get_deep_agent", return_value=(dummy_agent, None)
            ):
                result = agent_core.run("mode=overview")

        self.assertIn("deep-output", result)

    def test_run_returns_error_when_deep_agent_execution_fails(self) -> None:
        dummy_agent = Mock()
        dummy_agent.invoke.side_effect = RuntimeError("boom")
        with tempfile.TemporaryDirectory() as tmp:
            artifacts = Path(tmp)
            with patch.object(agent_core, "ARTIFACTS", artifacts), patch.object(
                agent_core, "_get_deep_agent", return_value=(dummy_agent, None)
            ):
                result = agent_core.run("mode=overview")
        self.assertIn("Deep Agent execution failed", result)

    def test_extract_agent_output_supports_block_content(self) -> None:
        result = {"messages": [{"role": "assistant", "content": [{"type": "text", "text": "hello"}]}]}
        self.assertEqual(agent_core._extract_agent_output(result), "hello")


if __name__ == "__main__":
    unittest.main()
