"""Local Claude Code skill management.

Handles installing/updating the bundled manta-client SKILL.md
to ~/.claude/skills/manta-client/.
"""

from __future__ import annotations

import re
from pathlib import Path

from manta_client import __version__

SKILL_NAME = "manta-client"
LOCAL_SKILL_DIR = Path.home() / ".claude" / "skills" / SKILL_NAME
LOCAL_SKILL_PATH = LOCAL_SKILL_DIR / "SKILL.md"
_VERSION_RE = re.compile(r"^skill-version:\s*[\"']?(.+?)[\"']?\s*$", re.MULTILINE)


def get_bundled_skill_content() -> str:
    """Read the SKILL.md bundled with the package."""
    bundled = Path(__file__).resolve().parent / "skills" / SKILL_NAME / "SKILL.md"
    return bundled.read_text(encoding="utf-8")


def get_installed_skill_version() -> str | None:
    """Extract skill-version from the locally installed SKILL.md."""
    if not LOCAL_SKILL_PATH.exists():
        return None
    content = LOCAL_SKILL_PATH.read_text(encoding="utf-8")
    m = _VERSION_RE.search(content)
    return m.group(1) if m else None


def get_package_version() -> str:
    """Return the current manta-client package version."""
    return __version__


def is_skill_outdated() -> bool | None:
    """Check if the local skill is outdated.

    Returns:
        True if outdated, False if up-to-date, None if not installed.
    """
    installed = get_installed_skill_version()
    if installed is None:
        return None
    return installed != __version__


def inject_version(content: str, version: str) -> str:
    """Inject skill-version into SKILL.md frontmatter."""
    if not content.startswith("---\n"):
        return content
    # Insert skill-version after opening ---
    return content.replace("---\n", f'---\nskill-version: "{version}"\n', 1)


def install_local_skill(force: bool = False) -> tuple[str, str | None, str]:
    """Install bundled SKILL.md to ~/.claude/skills/manta-client/.

    Args:
        force: Skip version check and overwrite.

    Returns:
        Tuple of (action, old_version, new_version) where action is
        "installed", "updated", or "skipped".
    """
    old_version = get_installed_skill_version()
    new_version = __version__

    if not force and old_version == new_version:
        return "skipped", old_version, new_version

    content = get_bundled_skill_content()
    content = inject_version(content, new_version)

    LOCAL_SKILL_DIR.mkdir(parents=True, exist_ok=True)
    LOCAL_SKILL_PATH.write_text(content, encoding="utf-8")

    action = "installed" if old_version is None else "updated"
    return action, old_version, new_version
