#!/usr/bin/env python3
"""
Export OurDigital Skills for Claude.ai Projects

Generates simplified skill files suitable for uploading to Claude.ai.

Usage:
    python export_for_claude_ai.py              # Export all skills
    python export_for_claude_ai.py --bundle     # Generate bundle only
    python export_for_claude_ai.py --individual # Generate individual files only
"""

import os
import re
import argparse
from pathlib import Path
from typing import Optional

SCRIPT_DIR = Path(__file__).parent.parent
SKILLS_DIR = SCRIPT_DIR.parent
EXPORT_DIR = SCRIPT_DIR / "claude-ai-export"
INDIVIDUAL_DIR = EXPORT_DIR / "individual"

# (dir, name, desc, triggers)
SKILLS = [
    ("01-ourdigital-brand-guide", "Brand Guide", "brand standards and style",
     '"our brand guide", "our 브랜드 가이드", "our 톤앤매너"'),
    ("02-ourdigital-blog", "Blog", "Korean blog drafts",
     '"our blog", "our 블로그", "our 한국어 포스트"'),
    ("03-ourdigital-journal", "Journal", "English essays",
     '"our journal", "our English essay", "our 영문 에세이"'),
    ("04-ourdigital-research", "Research", "research prompts",
     '"our research", "our 리서치", "our deep research"'),
    ("05-ourdigital-document", "Document", "presentations",
     '"our document", "our 발표자료", "our presentation"'),
    ("06-ourdigital-designer", "Designer", "image prompts",
     '"our design", "our 썸네일", "our image prompt"'),
    ("07-ourdigital-ad-manager", "Ad Manager", "ad copywriting",
     '"our ad copy", "our 광고 카피", "our keyword"'),
    ("08-ourdigital-trainer", "Trainer", "training materials",
     '"our training", "our 워크샵", "our 교육"'),
    ("09-ourdigital-backoffice", "Backoffice", "business documents",
     '"our 견적서", "our proposal", "our quote"'),
    ("10-ourdigital-skill-creator", "Skill Creator", "creating new skills",
     '"our skill create", "our 스킬 만들기"'),
]


def extract_skill_content(skill_dir: str) -> Optional[str]:
    """Extract and simplify content from a skill's SKILL.md."""
    desktop_path = SKILLS_DIR / skill_dir / "desktop" / "SKILL.md"

    if not desktop_path.exists():
        print(f"  Warning: {desktop_path} not found")
        return None

    content = desktop_path.read_text()

    # Remove YAML frontmatter
    if content.startswith("---"):
        parts = content.split("---", 2)
        if len(parts) >= 3:
            content = parts[2].strip()

    # Extract key sections (first 150 lines or so)
    lines = content.split("\n")

    # Find main heading and take content
    simplified = []
    in_content = False
    line_count = 0
    max_lines = 120

    for line in lines:
        if line.startswith("# "):
            in_content = True

        if in_content:
            simplified.append(line)
            line_count += 1

            if line_count >= max_lines:
                simplified.append("\n[... see full documentation for more ...]")
                break

    return "\n".join(simplified)


def generate_individual_files():
    """Generate individual skill files for Claude.ai."""
    INDIVIDUAL_DIR.mkdir(parents=True, exist_ok=True)

    print("Generating individual skill files...")

    for skill_dir, name, desc, triggers in SKILLS:
        content = extract_skill_content(skill_dir)
        if content:
            # Create simplified header with YAML frontmatter
            num = skill_dir.split("-")[0]
            skill_name = name.lower().replace(' ', '-')
            filename = f"{num}-{skill_name}.md"

            header = f"""---
name: ourdigital-{skill_name}
description: |
  {desc.capitalize()}.
  Triggers (ourdigital or our prefix):
  - {triggers}
---

# OurDigital {name}

**Purpose**: {desc.capitalize()}
**Triggers**: Use "our" or "ourdigital" prefix

---

"""
            output_path = INDIVIDUAL_DIR / filename
            output_path.write_text(header + content)
            print(f"  Created: {filename}")


def generate_bundle():
    """Generate combined bundle file."""
    print("Generating bundle file...")

    # Read existing bundle (already created manually with full content)
    bundle_path = EXPORT_DIR / "ourdigital-skills-bundle.md"
    if bundle_path.exists():
        print(f"  Bundle exists: {bundle_path}")
    else:
        print(f"  Warning: Bundle not found at {bundle_path}")


def main():
    parser = argparse.ArgumentParser(description="Export skills for Claude.ai")
    parser.add_argument("--bundle", action="store_true", help="Generate bundle only")
    parser.add_argument("--individual", action="store_true", help="Generate individual files only")
    args = parser.parse_args()

    print(f"Export directory: {EXPORT_DIR}\n")

    if args.bundle:
        generate_bundle()
    elif args.individual:
        generate_individual_files()
    else:
        generate_bundle()
        generate_individual_files()

    print("\nDone! Files ready for upload to Claude.ai Projects.")
    print(f"  Bundle: {EXPORT_DIR / 'ourdigital-skills-bundle.md'}")
    print(f"  Individual: {INDIVIDUAL_DIR}/")


if __name__ == "__main__":
    main()
