"""Template Starters for Empathy Framework

Scaffold new projects with Empathy pre-configured for different use cases.

Supported templates:
- python-fastapi: FastAPI web service with Empathy integration
- python-cli: Command-line tool with Empathy
- python-agent: AI agent toolkit project
- minimal: Minimal Empathy setup (just config files)

Copyright 2025 Smart-AI-Memory
Licensed under Fair Source License 0.9
"""

from pathlib import Path
from typing import Any

from attune.config import _validate_file_path

# Template definitions
TEMPLATES: dict[str, dict[str, Any]] = {
    "minimal": {
        "name": "Minimal",
        "description": "Just the Empathy config files - add to existing project",
        "files": {
            "attune.config.yml": """# Empathy Framework Configuration
# Generated by: empathy new minimal

user_id: "{{project_name}}"
target_level: 4
confidence_threshold: 0.75

# Model routing for cost optimization
model_routing:
  enabled: true
  provider: "anthropic"
  models:
    cheap: "claude-3-haiku-20240307"
    capable: "claude-sonnet-4-20250514"
    premium: "claude-opus-4-20250514"

# Claude Code integration
claude_sync:
  enabled: true
  output_dir: ".claude/rules/empathy"

# Persistence
persistence_enabled: true
persistence_backend: "sqlite"
persistence_path: ".empathy"
metrics_enabled: true
""",
            ".claude/CLAUDE.md": """# {{project_name}} - Claude Code Rules

## Project Context

This project uses Empathy Framework for AI-assisted development.

## Empathy Integration

Run these commands for best results:
- `empathy morning` - Start-of-day briefing
- `empathy ship` - Pre-commit checks
- `empathy sync-claude` - Sync patterns to Claude Code

## Coding Patterns

@patterns/debugging.json
@patterns/security.json
""",
            ".gitignore_additions": """# Empathy Framework
.attune/
patterns/sensitive/
*.db
""",
        },
    },
    "python-cli": {
        "name": "Python CLI Tool",
        "description": "Command-line tool with Empathy for smart assistance",
        "files": {
            "attune.config.yml": """# Empathy Framework Configuration
# Template: python-cli

user_id: "{{project_name}}"
target_level: 4
confidence_threshold: 0.75

model_routing:
  enabled: true
  provider: "anthropic"
  models:
    cheap: "claude-3-haiku-20240307"
    capable: "claude-sonnet-4-20250514"
    premium: "claude-opus-4-20250514"

claude_sync:
  enabled: true
  output_dir: ".claude/rules/empathy"

persistence_enabled: true
persistence_backend: "sqlite"
persistence_path: ".empathy"
metrics_enabled: true

inspection:
  parallel: true
  learning: true
  format: "terminal"
""",
            "{{project_name}}/__init__.py": '''"""
{{project_name}} - A CLI tool powered by Empathy Framework
"""

__version__ = "0.1.0"
''',
            "{{project_name}}/cli.py": '''"""
Command-line interface for {{project_name}}
"""

import argparse
from attune import EmpathyOS, load_config


def main():
    parser = argparse.ArgumentParser(
        prog="{{project_name}}",
        description="{{project_name}} - powered by Empathy Framework"
    )
    parser.add_argument("--version", action="version", version="%(prog)s 0.1.0")

    args = parser.parse_args()

    # Initialize Empathy
    config = load_config()
    empathy = EmpathyOS(config)

    print("{{project_name}} is ready!")
    print(f"Empathy level: {config.target_level}")


if __name__ == "__main__":
    main()
''',
            "pyproject.toml": """[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{project_name}}"
version = "0.1.0"
description = "A CLI tool powered by Empathy Framework"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
    "empathy-framework>=2.3",
]

[project.scripts]
{{project_name}} = "{{project_name}}.cli:main"
""",
            "README.md": """# {{project_name}}

A CLI tool powered by Empathy Framework.

## Installation

```bash
pip install -e .
```

## Usage

```bash
{{project_name}} --help
```

## Development

```bash
# Start-of-day briefing
empathy morning

# Pre-commit checks
empathy ship

# Sync patterns to Claude Code
empathy sync-claude
```
""",
            ".claude/CLAUDE.md": """# {{project_name}} - Claude Code Rules

## Project Context

CLI tool built with Empathy Framework.

## Key Commands

- `empathy morning` - Start-of-day briefing
- `empathy ship` - Pre-commit checks
- `empathy learn` - Extract patterns from git history

## Patterns

@patterns/debugging.json
""",
            ".gitignore": """# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/
.eggs/

# Empathy Framework
.attune/
patterns/sensitive/

# IDE
.vscode/
.idea/

# Environment
.env
.venv/
""",
        },
    },
    "python-fastapi": {
        "name": "Python FastAPI",
        "description": "FastAPI web service with Empathy integration",
        "files": {
            "attune.config.yml": """# Empathy Framework Configuration
# Template: python-fastapi

user_id: "{{project_name}}"
target_level: 4
confidence_threshold: 0.75

model_routing:
  enabled: true
  provider: "anthropic"
  models:
    cheap: "claude-3-haiku-20240307"
    capable: "claude-sonnet-4-20250514"
    premium: "claude-opus-4-20250514"

claude_sync:
  enabled: true
  output_dir: ".claude/rules/empathy"

persistence_enabled: true
persistence_backend: "sqlite"
persistence_path: ".empathy"
metrics_enabled: true

health:
  checks:
    lint: true
    format: true
    types: true
    security: true
""",
            "{{project_name}}/__init__.py": '''"""
{{project_name}} - FastAPI service with Empathy Framework
"""

__version__ = "0.1.0"
''',
            "{{project_name}}/main.py": '''"""
FastAPI application for {{project_name}}
"""

from fastapi import FastAPI
from attune import EmpathyOS, load_config

app = FastAPI(
    title="{{project_name}}",
    description="FastAPI service powered by Empathy Framework",
    version="0.1.0"
)

# Initialize Empathy (optional - for AI features)
try:
    config = load_config()
    empathy = EmpathyOS(config)
except Exception:
    empathy = None


@app.get("/")
async def root():
    return {
        "message": "Welcome to {{project_name}}",
        "empathy_enabled": empathy is not None
    }


@app.get("/health")
async def health():
    return {"status": "healthy"}
''',
            "pyproject.toml": """[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{project_name}}"
version = "0.1.0"
description = "FastAPI service powered by Empathy Framework"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
    "fastapi>=0.100",
    "uvicorn[standard]>=0.20",
    "empathy-framework>=2.3",
]

[project.scripts]
{{project_name}} = "{{project_name}}.main:app"
""",
            "README.md": """# {{project_name}}

FastAPI service powered by Empathy Framework.

## Installation

```bash
pip install -e .
```

## Running

```bash
uvicorn {{project_name}}.main:app --reload
```

## Development

```bash
# Start-of-day briefing
empathy morning

# Pre-commit checks
empathy ship

# Run health checks
empathy health
```

## API

- `GET /` - Root endpoint
- `GET /health` - Health check
""",
            ".claude/CLAUDE.md": """# {{project_name}} - Claude Code Rules

## Project Context

FastAPI web service with Empathy Framework integration.

## API Structure

- `main.py` - FastAPI app definition
- Standard RESTful patterns

## Commands

- `empathy morning` - Daily briefing
- `empathy ship` - Pre-commit checks
- `empathy health` - Code health

## Patterns

@patterns/debugging.json
@patterns/security.json
""",
            ".gitignore": """# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/

# Empathy Framework
.attune/
patterns/sensitive/

# Environment
.env
.venv/

# IDE
.vscode/
.idea/
""",
        },
    },
    "python-agent": {
        "name": "Python AI Agent",
        "description": "AI agent project with Empathy for pattern learning",
        "files": {
            "attune.config.yml": """# Empathy Framework Configuration
# Template: python-agent

user_id: "{{project_name}}_agent"
target_level: 5  # Systems thinking for agents
confidence_threshold: 0.8

model_routing:
  enabled: true
  provider: "anthropic"
  models:
    cheap: "claude-3-haiku-20240307"
    capable: "claude-sonnet-4-20250514"
    premium: "claude-opus-4-20250514"
  task_overrides:
    summarize: "cheap"
    classify: "cheap"
    generate_code: "capable"
    architectural_decision: "premium"
    coordinate: "premium"

claude_sync:
  enabled: true
  output_dir: ".claude/rules/empathy"
  sync_patterns:
    debugging: true
    security: true
    inspection: true

persistence_enabled: true
persistence_backend: "sqlite"
persistence_path: ".empathy"
metrics_enabled: true

# Agent-specific settings
pattern_library_enabled: true
pattern_sharing: true
""",
            "{{project_name}}/__init__.py": '''"""
{{project_name}} - AI Agent powered by Empathy Framework
"""

__version__ = "0.1.0"
''',
            "{{project_name}}/agent.py": '''"""
AI Agent implementation for {{project_name}}
"""

from attune import EmpathyOS, load_config
from attune_llm import EmpathyLLM
import os


class {{project_name_class}}Agent:
    """
    AI Agent with Empathy-powered learning and memory.
    """

    def __init__(self):
        self.config = load_config()
        self.empathy = EmpathyOS(self.config)

        # Initialize LLM with model routing
        self.llm = EmpathyLLM(
            provider="anthropic",
            api_key=os.getenv("ANTHROPIC_API_KEY"),
        )

    async def process(self, user_input: str, context: dict = None) -> str:
        """Process user input and return response."""
        response = await self.llm.interact(
            user_id=self.config.user_id,
            user_input=user_input,
            context=context or {}
        )
        return response.get("response", "")

    def get_patterns(self) -> list:
        """Get learned patterns."""
        return self.empathy.pattern_library.list_patterns()


async def main():
    """Example usage."""
    agent = {{project_name_class}}Agent()
    response = await agent.process("Hello, what can you help me with?")
    print(response)


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
''',
            "pyproject.toml": """[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "{{project_name}}"
version = "0.1.0"
description = "AI Agent powered by Empathy Framework"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
    "empathy-framework>=2.3",
    "anthropic>=0.18",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-asyncio>=0.21",
]
""",
            "README.md": """# {{project_name}}

AI Agent powered by Empathy Framework with pattern learning.

## Setup

1. Install dependencies:
   ```bash
   pip install -e ".[dev]"
   ```

2. Set API key:
   ```bash
   export ANTHROPIC_API_KEY="your-key"
   ```

3. Run agent:
   ```bash
   python -m {{project_name}}.agent
   ```

## Features

- Model routing for cost optimization
- Pattern learning from interactions
- Claude Code integration

## Development

```bash
# Learn patterns from git history
empathy learn --analyze 50

# Sync patterns to Claude Code
empathy sync-claude

# Morning briefing
empathy morning
```
""",
            ".claude/CLAUDE.md": """# {{project_name}} - AI Agent Rules

## Project Context

AI agent with Empathy Framework for pattern learning and memory.

## Agent Architecture

- `agent.py` - Main agent class with Empathy integration
- Model routing: Haiku for simple, Sonnet for code, Opus for decisions

## Pattern Storage

Patterns are stored in `patterns/` and synced to Claude Code.

@patterns/debugging.json
@patterns/security.json
@patterns/inspection.json
""",
            ".gitignore": """# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/

# Empathy Framework
.attune/
patterns/sensitive/

# Environment
.env
.venv/

# IDE
.vscode/
.idea/
""",
            "tests/__init__.py": "",
            "tests/test_agent.py": '''"""Tests for {{project_name}} agent."""

import pytest
from {{project_name}}.agent import {{project_name_class}}Agent


def test_agent_init():
    """Test agent initialization."""
    # Note: This will require config file
    # agent = {{project_name_class}}Agent()
    # assert agent is not None
    pass
''',
        },
    },
}


def list_templates() -> list:
    """List available templates."""
    return [
        {"id": tid, "name": t["name"], "description": t["description"]}
        for tid, t in TEMPLATES.items()
    ]


def scaffold_project(
    template_name: str,
    project_name: str,
    target_dir: str | None = None,
    force: bool = False,
) -> dict:
    """Create a new project from a template.

    Args:
        template_name: Template ID (minimal, python-cli, python-fastapi, python-agent)
        project_name: Name for the new project
        target_dir: Directory to create project in (default: ./{project_name})
        force: Overwrite existing files

    Returns:
        Dict with created files and status

    """
    if template_name not in TEMPLATES:
        return {
            "success": False,
            "error": f"Unknown template: {template_name}",
            "available": list(TEMPLATES.keys()),
        }

    template = TEMPLATES[template_name]
    target = Path(target_dir) if target_dir else Path(project_name)

    # Check if directory exists
    if target.exists() and not force:
        if any(target.iterdir()):
            return {
                "success": False,
                "error": f"Directory '{target}' exists and is not empty. Use --force to overwrite.",
            }

    # Create directory
    target.mkdir(parents=True, exist_ok=True)

    # Create project name class version (for Python class names)
    project_name_class = "".join(
        word.capitalize() for word in project_name.replace("-", "_").replace(" ", "_").split("_")
    )

    # Create files
    created_files = []
    files = template["files"]
    if not isinstance(files, dict):
        return {"success": False, "error": "Invalid template structure"}
    for file_path, content in files.items():
        # Replace placeholders in path
        actual_path = file_path.replace("{{project_name}}", project_name)

        # Replace placeholders in content
        actual_content = content.replace("{{project_name}}", project_name)
        actual_content = actual_content.replace("{{project_name_class}}", project_name_class)

        # Create file
        full_path = target / actual_path
        full_path.parent.mkdir(parents=True, exist_ok=True)

        # Handle special files
        if file_path == ".gitignore_additions":
            # Append to existing .gitignore or create new
            gitignore_path = target / ".gitignore"
            validated_gitignore = _validate_file_path(str(gitignore_path))
            if validated_gitignore.exists():
                with open(validated_gitignore, "a") as f:
                    f.write("\n" + actual_content)
            else:
                with open(validated_gitignore, "w") as f:
                    f.write(actual_content)
            created_files.append(".gitignore")
        else:
            validated_path = _validate_file_path(str(full_path))
            with open(validated_path, "w") as f:
                f.write(actual_content)
            created_files.append(actual_path)

    # Create patterns directory
    (target / "patterns").mkdir(exist_ok=True)

    return {
        "success": True,
        "template": template_name,
        "project_name": project_name,
        "target_dir": str(target),
        "files_created": created_files,
        "next_steps": [f"cd {target}", "pip install -e .", "empathy morning"],
    }


def cmd_new(args):
    """CLI command handler for creating new projects."""
    template = getattr(args, "template", None)
    project_name = getattr(args, "name", None)
    target_dir = getattr(args, "output", None)
    force = getattr(args, "force", False)
    list_only = getattr(args, "list", False)

    if list_only:
        print("\nAvailable Templates:")
        print("-" * 50)
        for t in list_templates():
            print(f"  {t['id']:15} {t['description']}")
        print("\nUsage: empathy new <template> <project-name>")
        print()
        return 0

    if not template or not project_name:
        print("Usage: empathy new <template> <project-name>")
        print("       empathy new --list")
        return 1

    print(f"\nCreating new project from '{template}' template...")

    result = scaffold_project(template, project_name, target_dir, force)

    if result["success"]:
        print(f"\n  Project created: {result['target_dir']}")
        print("\n  Files created:")
        for f in result["files_created"]:
            print(f"    - {f}")
        print("\n  Next steps:")
        for step in result["next_steps"]:
            print(f"    $ {step}")
        print()
        return 0
    print(f"\n  Error: {result['error']}")
    if "available" in result:
        print(f"  Available templates: {', '.join(result['available'])}")
    print()
    return 1
