"""Load Agent configuration files from JSON or YAML."""

from __future__ import annotations

import json
from pathlib import Path

import yaml

from src.models import AgentConfig

_SUPPORTED_EXTENSIONS = (".json", ".yaml", ".yml")


def load_agent_config(path: Path) -> AgentConfig:
    """Load a single Agent config from a JSON or YAML file.

    Args:
        path: Absolute or relative path to a .json, .yaml, or .yml file.

    Returns:
        A validated AgentConfig instance.

    Raises:
        FileNotFoundError: If the file does not exist at the given path.
        ValueError: If the file extension is not supported.
    """
    if not path.exists():
        raise FileNotFoundError(f"Agent config not found: {path}")

    suffix = path.suffix.lower()
    if suffix not in _SUPPORTED_EXTENSIONS:
        raise ValueError(
            f"Unsupported file format: '{suffix}'. "
            f"Use one of: {', '.join(_SUPPORTED_EXTENSIONS)}"
        )

    raw_text = path.read_text(encoding="utf-8")

    if suffix == ".json":
        data = json.loads(raw_text)
    else:
        data = yaml.safe_load(raw_text)

    return AgentConfig(**data)


def load_agents(
    names: list[str],
    agents_dir: Path = Path("agents"),
) -> dict[str, AgentConfig]:
    """Load multiple Agent configs by name from a directory.

    Searches for each name with all supported extensions (.json, .yaml, .yml).
    The first matching file wins.

    Args:
        names: List of agent names (without file extension).
        agents_dir: Directory that contains the agent config files.

    Returns:
        A dict mapping each name to its AgentConfig.

    Raises:
        FileNotFoundError: If no config file is found for any requested name.
    """
    agents: dict[str, AgentConfig] = {}

    for name in names:
        found = False
        for ext in _SUPPORTED_EXTENSIONS:
            candidate = agents_dir / f"{name}{ext}"
            if candidate.exists():
                agents[name] = load_agent_config(candidate)
                found = True
                break

        if not found:
            available = [
                p.stem
                for p in agents_dir.iterdir()
                if p.suffix.lower() in _SUPPORTED_EXTENSIONS
            ]
            raise FileNotFoundError(
                f"Agent config not found for '{name}'. "
                f"Available agents: {', '.join(sorted(available)) or '(none)'}"
            )

    return agents
