"""Tests for the agent builder."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import builtins


def test_get_current_time_returns_stable_format():
    """get_current_time returns a parseable datetime string."""
    from icarus.tools import get_current_time

    result = get_current_time()
    # Format: "Thursday, 2026-03-06 14:30:45 EET"
    assert "," in result  # day-of-week comma
    assert "-" in result  # date separators
    assert ":" in result  # time separators


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_create_icarus_agent_with_model_instance(
    mock_create_model, mock_cli_agent, user_context
):
    """create_icarus_agent works with a BaseChatModel instance."""
    from icarus.runtime.builder import create_icarus_agent

    mock_model = MagicMock()
    mock_graph = MagicMock()
    mock_backend = MagicMock()
    mock_cli_agent.return_value = (mock_graph, mock_backend)

    result = create_icarus_agent(user_context, model=mock_model)

    assert result.graph is mock_graph
    assert result.backend is mock_backend
    assert result.model is mock_model
    # Should NOT call create_model when given a model instance
    mock_create_model.assert_not_called()
    # Should call create_cli_agent with the model
    mock_cli_agent.assert_called_once()
    call_kwargs = mock_cli_agent.call_args
    assert call_kwargs.kwargs["model"] is mock_model


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_create_icarus_agent_with_model_spec(
    mock_create_model, mock_cli_agent, user_context
):
    """create_icarus_agent resolves model spec via create_model."""
    from icarus.runtime.builder import create_icarus_agent

    mock_model = MagicMock()
    mock_result = MagicMock()
    mock_result.model = mock_model
    mock_create_model.return_value = mock_result

    mock_graph = MagicMock()
    mock_backend = MagicMock()
    mock_cli_agent.return_value = (mock_graph, mock_backend)

    result = create_icarus_agent(user_context, model="azure_ai:Kimi-K2.5")

    assert result.graph is mock_graph
    mock_create_model.assert_called_once_with("azure_ai:Kimi-K2.5")


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_create_icarus_agent_delegates_prompt_to_agent(
    mock_create_model, mock_cli_agent, user_context
):
    """create_icarus_agent lets agent.py handle system prompt via get_system_prompt()."""
    from icarus.runtime.builder import create_icarus_agent

    mock_model = MagicMock()
    mock_result = MagicMock()
    mock_result.model = mock_model
    mock_create_model.return_value = mock_result
    mock_cli_agent.return_value = (MagicMock(), MagicMock())

    create_icarus_agent(user_context)

    call_kwargs = mock_cli_agent.call_args.kwargs
    assert call_kwargs["assistant_id"] == "default"
    # system_prompt is not passed — agent.py uses get_system_prompt() fallback
    assert "system_prompt" not in call_kwargs


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_create_icarus_agent_passes_memory_dir(
    mock_create_model, mock_cli_agent, user_context
):
    """create_icarus_agent passes memory_dir from UserContext to create_cli_agent."""
    from icarus.runtime.builder import create_icarus_agent

    mock_model = MagicMock()
    mock_result = MagicMock()
    mock_result.model = mock_model
    mock_create_model.return_value = mock_result
    mock_cli_agent.return_value = (MagicMock(), MagicMock())

    create_icarus_agent(user_context)

    call_kwargs = mock_cli_agent.call_args.kwargs
    assert call_kwargs["memory_dir"] == user_context.memory_dir


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_create_icarus_agent_works_without_pim(
    mock_create_model, mock_cli_agent, user_context
):
    """create_icarus_agent works when PIM is not installed (ImportError)."""
    mock_model = MagicMock()
    mock_result = MagicMock()
    mock_result.model = mock_model
    mock_create_model.return_value = mock_result
    mock_cli_agent.return_value = (MagicMock(), MagicMock())

    # Temporarily block icarus.tools.pim import inside builder
    _real_import = builtins.__import__

    def _blocking_import(name, *args, **kwargs):
        if name == "icarus.tools.pim":
            raise ImportError("No module named 'icarus.tools.pim'")
        return _real_import(name, *args, **kwargs)

    with patch("builtins.__import__", side_effect=_blocking_import):
        # Reload builder to re-execute its import-time code isn't needed —
        # the try/except is inside the function body
        from icarus.runtime.builder import create_icarus_agent
        result = create_icarus_agent(user_context, model=mock_model)

    assert result.graph is not None
    # Verify create_cli_agent was called (agent works without PIM)
    mock_cli_agent.assert_called_once()
