"""YAML topology loading and validation."""

from __future__ import annotations

import logging
from pathlib import Path

import yaml
from pydantic import ValidationError

from .schema import TopologySpec

logger = logging.getLogger("vmcluster_mcp.topology")


def load_topology(name: str, topology_dir: str) -> TopologySpec:
    """Load and validate a topology YAML file by name.

    Args:
        name: Topology name (filename without .yaml extension)
        topology_dir: Directory containing topology YAML files

    Returns:
        Validated TopologySpec

    Raises:
        FileNotFoundError: If topology file does not exist
        ValueError: If YAML is malformed or fails schema validation (includes field path)
    """
    topology_path = Path(topology_dir) / f"{name}.yaml"
    if not topology_path.is_file():
        raise FileNotFoundError(f"Topology file not found: {topology_path}")

    with open(topology_path) as f:
        raw = yaml.safe_load(f)

    if not isinstance(raw, dict):
        raise ValueError(f"Topology file must contain a YAML mapping, got {type(raw).__name__}: {topology_path}")

    try:
        spec = TopologySpec(**raw)
    except ValidationError as e:
        field_errors = []
        for err in e.errors():
            loc = " -> ".join(str(part) for part in err["loc"])
            field_errors.append(f"  {loc}: {err['msg']}")
        raise ValueError(f"Topology validation failed for {topology_path}:\n" + "\n".join(field_errors)) from e

    logger.info("Loaded topology %s from %s (%d nodes)", name, topology_path, len(spec.nodes))
    return spec
