"""Tests for ievo.core.project.ProjectManifest."""

from __future__ import annotations

from pathlib import Path

import yaml

from ievo.core.project import ProjectManifest


def test_load_manifest(tmp_project: Path) -> None:
    m = ProjectManifest.load(tmp_project)
    assert m.project == "test-project"
    assert m.version == "0.1.0"
    assert m.agents == {}


def test_load_with_defaults(tmp_path: Path) -> None:
    (tmp_path / "ievo.yaml").write_text("project: minimal\n")
    m = ProjectManifest.load(tmp_path)
    assert m.project == "minimal"
    assert m.version == "0.1.0"
    assert m.created == ""
    assert m.agents == {}
    assert m.overrides == {}


def test_save_roundtrip(tmp_path: Path) -> None:
    m = ProjectManifest(project="roundtrip", version="1.0.0", created="2026-01-01")
    m.add_agent("coder", "0.2.0")
    m.save(tmp_path)

    loaded = ProjectManifest.load(tmp_path)
    assert loaded.project == "roundtrip"
    assert loaded.version == "1.0.0"
    assert loaded.agents == {"coder": "0.2.0"}


def test_save_includes_overrides(tmp_path: Path) -> None:
    m = ProjectManifest(project="test", overrides={"coder": {"model": {"primary": "opus"}}})
    m.save(tmp_path)

    data = yaml.safe_load((tmp_path / "ievo.yaml").read_text())
    assert "overrides" in data
    assert data["overrides"]["coder"]["model"]["primary"] == "opus"


def test_save_omits_empty_overrides(tmp_path: Path) -> None:
    m = ProjectManifest(project="test")
    m.save(tmp_path)

    data = yaml.safe_load((tmp_path / "ievo.yaml").read_text())
    assert "overrides" not in data


def test_has_agent() -> None:
    m = ProjectManifest(project="test", agents={"coder": "0.1.0"})
    assert m.has_agent("coder") is True
    assert m.has_agent("tester") is False


def test_add_agent() -> None:
    m = ProjectManifest(project="test")
    m.add_agent("spec-writer", "0.1.0")
    assert m.agents == {"spec-writer": "0.1.0"}


def test_remove_agent() -> None:
    m = ProjectManifest(
        project="test",
        agents={"coder": "0.1.0", "architect": "0.1.0"},
        overrides={"coder": {"model": {"primary": "opus"}}},
    )
    m.remove_agent("coder")
    assert "coder" not in m.agents
    assert "coder" not in m.overrides
    assert "architect" in m.agents


def test_remove_nonexistent_agent() -> None:
    m = ProjectManifest(project="test")
    m.remove_agent("nonexistent")  # should not raise
    assert m.agents == {}
