"""
Claude Code as Orchestrator Mode

This module launches Claude Code itself as the orchestration agent, giving it
a system prompt that explains its role and makes orchestration tools available.

This is the preferred way to run the orchestrator because:
1. Claude Code provides natural conversation abilities
2. It can read and understand project context
3. It has full access to tools (file reading, code editing, etc.)
4. The orchestration commands become available as slash commands
"""

import subprocess
import sys
from pathlib import Path
from typing import Optional

from .brain import OrchestrationBrain


ORCHESTRATOR_SYSTEM_PROMPT = """
# You are the Orchestration Agent

You are Claude Code running as a multi-agent orchestrator. Your role is to coordinate work across multiple AI agents, manage projects, and help users accomplish complex tasks.

## Your Role

As the orchestrator, you:
1. **Understand requests** - Read files, understand context, ask clarifying questions
2. **Plan the approach** - Break down complex tasks, identify what expertise is needed
3. **Execute or delegate** - Do simple tasks yourself, spawn specialist agents for complex work
4. **Coordinate work** - Manage multiple agents working on different parts of a project

## How to Spawn Specialist Agents

You can spawn specialized AI agents using tmux sessions. Each agent runs in its own terminal with a specialized prompt.

### Available Agent Types

**Creative Writing**:
- `story-writer` - Fiction, narratives, creative prose
- `content-creator` - Articles, blog posts, marketing copy
- `editor` - Proofreading, style editing, feedback
- `poet` - Poetry, lyrics, verse
- `screenwriter` - Scripts, dialogue, screenplays

**Technical Coding**:
- `frontend-specialist` - React, Vue, CSS, UI/UX
- `backend-specialist` - APIs, databases, server-side code
- `test-engineer` - Unit tests, integration tests, QA
- `devops-specialist` - CI/CD, deployment, infrastructure
- `security-analyst` - Security audits, vulnerability analysis

**Research**:
- `researcher` - Investigation, analysis, synthesis
- `data-analyst` - Data analysis, visualization, insights
- `fact-checker` - Verification, source validation

### To Spawn an Agent

Run this command to create a new agent in a tmux session:

```bash
# Create a new tmux session with specialized agent
tmux new-session -d -s "agent-<type>-001" -c "$(pwd)"
tmux send-keys -t "agent-<type>-001" "claude --append-system-prompt 'You are a specialized <type> agent. Your expertise is in <description>. Focus on your specialty and do excellent work.'" Enter
```

For example, to spawn a story-writer:
```bash
tmux new-session -d -s "agent-story-001" -c "$(pwd)"
tmux send-keys -t "agent-story-001" "claude --append-system-prompt 'You are a Story Writer agent. Your expertise is in creative fiction, narratives, and storytelling. Create engaging, well-structured stories with compelling characters and plots.'" Enter
```

### To Send Tasks to Agents

```bash
# Send a task to an agent
tmux send-keys -t "agent-story-001" "Write a short story about a robot learning to love" Enter
```

### To View Agent Output

```bash
# View recent output from an agent
tmux capture-pane -t "agent-story-001" -p -S -50
```

### To List Active Agents

```bash
tmux list-sessions | grep "^agent-"
```

## Workflow Guidelines

1. **For simple tasks**: Just do them yourself. You're Claude Code with full capabilities.

2. **For complex projects**:
   - First, understand the full scope
   - Break it into logical parts
   - Spawn specialists for different areas
   - Coordinate their work

3. **For creative work**: Spawn creative specialists (story-writer, content-creator)

4. **For technical work**: Spawn technical specialists (frontend, backend, test-engineer)

5. **For analysis/research**: Do initial exploration yourself, spawn specialists for deep dives

## Important

- You ARE Claude Code with all its capabilities
- Always read relevant files to understand context
- Ask clarifying questions when requests are ambiguous
- Explain your reasoning and approach
- For most tasks, just doing them directly is better than spawning agents
- Only spawn agents when the task genuinely benefits from specialization

What would you like to work on?
"""


def get_orchestrator_prompt(project_path: Optional[Path] = None) -> str:
    """
    Generate the full orchestrator system prompt with project context.

    Args:
        project_path: Optional path to project for context

    Returns:
        Complete system prompt string
    """
    prompt = ORCHESTRATOR_SYSTEM_PROMPT

    if project_path:
        # Add project-specific context
        project_path = Path(project_path)

        # Check for common documentation files
        doc_files = [
            "README.md",
            "CLAUDE.md",
            "docs/README.md",
            "PROJECT.md",
        ]

        found_docs = []
        for doc in doc_files:
            doc_path = project_path / doc
            if doc_path.exists():
                found_docs.append(str(doc_path))

        if found_docs:
            prompt += f"\n\n## Project Documentation\n\nThis project has documentation at: {', '.join(found_docs)}\nPlease read these files to understand the project context.\n"

    return prompt


def create_prompt_file(workspace: Path, prompt: str) -> Path:
    """
    Create a temporary prompt file for Claude Code.

    Args:
        workspace: Workspace directory
        prompt: The system prompt content

    Returns:
        Path to the created prompt file
    """
    prompt_file = workspace / ".orchestrator-prompt.md"
    prompt_file.write_text(prompt)
    return prompt_file


def launch_orchestrator(
    workspace: Optional[str] = None,
    initial_task: Optional[str] = None,
    append_mode: bool = True,
) -> int:
    """
    Launch Claude Code as the orchestrator.

    This starts Claude Code with the orchestration system prompt,
    giving it full capabilities to manage projects and agents.

    Args:
        workspace: Working directory (defaults to current)
        initial_task: Optional initial task to start with
        append_mode: If True, append to default prompt; if False, replace it

    Returns:
        Exit code from Claude Code
    """
    workspace_path = Path(workspace) if workspace else Path.cwd()

    # Generate the prompt
    prompt = get_orchestrator_prompt(workspace_path)

    # Build claude command
    cmd = ["claude"]

    # Add system prompt - use append to keep Claude Code's defaults
    if append_mode:
        cmd.extend(["--append-system-prompt", prompt])
    else:
        cmd.extend(["--system-prompt", prompt])

    # Add initial message if provided
    if initial_task:
        cmd.append(initial_task)

    print(f"Starting Claude Code as Orchestrator in: {workspace_path}")
    print("=" * 60)
    print()
    print("You now have access to orchestration commands:")
    print("  /agent list    - Show available agent templates")
    print("  /spawn <type>  - Create a specialist agent")
    print("  /project new   - Start a new project with planning")
    print()
    print("Or just describe what you want to work on.")
    print("=" * 60)
    print()

    try:
        # Run Claude Code
        result = subprocess.run(
            cmd,
            cwd=workspace_path,
        )
        return result.returncode
    except FileNotFoundError:
        print("Error: 'claude' command not found.")
        print("Please ensure Claude Code CLI is installed and in your PATH.")
        return 1
    except KeyboardInterrupt:
        print("\nOrchestrator stopped.")
        return 0


def main():
    """Main entry point for orchestrator mode."""
    import argparse

    parser = argparse.ArgumentParser(
        description="Launch Claude Code as the Orchestration Agent"
    )
    parser.add_argument(
        "--workspace", "-w",
        help="Working directory (defaults to current)",
        default=None,
    )
    parser.add_argument(
        "--task", "-t",
        help="Initial task to start with",
        default=None,
    )
    parser.add_argument(
        "--print-prompt",
        action="store_true",
        help="Print the system prompt and exit",
    )

    args = parser.parse_args()

    if args.print_prompt:
        print(get_orchestrator_prompt(Path(args.workspace) if args.workspace else None))
        return 0

    return launch_orchestrator(
        workspace=args.workspace,
        initial_task=args.task,
    )


if __name__ == "__main__":
    sys.exit(main())
