#!/usr/bin/env python3
"""
Generate Claude plugin directories from registry bundles with mcp-hints.

Usage:
  python3 scripts/generate-plugins.py [--bundle knowledge-work-data] [--dry-run]
"""

from __future__ import annotations

import argparse
import json
import shutil
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BUNDLES_JSON = ROOT / "registry" / "bundles.json"
CURSOR_SKILLS = ROOT / ".cursor" / "skills"
PLUGINS_OUT = ROOT / "plugins"
MCP_TEMPLATES = ROOT / "mcp-templates"

PLUGIN_TO_UPSTREAM = {
    "knowledge-work-data": "data",
    "knowledge-work-engineering": "engineering",
    "knowledge-work-product-management": "product-management",
    "knowledge-work-productivity": "productivity",
    "knowledge-work-marketing": "marketing",
    "knowledge-work-sales": "sales",
    "knowledge-work-finance": "finance",
    "knowledge-work-legal": "legal",
    "knowledge-work-customer-support": "customer-support",
    "knowledge-work-bio-research": "bio-research",
    "knowledge-work-cowork-plugin-management": "cowork-plugin-management",
}


def load_bundles() -> list[dict]:
    data = json.loads(BUNDLES_JSON.read_text(encoding="utf-8"))
    return data.get("bundles", [])


def pick_mcp_template(bundle: dict) -> Path | None:
    hints = bundle.get("mcp-hints") or []
    hint_set = {h.lower() for h in hints}
    if hint_set & {"snowflake", "bigquery", "databricks", "hex"}:
        return MCP_TEMPLATES / "data-warehouse.json"
    if hint_set & {"github", "gitlab"}:
        return MCP_TEMPLATES / "source-control.json"
    if hint_set & {"linear", "jira", "asana", "notion"}:
        return MCP_TEMPLATES / "project-tracker.json"
    if hint_set & {"datadog", "pagerduty", "newrelic"}:
        return MCP_TEMPLATES / "monitoring.json"
    if hint_set & {"slack", "microsoft365"}:
        return MCP_TEMPLATES / "comms.json"
    return MCP_TEMPLATES / "data-warehouse.json" if hints else None


def write_connectors_md(dest: Path, bundle: dict) -> None:
    hints = bundle.get("mcp-hints") or []
    lines = [
        "# Connectors",
        "",
        f"Bundle: **{bundle.get('title', bundle['id'])}**",
        "",
        "Copy `.mcp.json.template` to `.mcp.json` and fill OAuth / URLs for your environment.",
        "",
        "## Suggested MCP servers",
        "",
    ]
    if hints:
        for h in hints:
            lines.append(f"- `{h}` — see [Anthropic knowledge-work-plugins](https://github.com/anthropics/knowledge-work-plugins)")
    else:
        lines.append("- No MCP hints for this bundle.")
    lines.append("")
    dest.write_text("\n".join(lines), encoding="utf-8")


def generate_plugin(bundle: dict, dry_run: bool) -> bool:
    if not bundle.get("mcp-hints") and not bundle["id"].startswith("knowledge-work-"):
        return False

    bundle_id = bundle["id"]
    out_dir = PLUGINS_OUT / bundle_id
    skills = bundle.get("skills") or []
    if bundle.get("domains") == ["knowledge-work"]:
        skills = [
            p.parent.relative_to(CURSOR_SKILLS).as_posix()
            for p in sorted(CURSOR_SKILLS.glob("knowledge-work/*/*/SKILL.md"))
        ]

    if not skills:
        print(f"Skip {bundle_id}: no skills", file=sys.stderr)
        return False

    plugin_json = {
        "name": bundle_id,
        "description": bundle.get("description", ""),
        "version": "1.0.0",
        "author": "awesome-agent-skill (adapted from anthropics/knowledge-work-plugins)",
    }

    if dry_run:
        print(f"[dry-run] {out_dir} ({len(skills)} skills)")
        return True

    if out_dir.exists():
        shutil.rmtree(out_dir)
    out_dir.mkdir(parents=True)
    (out_dir / ".claude-plugin").mkdir()
    (out_dir / ".claude-plugin" / "plugin.json").write_text(
        json.dumps(plugin_json, indent=2) + "\n", encoding="utf-8"
    )

    mcp_src = pick_mcp_template(bundle)
    if mcp_src and mcp_src.is_file():
        shutil.copy2(mcp_src, out_dir / ".mcp.json.template")
    else:
        (out_dir / ".mcp.json.template").write_text(
            json.dumps({"mcpServers": {}}, indent=2) + "\n",
            encoding="utf-8",
        )

    skills_dir = out_dir / "skills"
    skills_dir.mkdir()
    for sid in skills:
        src = CURSOR_SKILLS / sid / "SKILL.md"
        if not src.is_file():
            print(f"WARN missing {src}", file=sys.stderr)
            continue
        leaf = sid.split("/")[-1]
        dest_skill = skills_dir / leaf
        dest_skill.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dest_skill / "SKILL.md")

    write_connectors_md(out_dir / "CONNECTORS.md", bundle)
    upstream = PLUGIN_TO_UPSTREAM.get(bundle_id, "")
    readme = [
        f"# {bundle.get('title', bundle_id)}",
        "",
        bundle.get("description", ""),
        "",
        "Generated by `scripts/generate-plugins.py`. Skills sourced from `.cursor/skills/`.",
        "",
    ]
    if upstream:
        readme.append(
            f"Upstream reference: [anthropics/knowledge-work-plugins/{upstream}](https://github.com/anthropics/knowledge-work-plugins/tree/main/{upstream})"
        )
    (out_dir / "README.md").write_text("\n".join(readme) + "\n", encoding="utf-8")
    print(f"Wrote {out_dir} ({len(skills)} skills)")
    return True


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--bundle", action="append", default=[], help="Bundle id(s) to generate")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    bundles = load_bundles()
    targets = {b["id"]: b for b in bundles if b.get("mcp-hints") or b["id"].startswith("knowledge-work-")}

    if args.bundle:
        selected = [targets[bid] for bid in args.bundle if bid in targets]
    else:
        selected = list(targets.values())

    if not selected:
        print("No bundles with mcp-hints found", file=sys.stderr)
        return 1

    PLUGINS_OUT.mkdir(parents=True, exist_ok=True)
    count = sum(1 for b in selected if generate_plugin(b, args.dry_run))
    print(f"Generated {count} plugin(s)")
    return 0


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