"""CloneBox profile templates for various dev tools.

Each tool gets a YAML profile that defines the VM configuration:
  - Base image, resources (memory, vcpus)
  - Packages and apps to install
  - Shared paths (virtiofs mounts from host)
  - Cloned paths (copied into VM on creation)
  - GUI/SPICE settings

Profile merge order:
  1. Tool base profile (e.g. windsurf.clonebox.yaml)
  2. Account override (e.g. windsurf.work-anthropic.yaml)
  3. CLI overrides (--memory, --vcpus, etc.)
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import structlog

logger = structlog.get_logger()

PROFILES_DIR = Path(__file__).parent


def get_builtin_profile(tool: str) -> Path | None:
    """Get the path to a built-in profile YAML for a tool."""
    profile = PROFILES_DIR / f"{tool}.clonebox.yaml"
    if profile.exists():
        return profile
    return None


def list_builtin_profiles() -> list[str]:
    """List all available built-in profile names."""
    return sorted(
        p.stem.replace(".clonebox", "")
        for p in PROFILES_DIR.glob("*.clonebox.yaml")
    )


def merge_profiles(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
    """Deep-merge two profile dicts. Override values take precedence.

    Lists are replaced (not appended). Nested dicts are merged recursively.
    """
    result = dict(base)
    for key, value in override.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_profiles(result[key], value)
        else:
            result[key] = value
    return result


def load_profile_yaml(path: Path) -> dict[str, Any]:
    """Load a YAML profile, with graceful fallback if PyYAML is not installed."""
    try:
        import yaml
    except ImportError:
        logger.warning("pyyaml_not_installed", hint="pip install proxym[vm]")
        return {}
    try:
        return yaml.safe_load(path.read_text()) or {}
    except Exception as e:
        logger.error("profile_load_failed", path=str(path), error=str(e))
        return {}
