import os
import re
from pathlib import Path
from typing import Dict, List, Optional

# Constants
REPO_ROOT = Path(__file__).parent.parent.parent.parent
EXTERNAL_DIR = REPO_ROOT / "packages/external"
OUTPUT_FILE = REPO_ROOT / "docs/CONTEXT7_SKILL_LIBRARY.md"

SKILL_DIRS = [
    EXTERNAL_DIR / "antigravity-awesome-skills/skills",
    EXTERNAL_DIR / "claude-code-settings/skills",
]

# Category Keywords for Auto-Classification
CATEGORIES = {
    "🛸 Autonomous": ["autonomous", "subagent", "parallel", "loki"],
    "🛠️ Development": [
        "develop",
        "frontend",
        "backend",
        "react",
        "typescript",
        "javascript",
        "code",
        "debug",
        "refactor",
        "architect",
        "api",
        "bun",
        "guide",
    ],
    "🎨 Creative & Design": ["design", "ui", "ux", "art", "canvas", "css", "theme", "visual", "d3"],
    "🤖 AI & LLM": [
        "llm",
        "agent",
        "prompt",
        "mcp",
        "ai",
        "claude",
        "gemini",
        "codex",
        "model",
        "notebooklm",
    ],
    "📄 Documentation": ["doc", "pdf", "docx", "pptx", "xlsx", "writing", "internal comms"],
    "📈 Product & Strategy": ["product", "manager", "strategy", "aso", "brainstorm", "plan"],
    "🏗️ Infrastructure & Git": [
        "git",
        "linux",
        "shell",
        "workflow",
        "docker",
        "infra",
        "aws",
        "cloud",
        "network",
    ],
    "🧪 QA & Testing": ["test", "qa", "debug", "playwright", "fix"],
    "🛡️ Cybersecurity": [
        "hack",
        "pentest",
        "exploit",
        "security",
        "vulnerability",
        "injection",
        "wireshark",
        "shodan",
        "owasp",
        "burp",
        "metasploit",
        "privilege",
        "reconnaissance",
    ],
    "🔄 Workflow & Optimization": [
        "workflow",
        "kaizen",
        "poka-yoke",
        "review",
        "jit",
        "kiro",
        "spec",
    ],
}

DEFAULT_CATEGORY = "🧩 Uncategorized"


def parse_skill_md(file_path: Path) -> dict:
    """Parses SKILL.md to extract name and description."""
    content = file_path.read_text(encoding="utf-8")

    # Extract Frontmatter
    frontmatter_match = re.search(r"^---\n(.*?)\n---", content, re.DOTALL)
    data = {"path": str(file_path.parent.relative_to(REPO_ROOT)), "id": file_path.parent.name}

    if frontmatter_match:
        fm = frontmatter_match.group(1)
        name_match = re.search(r"name:\s*(.+)", fm)
        desc_match = re.search(r"description:\s*(.+)", fm, re.IGNORECASE)

        if name_match:
            data["name"] = name_match.group(1).strip()
        if desc_match:
            data["description"] = desc_match.group(1).strip()

    if "name" not in data:
        data["name"] = data["id"]
    if "description" not in data:
        # Fallback: finding first paragraph
        lines = [l for l in content.split("\n") if l.strip() and not l.startswith(("#", "-", ">"))]
        if lines:
            data["description"] = lines[0][:100] + "..."
        else:
            data["description"] = "No description provided."

    return data


def classify_skill(skill: dict) -> str:
    """Classifies skill based on name and description keywords."""
    text = (skill["name"] + " " + skill["description"]).lower()

    for category, keywords in CATEGORIES.items():
        if any(k in text for k in keywords):
            return category

    return DEFAULT_CATEGORY


def main() -> None:
    print("🔍 Indexing Skills for Context7...")
    skills = []

    for skills_dir in SKILL_DIRS:
        if not skills_dir.exists():
            print(f"⚠️ Directory not found: {skills_dir}")
            continue

        for item in skills_dir.iterdir():
            if item.is_dir():
                skill_md = item / "SKILL.md"
                if skill_md.exists():
                    skill_data = parse_skill_md(skill_md)
                    skill_data["category"] = classify_skill(skill_data)
                    skills.append(skill_data)

    # Sort by Category then Name
    skills.sort(key=lambda x: (x["category"], x["name"]))

    # Generate Markdown
    md_content = "# 🌌 Context7 Skill Library Index\n\n"
    md_content += f"> **Total Skills Indexed:** {len(skills)}\n"
    md_content += "> **Generated by:** Antigravity Indexer\n\n"

    current_cat = ""
    for skill in skills:
        if skill["category"] != current_cat:
            current_cat = skill["category"]
            md_content += f"\n## {current_cat}\n\n"
            md_content += "| Skill Name | Description | Path |\n"
            md_content += "| :--- | :--- | :--- |\n"

        # Clean description for table
        desc = skill["description"].replace("|", "-").replace("\n", " ")
        if len(desc) > 80:
            desc = desc[:77] + "..."

        link_path = skill["path"]
        md_content += (
            f"| **{skill['name']}** | {desc} | [`{skill['id']}`]({link_path}/SKILL.md) |\n"
        )

    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT_FILE.write_text(md_content, encoding="utf-8")
    print(f"✅ Context7 Index saved to: {OUTPUT_FILE}")


if __name__ == "__main__":
    main()
