from pathlib import Path

import pytest

from core.agent_loader import load_agent_config, load_named_agents


def test_load_agent_config_from_yaml(tmp_path: Path) -> None:
    path = tmp_path / "arch.yaml"
    path.write_text(
        """
name: arch
role: Architect
description: desc
system_prompt: prompt
input_schema_description: in
output_schema_description: out
input_schema: {type: object}
output_schema:
  type: object
  properties:
    response: {type: string}
  required: [response]
""".strip(),
        encoding="utf-8",
    )

    config = load_agent_config(path)

    assert config.name == "arch"


def test_load_agent_config_rejects_unsupported_extension(tmp_path: Path) -> None:
    path = tmp_path / "arch.txt"
    path.write_text("{}", encoding="utf-8")

    with pytest.raises(ValueError):
        load_agent_config(path)


def test_load_agent_config_rejects_missing_file(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        load_agent_config(tmp_path / "missing.yaml")


def test_load_agent_config_rejects_incompatible_output_schema(tmp_path: Path) -> None:
    path = tmp_path / "arch.yaml"
    path.write_text(
        """
name: arch
role: Architect
description: desc
system_prompt: prompt
input_schema_description: in
output_schema_description: out
input_schema: {type: object}
output_schema:
  type: object
  properties:
    answer: {type: string}
  required: [answer]
""".strip(),
        encoding="utf-8",
    )

    with pytest.raises(ValueError):
        load_agent_config(path)


def test_load_named_agents_returns_mapping(tmp_path: Path) -> None:
    path = tmp_path / "arch.yaml"
    path.write_text(
        """
name: arch
role: Architect
description: desc
system_prompt: prompt
input_schema_description: in
output_schema_description: out
input_schema: {type: object}
output_schema:
  type: object
  properties:
    response: {type: string}
  required: [response]
""".strip(),
        encoding="utf-8",
    )

    agents = load_named_agents(["arch"], tmp_path)

    assert list(agents) == ["arch"]


def test_pm_agent_schema_matches_pmdecision_shape(tmp_path: Path) -> None:
    path = tmp_path / "pm.yaml"
    path.write_text(
        """
name: pm
role: PM
description: desc
system_prompt: prompt
input_schema_description: in
output_schema_description: out
input_schema: {type: object}
output_schema:
  type: object
  properties:
    analysis: {type: string}
    next_action: {type: string}
    target_agent: {type: string}
    prompt_for_agent: {type: string}
    final_report: {type: string}
  required: [analysis, next_action]
""".strip(),
        encoding="utf-8",
    )

    config = load_agent_config(path)

    assert "analysis" in config.output_schema["properties"]
    assert "next_action" in config.output_schema["properties"]
