#!/usr/bin/env python3
"""Verify CARBON's bare Claude command alias installer."""

from __future__ import annotations

import json
import subprocess
import sys
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parent.parent
INSTALLER = ROOT / "scripts" / "install-claude-aliases.py"


def preferred_alias_name(canonical_name: str) -> str:
    if canonical_name == "carbon" or canonical_name.startswith("carbon-"):
        return canonical_name
    return f"carbon-{canonical_name}"


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-claude-alias-") as temporary:
        skills_dir = Path(temporary) / "skills"
        stale_alias = skills_dir / "carbon-upgrade" / "SKILL.md"
        stale_alias.parent.mkdir(parents=True)
        stale_alias.write_text(
            "---\nname: carbon-upgrade\ndescription: stale alias\n---\n\n"
            "<!-- generated by CARBON bare Claude alias installer -->\n",
            encoding="utf-8",
        )
        result = subprocess.run(
            [
                sys.executable,
                str(INSTALLER),
                "--plugin-root",
                str(ROOT),
                "--skills-dir",
                str(skills_dir),
                "--apply",
            ],
            check=True,
            capture_output=True,
            text=True,
        )
        payload = json.loads(result.stdout)
        aliases = sorted(skills_dir.glob("*/SKILL.md"))
        assert payload["status"] == "applied"
        assert payload["aliases"] == 44
        assert payload["staleAliasesRemoved"] == 1
        assert len(aliases) == 44
        assert (skills_dir / "carbon-demo" / "SKILL.md").is_file()
        assert not stale_alias.exists()
        assert (skills_dir / "carbon-ai-upgrade" / "SKILL.md").is_file()
        assert (skills_dir / "carbon-more" / "SKILL.md").is_file()
        assert (skills_dir / "carbon-human" / "SKILL.md").is_file()
        assert (skills_dir / "carbon-feedback" / "SKILL.md").is_file()
        assert (skills_dir / "carbon-chatbot" / "SKILL.md").is_file()
        assert (skills_dir / "carbon-failure" / "SKILL.md").is_file()
        assert not (skills_dir / "ai-upgrade").exists()
        assert not (skills_dir / "chatbot").exists()
        assert not (skills_dir / "failure").exists()

        canonical_by_alias = {}
        for source in sorted((ROOT / "skills").glob("*/SKILL.md")):
            source_text = source.read_text(encoding="utf-8")
            canonical_name = next(
                line.split(":", 1)[1].strip()
                for line in source_text.splitlines()
                if line.startswith("name:")
            )
            canonical_by_alias[preferred_alias_name(canonical_name)] = source.resolve()

        for alias in aliases:
            text = alias.read_text(encoding="utf-8")
            name = alias.parent.name
            canonical = canonical_by_alias[name]
            assert name == "carbon" or name.startswith("carbon-")
            assert f"name: {name}" in text
            assert f"unnamespaced `/{name}` alias" in text
            assert str(canonical) in text
            assert "$ARGUMENTS" in text
            assert "carbon:carbon" not in text
            assert "embedded `text/html` resource as a Claude artifact" in text
            assert "absolute in-workspace `claudeChatLink`" in text
            assert "generic relative `chatLink`" in text
            assert "carbon_open_execution_plan" in text
            assert "Never invoke macOS `open`" in text

        remove = subprocess.run(
            [
                sys.executable,
                str(INSTALLER),
                "--plugin-root",
                str(ROOT),
                "--skills-dir",
                str(skills_dir),
                "--remove",
                "--apply",
            ],
            check=True,
            capture_output=True,
            text=True,
        )
        removed = json.loads(remove.stdout)
        assert removed["aliases"] == 44
        assert not list(skills_dir.glob("*/SKILL.md"))

        malicious_root = Path(temporary) / "malicious-plugin"
        malicious_skill = malicious_root / "skills" / "escape" / "SKILL.md"
        malicious_skill.parent.mkdir(parents=True)
        malicious_skill.write_text(
            "---\nname: ../../escape\ndescription: must not escape the alias directory\n---\n",
            encoding="utf-8",
        )
        rejected = subprocess.run(
            [
                sys.executable,
                str(INSTALLER),
                "--plugin-root",
                str(malicious_root),
                "--skills-dir",
                str(skills_dir),
                "--apply",
            ],
            check=False,
            capture_output=True,
            text=True,
        )
        assert rejected.returncode != 0
        assert not (Path(temporary) / "escape").exists()

    print("PASS: 44 consistently carbon-prefixed Claude commands, including carbon-human, carbon-feedback, carbon-demo, carbon-more, legacy bare-alias cleanup, specialist commands, removal, namespace isolation, and path containment verified.")
    return 0


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