"""Agent configuration CRUD. Configs stored in $ROOHAI_DATA_DIR/agents/*.yaml."""

from __future__ import annotations

import os
import re
from pathlib import Path

import yaml

# Agent names must be URL-safe and filesystem-safe:
#   - Letters, digits, hyphens, and underscores only
#   - Must start with a letter or digit
#   - 1–64 characters
AGENT_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")

ROOHAI_DIR = Path(os.environ.get("ROOHAI_DATA_DIR", os.environ.get("VOICEAI_DATA_DIR", Path.home() / ".roohai")))
AGENTS_DIR = ROOHAI_DIR / "agents"


def _ensure_dir() -> None:
    AGENTS_DIR.mkdir(parents=True, exist_ok=True)


def list_agents() -> list[dict]:
    """List all saved agent configs."""
    _ensure_dir()
    agents = []
    for f in sorted(AGENTS_DIR.glob("*.yaml")):
        if f.name == ".gitkeep":
            continue
        data = yaml.safe_load(f.read_text())
        if isinstance(data, dict):
            agents.append(data)
    return agents


def get_agent(name: str) -> dict | None:
    """Get a single agent config by name."""
    _ensure_dir()
    path = AGENTS_DIR / f"{name}.yaml"
    if not path.exists():
        return None
    data = yaml.safe_load(path.read_text())
    return data if isinstance(data, dict) else None


def validate_agent_name(name: str) -> None:
    """Raise ValueError if *name* is not a valid agent name."""
    if not AGENT_NAME_RE.match(name):
        raise ValueError(
            f"Invalid agent name '{name}'. Names must be 1–64 characters, "
            "start with a letter or digit, and contain only letters, digits, "
            "hyphens, or underscores."
        )


def save_agent(config: dict) -> None:
    """Save an agent config. The config must have a 'name' key."""
    _ensure_dir()
    name = config["name"]
    validate_agent_name(name)
    path = AGENTS_DIR / f"{name}.yaml"
    path.write_text(yaml.safe_dump(config, default_flow_style=False))


def delete_agent(name: str) -> bool:
    """Delete an agent config. Returns True if it existed."""
    path = AGENTS_DIR / f"{name}.yaml"
    if path.exists():
        path.unlink()
        return True
    return False
