name: Update marketplace index

on:
  push:
    branches: [main]
    paths:
      - 'skills/**'

jobs:
  update-index:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Regenerate index.json
        run: |
          python3 << 'EOF'
          import os, json, re
          from datetime import datetime, timezone
          from collections import Counter

          skills_dir = "skills"
          skills = []
          subdomain_counts = Counter()
          tag_counter = Counter()

          for skill_name in sorted(os.listdir(skills_dir)):
              skill_md = os.path.join(skills_dir, skill_name, "SKILL.md")
              if not os.path.isfile(skill_md):
                  continue
              with open(skill_md, "r", encoding="utf-8") as f:
                  content = f.read()
              fm_match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)
              if not fm_match:
                  continue
              fm = fm_match.group(1)
              def get_field(field, text):
                  m = re.search(rf"^{field}:\s*(.+)$", text, re.MULTILINE)
                  return m.group(1).strip().strip('"') if m else ""
              def get_tags(text):
                  m = re.search(r"^tags:\s*\[(.+)\]", text, re.MULTILINE)
                  return [t.strip() for t in m.group(1).split(",")] if m else []

              tags = get_tags(fm)
              subdomain = get_field("subdomain", fm)
              subdomain_counts[subdomain] += 1
              for t in tags:
                  tag_counter[t] += 1

              skills.append({
                  "name": get_field("name", fm),
                  "description": get_field("description", fm),
                  "domain": "cybersecurity",
                  "subdomain": subdomain,
                  "tags": tags,
                  "version": get_field("version", fm) or "1.0",
                  "author": "mukul975",
                  "license": "Apache-2.0",
                  "path": f"skills/{skill_name}"
              })

          top_tags = sorted(tag_counter.items(), key=lambda x: -x[1])[:20]
          index = {
              "version": "1.0.0",
              "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
              "repository": "https://github.com/mukul975/Anthropic-Cybersecurity-Skills",
              "total_skills": len(skills),
              "total_domains": 1,
              "total_subdomains": len(subdomain_counts),
              "domain_stats": {"cybersecurity": len(skills)},
              "subdomain_stats": dict(subdomain_counts),
              "top_tags": [{"tag": t, "count": c} for t, c in top_tags],
              "skills": skills
          }

          with open("index.json", "w", encoding="utf-8") as f:
              json.dump(index, f, indent=2)

          print(f"Updated index.json: {len(skills)} skills, {len(subdomain_counts)} subdomains")
          EOF

      - name: Commit updated index
        run: |
          git config user.name "mukul975"
          git config user.email "mukul975@users.noreply.github.com"
          git add index.json
          git diff --staged --quiet || git commit -m "chore: auto-update index.json"
          git push
