#!/usr/bin/env python3
"""Package a skill directory into a distributable archive.

Creates a .tar.gz archive of a skill directory, excluding workspace
and temporary files.

Usage:
    python3 package_skill.py .claude/skills/my-skill
    python3 package_skill.py .claude/skills/my-skill --output my-skill-v1.tar.gz
"""

import argparse
import os
import sys
import tarfile
from pathlib import Path

# Directories and patterns to exclude from the archive
EXCLUDE_PATTERNS = {
    "*-workspace",
    "__pycache__",
    "*.pyc",
    ".DS_Store",
    "description_eval.json",
    "feedback.json",
    "review.html",
}


def should_exclude(path):
    """Check if a path should be excluded from the archive."""
    name = Path(path).name
    for pattern in EXCLUDE_PATTERNS:
        if pattern.startswith("*") and name.endswith(pattern[1:]):
            return True
        if pattern.endswith("*") and name.startswith(pattern[:-1]):
            return True
        if name == pattern:
            return True
    return False


def package_skill(skill_dir, output_path=None):
    """Create a .tar.gz archive of the skill directory."""
    skill_dir = Path(skill_dir).resolve()
    if not skill_dir.exists():
        print(f"Error: {skill_dir} not found", file=sys.stderr)
        sys.exit(1)

    skill_md = skill_dir / "SKILL.md"
    if not skill_md.exists():
        print(f"Error: No SKILL.md found in {skill_dir}", file=sys.stderr)
        sys.exit(1)

    slug = skill_dir.name
    if output_path is None:
        output_path = skill_dir.parent / f"{slug}.tar.gz"
    else:
        output_path = Path(output_path)

    file_count = 0
    with tarfile.open(output_path, "w:gz") as tar:
        for root, dirs, files in os.walk(skill_dir):
            # Filter out excluded directories
            dirs[:] = [d for d in dirs if not should_exclude(d)]

            for f in files:
                filepath = Path(root) / f
                if should_exclude(filepath):
                    continue

                arcname = str(filepath.relative_to(skill_dir.parent))
                tar.add(filepath, arcname=arcname)
                file_count += 1

    size_kb = output_path.stat().st_size / 1024
    print(f"Packaged {file_count} files into {output_path} ({size_kb:.1f} KB)")
    return str(output_path)


def main():
    parser = argparse.ArgumentParser(description="Package a skill for distribution")
    parser.add_argument("skill_dir", help="Path to skill directory")
    parser.add_argument("--output", "-o", help="Output archive path")
    args = parser.parse_args()

    package_skill(args.skill_dir, args.output)


if __name__ == "__main__":
    main()
