"""Tyler init command - scaffold new agent projects"""
import os
import click
from pathlib import Path
from typing import Optional
import textwrap

def create_project_structure(project_name: str, path: Optional[str] = None) -> Path:
    """Create the project directory structure"""
    if path:
        project_path = Path(path) / project_name
    else:
        project_path = Path.cwd() / project_name
    
    # Create directories
    project_path.mkdir(parents=True, exist_ok=True)
    (project_path / "tools").mkdir(exist_ok=True)
    
    return project_path

def create_env_example(project_path: Path) -> None:
    """Create .env.example file"""
    content = """# API Keys
# Choose one of these providers and add your API key:

# OpenAI
OPENAI_API_KEY=your-openai-key-here

# Anthropic
ANTHROPIC_API_KEY=your-anthropic-key-here

# Google
GOOGLE_API_KEY=your-google-key-here

# Optional: Weights & Biases for observability
WANDB_API_KEY=your-wandb-key-here
"""
    (project_path / ".env.example").write_text(content)

def create_gitignore(project_path: Path) -> None:
    """Create .gitignore file"""
    content = """.env
__pycache__/
*.pyc
.coverage
.pytest_cache/
*.egg-info/
dist/
build/
.DS_Store
"""
    (project_path / ".gitignore").write_text(content)

def create_pyproject_toml(project_path: Path, project_name: str) -> None:
    """Create pyproject.toml file"""
    content = f"""[project]
name = "{project_name}"
version = "0.1.0"
description = "A Tyler agent for {project_name}"
requires-python = ">=3.11"
dependencies = [
    "slide-tyler>=2.0.0",
    "python-dotenv>=1.0.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0.0",
    "pytest-asyncio>=0.20.0",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
"""
    (project_path / "pyproject.toml").write_text(content)

def create_agent_py(project_path: Path, project_name: str, purpose: str) -> None:
    """Create the main agent.py file"""
    agent_name = project_name.replace("-", "_").replace(" ", "_")
    
    content = f'''"""
{project_name} - A Tyler agent
Generated by tyler init
"""
from dotenv import load_dotenv
load_dotenv()

import asyncio
from tyler import Agent, Thread, Message
from lye import WEB_TOOLS, FILES_TOOLS, IMAGE_TOOLS

# Import custom tools if any
# from tools import MY_CUSTOM_TOOLS

async def main():
    # Configure your agent
    agent = Agent(
        name="{agent_name}",
        model_name="gpt-4o",  # Or your preferred model
        purpose="{purpose}",
        tools=[
            # Add tool groups as needed
            *WEB_TOOLS,     # Web search and browsing
            *FILES_TOOLS,   # File operations
            # *IMAGE_TOOLS,   # Image analysis
            # *MY_CUSTOM_TOOLS,  # Your custom tools
        ],
        notes="""
        - Be helpful and thorough
        - Ask clarifying questions when needed
        - Provide sources when using web tools
        """
    )
    
    # Create a thread and run a test
    thread = Thread()
    thread.add_message(Message(
        role="user", 
        content="Hello! What can you help me with?"
    ))
    
    print("🤖 Testing agent...")
    processed_thread, new_messages = await agent.go(thread)
    
    for msg in new_messages:
        if msg.role == "assistant":
            print(f"\\n💬 {{msg.content}}")

if __name__ == "__main__":
    asyncio.run(main())
'''
    (project_path / "agent.py").write_text(content)

def create_tyler_config(project_path: Path, project_name: str, purpose: str) -> None:
    """Create tyler-config.yaml for the chat interface"""
    agent_name = project_name.replace("-", "_").replace(" ", "_")
    
    content = f"""# Tyler Chat Configuration
name: "{agent_name}"
purpose: "{purpose}"
model_name: "gpt-4o"  # Or your preferred model

# Tool Configuration
tools:
  - "web"      # Web search and browsing
  - "files"    # File operations
  # - "image"    # Image processing
  # - "slack"    # Slack integration
  # - "command_line"  # System commands
  
  # Custom tool files
  # - "./tools/custom_tool.py"

# Model Parameters
temperature: 0.7
max_tool_iterations: 10

# Optional notes for the agent
notes: |
  - Be helpful and thorough
  - Ask clarifying questions when needed
  - Provide sources when using web tools
"""
    (project_path / "tyler-config.yaml").write_text(content)

def create_readme(project_path: Path, project_name: str) -> None:
    """Create README.md file"""
    content = f"""# {project_name}

A Tyler agent project.

## Setup

1. Install dependencies:
   ```bash
   uv venv
   uv pip install -e .
   ```

2. Set up your API keys:
   ```bash
   cp .env.example .env
   # Edit .env with your actual API keys
   ```

## Usage

### Run the agent programmatically:
```bash
uv run python agent.py
```

### Chat with your agent:
```bash
tyler chat --config tyler-config.yaml
```

## Adding Custom Tools

1. Create your tool in the `tools/` directory
2. Import it in `agent.py`
3. Add it to the agent's tools list

See the [Tyler documentation](https://docs.slide.so) for more information.
"""
    (project_path / "README.md").write_text(content)

def create_tools_init(project_path: Path) -> None:
    """Create tools/__init__.py with example"""
    content = '''"""Custom tools for your agent"""

# Example custom tool:
def example_tool(*, query: str) -> str:
    """An example custom tool.
    
    Args:
        query: The input query
        
    Returns:
        A helpful response
    """
    return f"You asked: {query}"

# Export your tools
MY_CUSTOM_TOOLS = [
    {
        "definition": {
            "type": "function",
            "function": {
                "name": "example_tool",
                "description": "An example custom tool",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "The input query"
                        }
                    },
                    "required": ["query"]
                }
            }
        },
        "implementation": example_tool
    }
]
'''
    (project_path / "tools" / "__init__.py").write_text(content)

@click.command()
@click.argument('project_name')
@click.option('--path', '-p', help='Path to create project in (defaults to current directory)')
@click.option('--purpose', help='Purpose of the agent', default="To be a helpful AI assistant")
def init(project_name: str, path: Optional[str], purpose: str):
    """Initialize a new Tyler agent project.
    
    Example:
        tyler init my-research-agent
        tyler init "Customer Support Bot" --purpose "To help customers with product questions"
    """
    try:
        # Sanitize project name for use as directory
        safe_name = project_name.lower().replace(" ", "-")
        
        click.echo(f"🚀 Creating new Tyler agent project: {safe_name}")
        
        # Create project structure
        project_path = create_project_structure(safe_name, path)
        
        # Create files
        create_env_example(project_path)
        create_gitignore(project_path)
        create_pyproject_toml(project_path, project_name)
        create_agent_py(project_path, project_name, purpose)
        create_tyler_config(project_path, project_name, purpose)
        create_readme(project_path, project_name)
        create_tools_init(project_path)
        
        # Success message
        click.echo(f"✅ Created project structure in {project_path}")
        click.echo("\n📝 Next steps:")
        click.echo(f"  1. cd {safe_name}")
        click.echo("  2. cp .env.example .env")
        click.echo("  3. Add your API keys to .env")
        click.echo("  4. tyler chat --config tyler-config.yaml")
        
    except Exception as e:
        click.echo(f"❌ Error creating project: {e}", err=True)
        raise click.Abort()

# CLI command that will be imported by main.py
cli = init
