#!/usr/bin/env python3
"""Validate Claude Code subagent definition files (agents/*.md).

Checks the YAML frontmatter of every agent file using only the standard
library. It understands the small YAML subset used in subagent files:
`key: value` pairs, quoted strings, and simple `- item` lists.

Usage:
    python3 scripts/validate_agents.py [AGENTS_DIR ...]

Exit code 0 when every file is valid, 1 otherwise.
"""
from __future__ import annotations

import re
import sys
from dataclasses import dataclass, field
from pathlib import Path

NAME_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
KNOWN_TOOLS = {
    "Agent", "Bash", "Edit", "Glob", "Grep", "LS", "MultiEdit", "NotebookEdit",
    "NotebookRead", "Read", "Skill", "TodoWrite", "WebFetch", "WebSearch", "Write",
}
MODELS = {"inherit", "sonnet", "opus", "haiku", "fable"}
COLORS = {"red", "blue", "green", "yellow", "purple", "orange", "pink", "cyan"}
PERMISSION_MODES = {"default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", "manual"}
MAX_DESCRIPTION = 1024
MIN_BODY_CHARS = 200


@dataclass
class Result:
    path: Path
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)

    @property
    def ok(self) -> bool:
        return not self.errors


def _unquote(value: str) -> str:
    value = value.strip()
    if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
        return value[1:-1]
    return value


def parse_frontmatter(text: str) -> tuple[dict[str, object], str]:
    """Split a markdown file into (frontmatter dict, body).

    Raises ValueError if the file has no frontmatter block.
    """
    lines = text.splitlines()
    if not lines or lines[0].strip() != "---":
        raise ValueError("file must start with a '---' frontmatter line")
    try:
        end = next(i for i in range(1, len(lines)) if lines[i].strip() == "---")
    except StopIteration:
        raise ValueError("frontmatter is not closed with '---'") from None

    data: dict[str, object] = {}
    current_list: list[str] | None = None
    for raw in lines[1:end]:
        if not raw.strip() or raw.lstrip().startswith("#"):
            continue
        stripped = raw.strip()
        if stripped.startswith("- ") and current_list is not None:
            current_list.append(_unquote(stripped[2:]))
            continue
        if ":" not in raw or raw[0].isspace():
            raise ValueError(f"cannot parse frontmatter line: {raw!r}")
        key, _, value = raw.partition(":")
        key, value = key.strip(), value.strip()
        if key in data:
            raise ValueError(f"duplicate key: {key}")
        if value == "":
            current_list = []
            data[key] = current_list
        else:
            current_list = None
            data[key] = _unquote(value)
    body = "\n".join(lines[end + 1:])
    return data, body


def split_tools(value: object) -> list[str]:
    if isinstance(value, list):
        items = value
    else:
        items = str(value).split(",")
    return [item.strip() for item in items if item.strip()]


def tool_base(tool: str) -> str:
    """'Bash(git diff:*)' -> 'Bash', 'Agent(worker)' -> 'Agent'."""
    return tool.split("(", 1)[0].strip()


def validate_file(path: Path) -> Result:
    result = Result(path)
    try:
        meta, body = parse_frontmatter(path.read_text(encoding="utf-8"))
    except (ValueError, UnicodeDecodeError) as exc:
        result.errors.append(str(exc))
        return result

    name = meta.get("name")
    if not isinstance(name, str) or not name:
        result.errors.append("missing required field: name")
    else:
        if not NAME_RE.match(name):
            result.errors.append(f"name {name!r} should be lowercase words joined by hyphens")
        if name != path.stem:
            result.warnings.append(f"name {name!r} does not match file name {path.stem!r}")

    description = meta.get("description")
    if not isinstance(description, str) or not description.strip():
        result.errors.append("missing required field: description")
    elif len(description) > MAX_DESCRIPTION:
        result.errors.append(f"description is {len(description)} chars; keep it under {MAX_DESCRIPTION}")
    elif "use" not in description.lower():
        result.warnings.append("description should say when to use the agent (for example 'Use when ...')")

    for key in ("tools", "disallowedTools"):
        if key in meta:
            tools = split_tools(meta[key])
            if not tools:
                result.errors.append(f"{key} is present but empty")
            for tool in tools:
                base = tool_base(tool)
                if base.startswith("mcp__"):
                    continue
                if base not in KNOWN_TOOLS:
                    result.warnings.append(f"unknown tool in {key}: {tool!r}")

    model = meta.get("model")
    if model is not None and model not in MODELS and not str(model).startswith("claude-"):
        result.errors.append(f"model {model!r} must be one of {sorted(MODELS)} or a full model ID")

    color = meta.get("color")
    if color is not None and color not in COLORS:
        result.errors.append(f"color {color!r} must be one of {sorted(COLORS)}")

    mode = meta.get("permissionMode")
    if mode is not None and mode not in PERMISSION_MODES:
        result.errors.append(f"permissionMode {mode!r} must be one of {sorted(PERMISSION_MODES)}")

    if len(body.strip()) < MIN_BODY_CHARS:
        result.errors.append(f"system prompt body is shorter than {MIN_BODY_CHARS} characters")

    return result


def validate_dir(directory: Path) -> list[Result]:
    results = [validate_file(p) for p in sorted(directory.rglob("*.md"))]
    seen: dict[str, Path] = {}
    for res in results:
        try:
            meta, _ = parse_frontmatter(res.path.read_text(encoding="utf-8"))
        except (ValueError, UnicodeDecodeError):
            continue
        name = meta.get("name")
        if isinstance(name, str) and name:
            if name in seen and seen[name].parent == res.path.parent:
                res.errors.append(f"duplicate name {name!r} (also in {seen[name].name})")
            seen.setdefault(name, res.path)
    return results


def main(argv: list[str]) -> int:
    dirs = [Path(a) for a in argv] or [Path(__file__).resolve().parent.parent / "agents"]
    failed = 0
    total = 0
    for directory in dirs:
        if not directory.is_dir():
            print(f"error: {directory} is not a directory", file=sys.stderr)
            return 1
        for res in validate_dir(directory):
            total += 1
            for w in res.warnings:
                print(f"WARN  {res.path}: {w}")
            for e in res.errors:
                print(f"ERROR {res.path}: {e}")
            if not res.ok:
                failed += 1
    print(f"{total - failed}/{total} agent files valid")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
