"""Configuration loading from launcher.yaml."""

from pathlib import Path
from typing import Optional

import yaml

from mercury_launcher.models import AgentConfig, LauncherConfig


DEFAULT_CONFIG_PATHS = [
    Path("launcher.yaml"),
    Path("launcher.yml"),
    Path.home() / ".mercury" / "launcher.yaml",
]


def load_config(path: Optional[Path] = None) -> LauncherConfig:
    """Load launcher config from YAML file.

    Searches default paths if no explicit path given.
    """
    if path:
        return _parse_config(path)

    for default_path in DEFAULT_CONFIG_PATHS:
        if default_path.exists():
            return _parse_config(default_path)

    return LauncherConfig()


def _parse_config(path: Path) -> LauncherConfig:
    """Parse a YAML config file into LauncherConfig."""
    with open(path) as f:
        raw = yaml.safe_load(f) or {}

    agents = []
    for entry in raw.get("agents", []):
        # Expand ~ in working_directory
        if "working_directory" in entry:
            entry["working_directory"] = str(Path(entry["working_directory"]).expanduser())
        agents.append(AgentConfig(**entry))

    log_dir = raw.get("log_dir")
    if log_dir:
        log_dir = Path(log_dir).expanduser()

    return LauncherConfig(
        agents=agents,
        log_level=raw.get("log_level", "INFO"),
        log_dir=log_dir,
    )


def add_agent_to_config(
    config_path: Path,
    name: str,
    api_key: str,
    working_dir: str,
    mercury_url: Optional[str] = None,
) -> None:
    """Append an agent entry to the config file."""
    if config_path.exists():
        with open(config_path) as f:
            raw = yaml.safe_load(f) or {}
    else:
        raw = {}

    agents = raw.setdefault("agents", [])
    entry = {
        "name": name,
        "mcp_api_key": api_key,
        "working_directory": working_dir,
    }
    if mercury_url:
        entry["mercury_url"] = mercury_url
    agents.append(entry)

    config_path.parent.mkdir(parents=True, exist_ok=True)
    with open(config_path, "w") as f:
        yaml.dump(raw, f, default_flow_style=False, sort_keys=False)
