"""
Constants and templates for KEN-MCP server generator
All hardcoded strings and templates extracted from generator.py
"""

# File content templates
GITIGNORE_TEMPLATE = """__pycache__/
*.py[cod]
.env
.venv/
venv/
*.log
.DS_Store
"""

ENV_EXAMPLE_TEMPLATE = """# Environment variables for MCP server
# Copy this file to .env and fill in your actual values

# API Keys
# OPENAI_API_KEY=your_openai_api_key_here
# ANTHROPIC_API_KEY=your_anthropic_api_key_here
# GOOGLE_API_KEY=your_google_api_key_here

# Database Configuration
# DATABASE_URL=postgresql://user:password@localhost:5432/dbname
# REDIS_URL=redis://localhost:6379

# External Service URLs
# API_BASE_URL=https://api.example.com
# WEBHOOK_URL=https://your-webhook-endpoint.com

# Authentication
# AUTH_TOKEN=your_auth_token_here
# CLIENT_ID=your_client_id_here
# CLIENT_SECRET=your_client_secret_here

# Feature Flags
# DEBUG_MODE=false
# ENABLE_LOGGING=true

# Rate Limiting
# RATE_LIMIT_REQUESTS=100
# RATE_LIMIT_WINDOW=3600

# Custom Configuration
# Add your own environment variables below:
"""

# Server code templates
SERVER_HEADER_TEMPLATE = '''#!/usr/bin/env python3
"""
{description}
Generated by KEN-MCP on {date}

TODO: Claude, please customize this MCP server based on these requirements:
{requirements}

Instructions:
1. Rename the placeholder tools to match the actual functionality needed
2. Update tool descriptions and parameters based on requirements
3. Implement the actual logic in each tool function
4. Add/remove tools, resources, and prompts as needed
5. Update dependencies in pyproject.toml if additional packages are required
"""

{imports}

{env_loading}# Initialize the MCP server
mcp = FastMCP(
    name="{project_name}",
    instructions="""
    {description}
    
    Original Requirements:
    {requirements}
    
    TODO: Claude should update these instructions based on the actual implementation.
    """
)

'''

# Tool implementation templates
TOOL_BOILERPLATE_TEMPLATE = '''    # TODO: Claude, implement this tool based on the requirements in the docstring above
    # Consider:
    # - What data sources or APIs might be needed
    # - What processing or transformations are required
    # - What error cases should be handled
    # - What progress updates would be helpful
    
    try:
        # FastMCP Context Methods Reference:
        # - await ctx.info("message") - Log information
        # - await ctx.report_progress(current, total, "message") - Show progress
        # - await ctx.read_resource("uri") - Read from a resource
        
        await ctx.info(f"Starting {tool_name}...")
        
        # TODO: Add parameter validation
        # Example patterns:
        # if not input_data:
        #     raise ToolError("input_data is required")
        # 
        # if not isinstance(input_data, str):
        #     raise ToolError("input_data must be a string")
        #
        # if len(input_data) > 1000:
        #     raise ToolError("input_data too long (max 1000 chars)")
        
        # TODO: Implement the main functionality
        # Common patterns by use case:
        #
        # For data storage:
        #   storage_dir = Path.home() / ".mcp_data" / "{tool_name}"
        #   storage_dir.mkdir(parents=True, exist_ok=True)
        #
        # For API calls:
        #   import httpx
        #   async with httpx.AsyncClient() as client:
        #       response = await client.get(url)
        #
        # For file processing:
        #   from pathlib import Path
        #   file = Path(file_path)
        #   if not file.exists():
        #       raise ToolError(f"File not found: {{file_path}}")
        
        # TODO: Add progress updates for long operations
        # await ctx.report_progress(25, 100, "Loading data...")
        # await ctx.report_progress(50, 100, "Processing...")
        # await ctx.report_progress(75, 100, "Finalizing...")
        
        # TODO: Return appropriate result
        # Success pattern:
        # return {{
        #     "success": True,
        #     "data": processed_data,
        #     "count": len(results),
        #     "message": "Operation completed successfully"
        # }}
        
        result = {{
            "status": "not_implemented",
            "message": f"TODO: Implement {tool_name}",
            "tool": "{tool_name}",
            "description": {tool_desc},
            "input": locals()  # Shows all parameters for debugging
        }}
        
        await ctx.info(f"{tool_name} completed")
        return result
        
    except Exception as e:
        # Always use ToolError for user-facing errors
        raise ToolError(f"{tool_name} error: {{str(e)}}")
'''

TOOL_FALLBACK_TEMPLATE = '''    try:
        from datetime import datetime
        import json
        {param_validation}
        
        await ctx.info(f"Executing {tool_name}...")
        
        # Implementation based on tool purpose
        result = {{
            "tool": "{tool_name}",
            "description": {tool_desc},
            "status": "success",
            "message": "Tool executed successfully",
            "timestamp": datetime.now().isoformat()
        }}
        
        # Add input parameters to result
        for param_name, param_value in locals().items():
            if param_name not in ['ctx', 'result'] and not param_name.startswith('_'):
                result[f"input_{{param_name}}"] = param_value
        
        return result
        
    except Exception as e:
        raise ToolError(f"Failed to execute {tool_name}: {{str(e)}}")
'''

# Resource and prompt templates
RESOURCE_TEMPLATE = '''
@mcp.resource("{uri}")
async def resource_{resource_name}({params_str}) -> List[Dict[str, Any]]:
    """{description}"""
    # TODO: Implement this resource based on requirements
    # Consider what data should be exposed here
    return [{{
        "status": "not_implemented", 
        "message": "TODO: Implement resource for {uri}",
        "description": "{description}"
    }}]
'''

PROMPT_TEMPLATE = '''
@mcp.prompt
def {prompt_name}({params_str}) -> str:
    """{description}"""
    # TODO: Implement this prompt based on requirements
    # Return a string that will be converted to a user message
    # or return a PromptMessage object for more control
    return f"TODO: Implement {prompt_name} prompt - {{locals()}}"
'''

# PyProject template
PYPROJECT_TEMPLATE = """[project]
name = "{project_name}"
version = "0.1.0"
description = "{description}"
readme = "README.md"
requires-python = ">={python_version}"
dependencies = {dependencies}

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["."]
"""

# Documentation templates
README_TEMPLATE = """# {project_name}

{description}

## Installation

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

## Usage

This MCP server is designed to be used with Claude Desktop. See `help.md` for detailed setup and troubleshooting instructions.

## Documentation

- **Setup Guide**: See `help.md` for comprehensive setup instructions
- **Troubleshooting**: See `help.md` for common issues and solutions
- **MCP Protocol**: https://modelcontextprotocol.io

---
Generated by KEN-MCP
"""

# Test file header template
TEST_FILE_HEADER = '''#!/usr/bin/env python3
"""
Automated test suite for {project_name} MCP server
Generated by KEN-MCP

INSTRUCTIONS FOR CLAUDE:
1. Run this test file immediately: python test.py
2. Fix any failing tests in server.py
3. Add domain-specific test cases based on the requirements
4. Ensure all tests pass before considering the MCP complete

Original Requirements:
{requirements}
"""

import asyncio
import json
import sys
from pathlib import Path

# Add the parent directory to the path so we can import the server
sys.path.insert(0, str(Path(__file__).parent))

# Import the generated server
try:
    from server import mcp
except ImportError as e:
    print(f"❌ Failed to import server: {{e}}")
    print("Make sure server.py exists and has no syntax errors")
    sys.exit(1)
'''

# Error messages
ERROR_MESSAGES = {
    "file_not_found": "File not found: {file_path}",
    "invalid_url": "Invalid URL: {url} must start with http:// or https://",
    "invalid_type": "Invalid {param_name}: must be a valid {expected_type}",
    "parameter_required": "{param_name} is required",
    "value_too_long": "{param_name} too long (max {max_length} chars)",
    "import_failed": "Failed to import server: {error}",
    "syntax_error": "Syntax error in server.py: {error}",
    "test_failed": "{test_name} test failed: {error}",
    "generation_failed": "Failed to generate MCP server: {error}",
    "tool_error": "{tool_name} error: {error}"
}

# Progress messages
PROGRESS_MESSAGES = {
    "analyzing": "Analyzing requirements...",
    "creating_structure": "Creating project structure...",
    "generating_server": "Generating server code...",
    "creating_docs": "Creating documentation...",
    "generating_tests": "Generating test suite...",
    "validating": "Validating project...",
    "complete": "Generation complete!"
}

# Log messages
LOG_MESSAGES = {
    "starting_generation": "🚀 Starting MCP generation for: {project_name}",
    "analyzing_requirements": "📋 Creating boilerplate structure for Claude to customize...",
    "creating_project": "📁 Creating project structure...",
    "generating_code": "💻 Generating server code...",
    "generating_docs": "📚 Generating documentation...",
    "generating_tests": "🧪 Generating test suite...",
    "validating_project": "✔️ Validating project...",
    "project_created": "✅ Created project at: {project_path}",
    "plan_created": "✅ Boilerplate plan created with {tool_count} placeholder tools",
    "server_generated": "✅ Generated server.py and pyproject.toml",
    "docs_generated": "✅ Generated documentation files",
    "tests_generated": "✅ Generated test.py with comprehensive test suite"
}

# Keywords for domain detection
DOMAIN_KEYWORDS = {
    "cooking": ["recipe", "cook", "ingredient", "meal"],
    "task_management": ["task", "todo", "project", "deadline"],
    "monitoring": ["monitor", "track", "watch", "alert"],
    "api_integration": ["api", "endpoint", "rest", "http"],
    "file_processing": ["file", "document", "pdf", "csv"],
    "database": ["database", "sql", "query", "table"],
    "web_scraping": ["scrape", "web", "html", "crawl"],
    "crypto": ["crypto", "bitcoin", "ethereum", "price"],
    "ml_ai": ["classify", "predict", "analyze", "nlp"],
    "realtime": ["websocket", "real-time", "streaming", "live"],
    "auth": ["oauth", "auth", "login", "token"],
    "data_science": ["numpy", "pandas", "matplotlib", "chart"],
    "machine_learning": ["machine learning", "ml", "prediction", "model"]
}

# Dependency suggestions by domain
DEPENDENCY_SUGGESTIONS = {
    "api_http": ["httpx", "requests"],
    "web_scraping": ["beautifulsoup4", "requests", "lxml"],
    "data_processing": ["pandas", "openpyxl"],
    "database": ["sqlalchemy", "psycopg2", "pymysql"],
    "pdf": ["pypdf2"],
    "image": ["pillow"],
    "markdown": ["markdown"],
    "crypto": ["ccxt", "yfinance"],
    "ml_ai": ["scikit-learn", "nltk", "spacy"],
    "websocket": ["websockets", "asyncio"],
    "auth": ["authlib", "oauthlib"],
    "discord": ["discord.py"],
    "slack": ["slack-sdk"],
    "github": ["PyGithub"],
    "data_science": ["numpy", "pandas", "matplotlib"],
    "machine_learning": ["scikit-learn", "joblib"],
    "xml": ["xmltodict"]
}

# Default tool names by position
DEFAULT_TOOL_NAMES = {
    0: {
        "recipe": ["add_recipe", "create_recipe", "save_recipe"],
        "task": ["create_task", "add_todo", "new_task"],
        "monitor": ["start_monitor", "add_monitor", "track_item"],
        "default": ["create_item", "add_entry", "initialize"]
    },
    1: {
        "recipe": ["list_recipes", "search_recipes", "get_recipe"],
        "task": ["list_tasks", "get_tasks", "show_todos"],
        "default": ["list_items", "search_data", "query_items"]
    },
    2: {
        "recipe": ["update_recipe", "rate_recipe", "categorize_recipe"],
        "task": ["complete_task", "update_task", "mark_done"],
        "default": ["update_item", "process_data", "modify_entry"]
    }
}

# Standard library modules (don't need to be installed)
STDLIB_MODULES = {
    "pathlib", "json", "typing", "os", "datetime", 
    "subprocess", "shlex", "platform", "asyncio",
    "stat", "re", "sys"
}

# Default Python version
DEFAULT_PYTHON_VERSION = "3.10"

# Limits from CLAUDE.md
MAX_LINE_LENGTH = 120
MAX_PARAMS_PER_FUNCTION = 4
MAX_LINES_PER_FILE = 300
MAX_NESTING_LEVELS = 4
MAX_DOCSTRING_LENGTH = 500

# Test constants
TEST_MOCK_CONTEXT = '''# Test utilities
class MockContext:
    """Mock context for testing MCP tools"""
    def __init__(self):
        self.logs = []
        self.progress = []
    
    async def info(self, msg):
        self.logs.append(msg)
    
    async def report_progress(self, current, total, msg):
        self.progress.append((current, total, msg))
    
    async def read_resource(self, uri):
        return {"uri": uri, "content": "mock resource content"}
'''

# Help documentation sections
HELP_QUICK_START = """# {project_name} - Setup & Troubleshooting Guide

## 🚀 Quick Start

### Adding to Claude Code
```bash
# Add the MCP server
claude mcp add {project_name} "python3 {project_path}/server.py"

# IMPORTANT: Exit and restart Claude Code
# Type 'exit' or press Ctrl+C, then run 'claude' again

# Verify it's active
claude mcp list
# Should show: ✓ {project_name}    Active
```"""

HELP_TESTING_SECTION = """### Testing the MCP Server
```bash
cd {project_path}

# Run the automated test suite
python3 test.py

# Expected output:
# ==================================================
# 🧪 Running MCP Server Tests for {project_name}
# ==================================================
# Testing server initialization...
#   ✅ Server initialization test passed
# Testing tool_one...
#   ✅ Valid input test passed
# ... more tests ...
# ==================================================
# 📊 Test Summary: X/Y passed
# ==================================================
# ✅ All tests passed! The MCP server is ready to use.
```

If any tests fail:
1. Check the error messages in the test output
2. Fix the implementation in server.py
3. Run the tests again until all pass

### Manual Testing
```bash
# Test the server directly (for debugging)
python3 server.py
# Expected output: "Server started on stdio"
# Press Ctrl+C to stop
```"""

# Generation date format
DATE_FORMAT = '%Y-%m-%d'