#!/usr/bin/env python3
"""
Generate Skill - Create a complete skill folder from source analysis.

Part of the genesis-architect skill.

Usage:
    python generate_skill.py <skill_name> <source_file> [--output-dir path]

Arguments:
    skill_name      Name for the new skill (kebab-case)
    source_file     Source document to extract skill from
    --output-dir    Output directory (default: .claude/skills/)

Examples:
    python generate_skill.py piter-framework INDYDEVDAN_AGENTIC_MASTERY.md
    python generate_skill.py prompt-chains docs/chains.md --output-dir ./skills

Output:
    Complete skill folder with:
    - SKILL.md (with YAML frontmatter)
    - scripts/ (if deterministic operations found)
    - references/ (extracted detailed content)
"""

import argparse
import json
import os
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    parser.add_argument(
        "skill_name",
        type=str,
        help="Name for the new skill (kebab-case)"
    )

    parser.add_argument(
        "source_file",
        type=str,
        help="Source document to extract from"
    )

    parser.add_argument(
        "--output-dir",
        type=str,
        default=".claude/skills",
        help="Output directory for skills"
    )

    parser.add_argument(
        "--section",
        type=str,
        default=None,
        help="Specific section to extract (by heading text)"
    )

    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Show what would be created without creating"
    )

    return parser.parse_args()


def to_title_case(kebab_name: str) -> str:
    """Convert kebab-case to Title Case."""
    words = kebab_name.split('-')
    return ' '.join(word.capitalize() for word in words)


def extract_section(content: str, section_heading: str) -> Optional[str]:
    """Extract a specific section from markdown content."""
    lines = content.split('\n')
    in_section = False
    section_level = 0
    section_lines = []

    for line in lines:
        # Check for heading
        match = re.match(r'^(#{1,6})\s+(.+)$', line)

        if match:
            level = len(match.group(1))
            title = match.group(2).strip()

            if section_heading.lower() in title.lower():
                in_section = True
                section_level = level
                section_lines.append(line)
                continue

            if in_section and level <= section_level:
                # End of section
                break

        if in_section:
            section_lines.append(line)

    return '\n'.join(section_lines) if section_lines else None


def extract_code_blocks(content: str) -> List[Dict]:
    """Extract code blocks with their language."""
    blocks = []
    pattern = r'```(\w*)\n(.*?)```'

    for match in re.finditer(pattern, content, re.DOTALL):
        language = match.group(1) or 'text'
        code = match.group(2).strip()
        blocks.append({
            "language": language,
            "code": code,
            "lines": len(code.split('\n'))
        })

    return blocks


def generate_triggers(skill_name: str, content: str) -> List[str]:
    """Generate trigger phrases for the skill."""
    title = to_title_case(skill_name)

    triggers = [
        f"Use the {title} approach",
        f"Apply {title} pattern",
        f"Implement {skill_name}",
        f"How does {title} work",
        f"Run {skill_name} workflow"
    ]

    # Extract action verbs from content
    action_words = ['create', 'build', 'generate', 'analyze', 'process', 'execute']
    for word in action_words:
        if word in content.lower():
            triggers.append(f"{word.capitalize()} using {title}")
            break

    return triggers[:5]  # Return top 5


def generate_skill_md(
    skill_name: str,
    content: str,
    triggers: List[str]
) -> str:
    """Generate SKILL.md content."""
    title = to_title_case(skill_name)

    # Extract first paragraph as purpose
    paragraphs = re.split(r'\n\n+', content)
    purpose = ""
    for para in paragraphs:
        if not para.startswith('#') and len(para) > 50:
            purpose = para[:300].replace('\n', ' ').strip()
            if len(para) > 300:
                purpose += "..."
            break

    if not purpose:
        purpose = f"Implements the {title} pattern for Genesis workflows."

    # Build SKILL.md
    skill_md = f'''---
name: {title}
description: |
  {purpose}

  WHEN TO USE:
'''

    for trigger in triggers:
        skill_md += f'  - "{trigger}"\n'

    skill_md += '''
  CAPABILITIES:
  - Follow structured process
  - Apply pattern consistently
  - Provide step-by-step guidance

allowed-tools:
  - Read
  - Write
  - Bash
---

'''

    skill_md += f"# {title}\n\n"
    skill_md += "## Purpose\n\n"
    skill_md += f"{purpose}\n\n"
    skill_md += "## Instructions\n\n"

    # Extract headings as instruction steps
    headings = re.findall(r'^##\s+(.+)$', content, re.MULTILINE)
    for i, heading in enumerate(headings[:5], 1):
        skill_md += f"### Step {i}: {heading}\n\n"
        skill_md += f"Follow the {heading.lower()} process as documented.\n\n"

    skill_md += "## References\n\n"
    skill_md += "See `references/` folder for detailed documentation.\n"

    return skill_md


def create_skill_folder(
    skill_name: str,
    output_dir: str,
    skill_md: str,
    reference_content: str,
    dry_run: bool = False
) -> Dict:
    """Create the complete skill folder structure."""
    skill_path = Path(output_dir) / skill_name
    files_created = []

    if dry_run:
        print(f"Would create: {skill_path}/")
        print(f"Would create: {skill_path}/SKILL.md")
        print(f"Would create: {skill_path}/references/")
        print(f"Would create: {skill_path}/references/full_documentation.md")
        return {"status": "dry_run", "path": str(skill_path)}

    # Create directories
    (skill_path / "references").mkdir(parents=True, exist_ok=True)
    (skill_path / "scripts").mkdir(exist_ok=True)

    # Write SKILL.md
    (skill_path / "SKILL.md").write_text(skill_md)
    files_created.append(str(skill_path / "SKILL.md"))

    # Write reference content
    ref_path = skill_path / "references" / "full_documentation.md"
    ref_path.write_text(reference_content)
    files_created.append(str(ref_path))

    # Create placeholder script
    script_content = f'''#!/usr/bin/env python3
"""
{to_title_case(skill_name)} - Helper script

Usage:
    python {skill_name.replace('-', '_')}.py [args]
"""

def main():
    print("Skill script placeholder - implement as needed")

if __name__ == "__main__":
    main()
'''
    script_path = skill_path / "scripts" / f"{skill_name.replace('-', '_')}.py"
    script_path.write_text(script_content)
    files_created.append(str(script_path))

    return {
        "status": "created",
        "path": str(skill_path),
        "files": files_created
    }


def main():
    """Main entry point."""
    args = parse_args()

    try:
        # Read source file
        source_path = Path(args.source_file)
        if not source_path.exists():
            print(f"Error: Source file not found - {args.source_file}", file=sys.stderr)
            sys.exit(1)

        content = source_path.read_text(encoding='utf-8')

        # Extract specific section if requested
        if args.section:
            section_content = extract_section(content, args.section)
            if not section_content:
                print(f"Error: Section '{args.section}' not found", file=sys.stderr)
                sys.exit(1)
            content = section_content

        # Generate components
        triggers = generate_triggers(args.skill_name, content)
        skill_md = generate_skill_md(args.skill_name, content, triggers)

        # Create skill folder
        result = create_skill_folder(
            skill_name=args.skill_name,
            output_dir=args.output_dir,
            skill_md=skill_md,
            reference_content=content,
            dry_run=args.dry_run
        )

        # Output result
        print(json.dumps(result, indent=2))

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
