"""End-to-end agent tests with a fake model (no credentials needed)."""

from __future__ import annotations

from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
from icarus.runtime.context import UserContext


@pytest.fixture
def e2e_context(tmp_path: Path) -> UserContext:
    """Create a UserContext for e2e testing."""
    config_dir = tmp_path / ".icarus"
    config_dir.mkdir()
    (config_dir / "skills").mkdir()
    working_dir = tmp_path / "workspace"
    working_dir.mkdir()

    return UserContext(
        username="e2e-test",
        home_dir=tmp_path,
        working_dir=working_dir,
        config_dir=config_dir,
        memory_sources=[],
        skill_sources=[],
    )


def test_system_prompt_loads_template():
    """System prompt loads from system_prompt.md template — identity-neutral."""
    from icarus.runtime.agent import get_system_prompt

    prompt = get_system_prompt("icarus")
    # Template should NOT hardcode an agent name — identity comes from AGENTS.md
    assert "AI assistant" in prompt
    assert "Core Behavior" in prompt


def test_system_prompt_includes_skills_path():
    """System prompt includes the skills directory path."""
    from icarus.runtime.agent import get_system_prompt

    prompt = get_system_prompt("icarus")
    assert "~/.icarus/icarus/skills/" in prompt


def test_system_prompt_includes_model_identity():
    """System prompt includes model identity when configured."""
    from icarus.runtime.agent import get_system_prompt

    with patch("icarus.runtime.agent.settings") as mock_settings:
        mock_settings.model_name = "test-model"
        mock_settings.model_provider = "test-provider"
        mock_settings.model_context_limit = None
        prompt = get_system_prompt("icarus")
        assert "test-model" in prompt


@patch("icarus.runtime.agent.create_cli_agent")
@patch("icarus.runtime.builder.create_model")
def test_agent_creation_flow(mock_create_model, mock_cli_agent, e2e_context):
    """Full agent creation flow works end-to-end."""
    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(e2e_context)

    # Verify the chain was called
    mock_create_model.assert_called_once()
    mock_cli_agent.assert_called_once()

    # system_prompt should be None (let agent.py use get_system_prompt)
    call_kwargs = mock_cli_agent.call_args[1]
    assert call_kwargs.get("system_prompt") is None

    # Verify result
    assert result.graph is mock_graph
    assert result.backend is mock_backend
    assert result.model is mock_model
