"""Bundled marketplace content — agents, templates, skills, registry.

All marketplace content is shipped inside the pip package so the CLI
works offline.  Functions here resolve ``Path`` objects for bundled
files and parse the YAML registry/frontmatter formats.
"""

from __future__ import annotations

from pathlib import Path

import yaml

_PKG_DIR = Path(__file__).parent


def bundled_registry_path() -> Path:
    """Return the path to the bundled ``registry.yaml``."""
    return _PKG_DIR / "registry.yaml"


def bundled_agent_path(name: str) -> Path | None:
    """Return the path to a bundled agent ``.md`` file, or ``None``."""
    path = _PKG_DIR / "agents" / f"{name}.md"
    return path if path.exists() else None


def bundled_template_path(filename: str) -> Path | None:
    """Return the path to a bundled template file, or ``None``."""
    path = _PKG_DIR / "templates" / filename
    return path if path.exists() else None


def bundled_skill_path(skill_name: str) -> Path | None:
    """Return the path to a bundled skill's ``SKILL.md``, or ``None``."""
    path = _PKG_DIR / "skills" / skill_name / "SKILL.md"
    return path if path.exists() else None


def list_bundled_agents() -> list[str]:
    """Return sorted list of bundled agent names (stems of ``.md`` files)."""
    agents_dir = _PKG_DIR / "agents"
    if not agents_dir.is_dir():
        return []
    return sorted(p.stem for p in agents_dir.glob("*.md"))


def list_bundled_templates() -> list[str]:
    """Return sorted list of bundled template filenames."""
    templates_dir = _PKG_DIR / "templates"
    if not templates_dir.is_dir():
        return []
    return sorted(p.name for p in templates_dir.glob("*.md"))


def list_bundled_skills() -> list[str]:
    """Return sorted list of bundled skill names (subdirectory names under skills/)."""
    skills_dir = _PKG_DIR / "skills"
    if not skills_dir.is_dir():
        return []
    return sorted(p.name for p in skills_dir.iterdir() if p.is_dir() and (p / "SKILL.md").exists())


def load_bundled_registry() -> dict:
    """Parse and return the bundled ``registry.yaml`` as a dict."""
    return yaml.safe_load(bundled_registry_path().read_text())


def parse_agent_frontmatter(path: Path) -> dict:
    """Parse YAML frontmatter from an agent ``.md`` file.

    Expects the file to start with ``---``, followed by YAML, then ``---``.
    Returns the parsed YAML as a dict, or an empty dict on parse failure.
    """
    text = path.read_text()
    if not text.startswith("---"):
        return {}
    parts = text.split("---", 2)
    if len(parts) < 3:  # noqa: PLR2004
        return {}
    try:
        result = yaml.safe_load(parts[1])
        return result if isinstance(result, dict) else {}
    except yaml.YAMLError:
        return {}
