"""Tests for agent_builder CLI."""

from __future__ import annotations

import json
from pathlib import Path

import yaml

from agent_builder import build_agent_config, AGENT_BUILDER_SYSTEM_PROMPT
from src.models import AgentConfig


class MockLLMClient:
    """Mock LLM client for agent builder."""

    def __init__(self, response: str) -> None:
        self.response = response

    def chat(self, system: str, messages: list[dict[str, str]]) -> str:
        return self.response


class TestBuildAgentConfig:
    """Tests for build_agent_config function."""

    def test_build_agent_config_returns_agent_config(self) -> None:
        llm_response = json.dumps({
            "role": "Chief Product Officer",
            "system_prompt": "You are a demanding product manager focused on simplicity.",
        })
        mock_client = MockLLMClient(response=llm_response)
        config = build_agent_config(name="steve_jobs", description="Mimics Steve Jobs' demanding product perspective", client=mock_client)
        assert isinstance(config, AgentConfig)
        assert config.name == "steve_jobs"
        assert config.role == "Chief Product Officer"
        assert "simplicity" in config.system_prompt

    def test_build_agent_config_saves_json(self, tmp_path: Path) -> None:
        llm_response = json.dumps({"role": "Architect", "system_prompt": "You are an architect."})
        mock_client = MockLLMClient(response=llm_response)
        config = build_agent_config(name="arch", description="Software architect", client=mock_client, output_dir=tmp_path, fmt="json")
        output_path = tmp_path / "arch.json"
        assert output_path.exists()
        loaded = json.loads(output_path.read_text(encoding="utf-8"))
        assert loaded["name"] == "arch"

    def test_build_agent_config_saves_yaml(self, tmp_path: Path) -> None:
        llm_response = json.dumps({"role": "DevOps", "system_prompt": "You are DevOps."})
        mock_client = MockLLMClient(response=llm_response)
        config = build_agent_config(name="devops", description="DevOps engineer", client=mock_client, output_dir=tmp_path, fmt="yaml")
        output_path = tmp_path / "devops.yaml"
        assert output_path.exists()
        loaded = yaml.safe_load(output_path.read_text(encoding="utf-8"))
        assert loaded["name"] == "devops"
