"""Project manifest (ievo.yaml) handling."""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path

import yaml

from ievo.core.config import IEVO_MANIFEST


@dataclass
class ProjectManifest:
    """Represents ievo.yaml."""

    project: str
    version: str = "0.1.0"
    created: str = ""
    agents: dict[str, str] = field(default_factory=dict)
    overrides: dict[str, dict] = field(default_factory=dict)

    # ── I/O ────────────────────────────────────────────────────

    @classmethod
    def load(cls, root: Path) -> ProjectManifest:
        path = root / IEVO_MANIFEST
        data = yaml.safe_load(path.read_text())
        return cls(
            project=data.get("project", root.name),
            version=data.get("version", "0.1.0"),
            created=data.get("created", ""),
            agents=data.get("agents", {}),
            overrides=data.get("overrides", {}),
        )

    def save(self, root: Path) -> None:
        path = root / IEVO_MANIFEST
        data = {
            "project": self.project,
            "version": self.version,
            "created": self.created,
            "agents": self.agents,
        }
        if self.overrides:
            data["overrides"] = self.overrides
        path.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))

    # ── Helpers ────────────────────────────────────────────────

    def has_agent(self, name: str) -> bool:
        return name in self.agents

    def add_agent(self, name: str, version: str) -> None:
        self.agents[name] = version

    def remove_agent(self, name: str) -> None:
        self.agents.pop(name, None)
        self.overrides.pop(name, None)
