#!/usr/bin/env python3
"""Hide namespaced CARBON plugin skills from Claude's slash-command menu."""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path


FIELD = "user-invocable: false"


def arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Mark Claude plugin skills as internal so bare user aliases own the slash menu."
    )
    parser.add_argument("plugin_root", help="Prepared Claude plugin root containing skills/.")
    parser.add_argument("--apply", action="store_true", help="Update skill frontmatter. Preview by default.")
    parser.add_argument("--check", action="store_true", help="Fail unless every skill is already hidden.")
    return parser.parse_args()


def insert_field(text: str) -> str:
    if re.search(r"^user-invocable:\s*false\s*$", text, re.MULTILINE):
        return text
    if not text.startswith("---\n"):
        raise ValueError("skill is missing YAML frontmatter")
    closing = text.find("\n---\n", 4)
    if closing < 0:
        raise ValueError("skill frontmatter is not closed")
    return text[:closing] + f"\n{FIELD}" + text[closing:]


def main() -> int:
    args = arguments()
    root = Path(args.plugin_root).expanduser().resolve()
    skills = sorted((root / "skills").glob("*/SKILL.md"))
    if not skills:
        raise SystemExit(f"No Claude plugin skills found under {root / 'skills'}")

    changed: list[str] = []
    missing: list[str] = []
    for skill in skills:
        text = skill.read_text(encoding="utf-8")
        configured = insert_field(text)
        if configured != text:
            missing.append(str(skill))
            if args.apply:
                skill.write_text(configured, encoding="utf-8")
                changed.append(str(skill))

    result = {
        "pluginRoot": str(root),
        "skills": len(skills),
        "hiddenFromSlashMenu": len(skills) - len(missing) + len(changed),
        "changed": changed,
        "missing": [] if args.apply else missing,
    }
    print(json.dumps(result, indent=2))
    if args.check and missing and not args.apply:
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
