#!/usr/bin/env python3
"""
Genesis Meta-Prompt Generator
==============================
Prompts that write prompts. Meta-agentics foundation.

"Every codebase must have meta-agentics" - IndyDevDan

Usage:
    python meta_prompts.py generate question "database queries"
    python meta_prompts.py generate expert "websocket handling"
    python meta_prompts.py generate skill "code review"
    python meta_prompts.py list
"""

import sys
import json
from datetime import datetime
from pathlib import Path
from typing import Dict, Any


# Meta-Prompt Templates
TEMPLATES = {
    "question": {
        "description": "Generate a question prompt for a specific domain",
        "template": '''# {domain} Question Prompt

## Purpose
Answer questions about {domain} using expertise file as mental model.

## Variables
- `question`: The user's question about {domain}

## Workflow
1. Read expertise file: expertise/{domain_slug}/expertise.yaml
2. Validate understanding against actual codebase
3. Answer question with validated knowledge

## Prompt
```
You are a {domain} expert for the Genesis system.

First, read the expertise file to load your mental model:
- expertise/{domain_slug}/expertise.yaml

Then validate your understanding by checking the actual code.
The code is always the source of truth.

Now answer this question: {{question}}

Be concise. Reference specific files and line numbers when relevant.
```
''',
    },

    "expert": {
        "description": "Generate an expert agent prompt for a domain",
        "template": '''# {domain} Expert Agent

## Purpose
Act as domain expert for {domain}, maintaining expertise through self-improvement.

## Expertise File
Location: expertise/{domain_slug}/expertise.yaml

## Capabilities
- Answer questions about {domain}
- Make changes to {domain} code
- Self-improve expertise after actions

## Three-Step Workflow

### Step 1: Plan
```
Analyze the task related to {domain}.
Read expertise file first.
Create a detailed plan.
```

### Step 2: Build
```
Execute the plan.
Make changes to codebase.
Validate changes work.
```

### Step 3: Self-Improve
```
What changed in the codebase?
Update expertise file with:
- New patterns discovered
- Files modified
- Lessons learned
```

## Key Principle
> "One executes and forgets, the other executes and learns."

This expert LEARNS from every action.
''',
    },

    "skill": {
        "description": "Generate a Claude Code skill definition",
        "template": '''---
name: genesis-{domain_slug}
description: {domain} capabilities for Genesis. Use when tasks involve {domain}.
---

# Genesis {domain} Skill

## When to Use
Activate this skill when the task involves:
- {domain} operations
- {domain} analysis
- {domain} improvements

## Expertise Location
Load mental model from: expertise/{domain_slug}/expertise.yaml

## Workflow

1. **Load Context**
   - Read expertise file
   - Check recent changes in domain

2. **Execute Task**
   - Apply domain knowledge
   - Follow established patterns
   - Validate against codebase

3. **Update Expertise**
   - Record new learnings
   - Update patterns
   - Increment version

## Key Files
- expertise/{domain_slug}/expertise.yaml
- expertise/{domain_slug}/self_improve.md

## Remember
The CODE is always the source of truth.
Expertise files are mental models, not documentation.
''',
    },

    "self_improve": {
        "description": "Generate a self-improvement prompt for a domain",
        "template": '''# {domain} Self-Improve Prompt

## Purpose
Sync {domain} expertise with current codebase state.

## Trigger
Run after any significant {domain} changes.

## Workflow

```
1. LOAD current expertise
   - Read expertise/{domain_slug}/expertise.yaml

2. SCAN for changes
   - Find files related to {domain}
   - Check git diff if available
   - Review recent commits

3. IDENTIFY updates needed
   - New files added
   - Patterns changed
   - Capabilities added/removed

4. UPDATE expertise
   - Modify expertise.yaml
   - Increment version
   - Record sync timestamp

5. LOG changes
   - Append to DEVLOG.md
   - Update knowledge graph
```

## Output
```yaml
sync_result:
  domain: "{domain}"
  timestamp: "{{timestamp}}"
  changes:
    - type: "..."
      description: "..."
  expertise_version: "X.Y"
```
''',
    },
}


def slugify(text: str) -> str:
    """Convert text to slug format."""
    return text.lower().replace(" ", "_").replace("-", "_")


def generate_prompt(template_type: str, domain: str) -> str:
    """Generate a prompt from template."""
    if template_type not in TEMPLATES:
        return f"Unknown template type: {template_type}"

    template = TEMPLATES[template_type]["template"]
    domain_slug = slugify(domain)

    return template.format(
        domain=domain,
        domain_slug=domain_slug,
    )


def save_prompt(template_type: str, domain: str, output_dir: str = None) -> str:
    """Generate and save a prompt."""
    content = generate_prompt(template_type, domain)
    domain_slug = slugify(domain)

    if output_dir is None:
        output_dir = f"/mnt/e/genesis-system/expertise/{domain_slug}"

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    filename = f"{template_type}_prompt.md"
    filepath = output_path / filename

    with open(filepath, 'w') as f:
        f.write(content)

    return str(filepath)


def list_templates() -> Dict[str, str]:
    """List available templates."""
    return {name: info["description"] for name, info in TEMPLATES.items()}


# CLI Interface
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("""
Genesis Meta-Prompt Generator
=============================

Commands:
  generate <type> <domain>    Generate a prompt
  save <type> <domain>        Generate and save to expertise dir
  list                        List available templates

Types:
  question      - Question prompt for domain expertise
  expert        - Full expert agent prompt
  skill         - Claude Code skill definition
  self_improve  - Self-improvement prompt

Examples:
  python meta_prompts.py generate question "database queries"
  python meta_prompts.py save expert "websocket handling"
  python meta_prompts.py list
        """)
        sys.exit(0)

    command = sys.argv[1]

    if command == "list":
        templates = list_templates()
        print("Available Templates:")
        for name, desc in templates.items():
            print(f"  {name}: {desc}")

    elif command == "generate" and len(sys.argv) >= 4:
        template_type = sys.argv[2]
        domain = sys.argv[3]
        print(generate_prompt(template_type, domain))

    elif command == "save" and len(sys.argv) >= 4:
        template_type = sys.argv[2]
        domain = sys.argv[3]
        filepath = save_prompt(template_type, domain)
        print(f"Saved to: {filepath}")

    else:
        print(f"Unknown command or missing arguments: {command}")
        sys.exit(1)
