from importlib import resources
import unittest
from collections import Counter
import tomllib
from pathlib import Path

import agentic_toolbelt
from setup import _data_files, _package_version

CANONICAL_SKILLS = (
    "docs",
    "exec-plan",
    "implement",
    "plan",
    "publish",
)


class PackagingTests(unittest.TestCase):
    def test_payload_files_are_available(self):
        root = resources.files(agentic_toolbelt)
        self.assertTrue((root / ".agents").is_dir())
        self.assertTrue((root / ".codex").is_dir())
        self.assertTrue((root / "AGENTS.md").is_file())
        self.assertTrue((root / ".agents" / "ralph" / "agents.sh").is_file())
        self.assertTrue((root / ".codex" / "skills" / "commit" / "SKILL.md").is_file())
        self.assertTrue((root / "templates" / "codex" / "config.toml.example").is_file())
        self.assertTrue((root / "templates" / "codex" / "agents" / "explorer.toml").is_file())
        self.assertTrue((root / "templates" / "codex" / "agents" / "reviewer.toml").is_file())
        self.assertTrue((root / "templates" / "codex" / "agents" / "worker.toml").is_file())
        self.assertTrue((root / ".agents" / "skills" / "plan" / "SKILL.md").is_file())
        self.assertTrue((root / ".agents" / "skills" / "implement" / "SKILL.md").is_file())
        self.assertTrue((root / ".agents" / "skills" / "docs" / "SKILL.md").is_file())
        self.assertTrue((root / ".agents" / "skills" / "publish" / "SKILL.md").is_file())

    def test_setup_data_files_excludes_cache_artifacts(self):
        files = _data_files()

        self.assertNotIn("__pycache__/__init__.cpython-312.pyc", files)
        self.assertFalse(any(path.endswith(".pyc") for path in files))

    def test_setup_version_matches_pyproject(self):
        version = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
        self.assertEqual(version, _package_version())

    def test_shared_skills_are_canonical_in_agents_only(self):
        root = resources.files(agentic_toolbelt)

        for skill in CANONICAL_SKILLS:
            self.assertTrue((root / ".agents" / "skills" / skill / "SKILL.md").is_file())
            self.assertFalse((root / ".github" / "skills" / skill / "SKILL.md").exists())

    def test_skill_names_are_unique_across_packaged_sources(self):
        root = resources.files(agentic_toolbelt)
        skill_files = list(root.glob(".agents/skills/*/SKILL.md")) + list(
            root.glob(".github/skills/*/SKILL.md")
        ) + list(root.glob(".codex/skills/*/SKILL.md"))
        counts = Counter(path.parent.name for path in skill_files)
        duplicates = {name: count for name, count in counts.items() if count > 1}

        self.assertEqual({}, duplicates)
