"""
Documentation generator for KEN-MCP
Handles generation of help.md and README.md files
"""

from pathlib import Path
from ken_mcp.core.models import GenerationPlan
from ken_mcp.templates.constants import (
    HELP_QUICK_START, HELP_TESTING_SECTION, README_TEMPLATE
)


def generate_documentation(
    project_path: Path, 
    plan: GenerationPlan, 
    project_name: str,
    python_version: str = "3.10"
) -> None:
    """Generate documentation files (help.md and README.md)
    
    Args:
        project_path: Path to project directory
        plan: Generation plan
        project_name: Name of the project
        python_version: Python version requirement
    """
    # Generate help.md
    help_content = generate_help_content(project_path, project_name, python_version)
    (project_path / "help.md").write_text(help_content)
    
    # Generate README.md
    readme_content = generate_readme_content(project_name, plan.description)
    (project_path / "README.md").write_text(readme_content)


def generate_help_content(project_path: Path, project_name: str, python_version: str) -> str:
    """Generate comprehensive help.md content
    
    Args:
        project_path: Path to project directory
        project_name: Name of the project
        python_version: Python version requirement
        
    Returns:
        Complete help.md content
    """
    # Start with quick start section
    content = HELP_QUICK_START.format(
        project_name=project_name,
        project_path=project_path
    )
    
    # Add testing section
    content += "\n" + HELP_TESTING_SECTION.format(
        project_path=project_path,
        project_name=project_name
    )
    
    # Add troubleshooting section
    content += "\n" + generate_troubleshooting_section(
        project_path, project_name, python_version
    )
    
    # Add management section
    content += "\n" + generate_management_section(project_name, project_path)
    
    # Add footer
    content += """

---
Generated by KEN-MCP - Comprehensive troubleshooting guide included
"""
    
    return content


def generate_troubleshooting_section(
    project_path: Path, 
    project_name: str, 
    python_version: str
) -> str:
    """Generate troubleshooting section for help.md
    
    Args:
        project_path: Path to project directory
        project_name: Name of the project
        python_version: Python version requirement
        
    Returns:
        Troubleshooting section content
    """
    return f"""
## 🔧 Troubleshooting Failed MCP Connection

If the MCP shows as "Failed" in Claude Code, follow these steps:

### Step 1: System Diagnosis

Run this comprehensive system check:

```bash
# Check MCP status
claude mcp list

# System information
echo "=== System Information ==="
uname -a
echo "Operating System: $(uname -s)"
echo "Architecture: $(uname -m)"

# Python availability
echo "=== Python Installation Analysis ==="
which python 2>/dev/null && python --version 2>/dev/null || echo "❌ python: not found"
which python3 2>/dev/null && python3 --version 2>/dev/null || echo "❌ python3: not found"

# Check specific Python versions
for version in 3.8 3.9 3.10 3.11 3.12; do
    cmd="python${{version}}"
    if which "$cmd" >/dev/null 2>&1; then
        echo "✅ $cmd: $($cmd --version 2>/dev/null)"
    else
        echo "❌ $cmd: not found"
    fi
done

# Test the MCP directly
cd {project_path}
python3 server.py
```

### Step 2: Common Fixes (Try in Order)

#### 1. Wrong Python Command (Most Common)
```bash
# Find your Python
which python3

# Remove and re-add with correct Python
claude mcp remove {project_name}
# EXIT Claude Code (type 'exit' or Ctrl+C) and restart with 'claude'

# Try different Python commands:
claude mcp add {project_name} "python3 {project_path}/server.py"
# OR
claude mcp add {project_name} "/usr/bin/python3 {project_path}/server.py"
# OR
claude mcp add {project_name} "python3.11 {project_path}/server.py"

# EXIT Claude Code and restart again
```

#### 2. Missing Dependencies
```bash
cd {project_path}
python3 -m pip install -e .

# If you get "externally managed environment" error:
python3 -m pip install --user -e .
# OR use pipx:
pipx install -e .
```

#### 3. Wrong File Path
```bash
# Verify the exact path
ls -la {project_path}/server.py

# Use absolute path when adding
claude mcp add {project_name} "python3 $(pwd)/server.py"
```

#### 4. Permission Issues
```bash
chmod +x {project_path}/server.py
```

#### 5. Python Version Conflicts
```bash
# This MCP requires Python >= {python_version}
# Check your version:
python3 --version

# If too old, use a newer Python:
claude mcp add {project_name} "python3.11 {project_path}/server.py"
```

### Step 3: Virtual Environment (If Other Fixes Fail)
```bash
cd {project_path}
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install -e .

# Use venv Python in Claude
claude mcp remove {project_name}
# EXIT and restart Claude Code
claude mcp add {project_name} "{project_path}/venv/bin/python {project_path}/server.py"
# EXIT and restart Claude Code
```

## 📋 Quick Fix Checklist

Run through this checklist when troubleshooting:

□ Test manually: `cd {project_path} && python3 server.py`
□ Check Python path: `which python3`
□ Install dependencies: `python3 -m pip install -e .`
□ Use absolute paths in `claude mcp add`
□ EXIT and restart Claude Code after EVERY change
□ Check MCP status: `claude mcp list`"""


def generate_management_section(project_name: str, project_path: Path) -> str:
    """Generate MCP management section
    
    Args:
        project_name: Name of the project
        project_path: Path to project directory
        
    Returns:
        Management section content
    """
    return f"""
## 🔄 Managing This MCP

### Update/Reinstall
```bash
# Remove the MCP
claude mcp remove {project_name}
# EXIT Claude Code (type 'exit' or Ctrl+C)

# Make any changes to the code if needed
cd {project_path}
# Edit files...

# Reinstall dependencies if needed
python3 -m pip install -e .

# Re-add the MCP
claude mcp add {project_name} "python3 {project_path}/server.py"
# EXIT and restart Claude Code
```

### Check Status
```bash
claude mcp list
# ✓ = Active (working)
# ✗ = Failed (see troubleshooting above)
```

### View Logs
Check Claude Desktop logs for detailed error messages if the above steps don't resolve the issue.

## 🆘 Still Not Working?

If you've tried all the above and the MCP still shows as "Failed":

1. **Test the exact command Claude is using:**
   ```bash
   # Copy the exact command from 'claude mcp list' output
   # Run it directly to see the error
   ```

2. **Check for conflicting Python packages:**
   ```bash
   pip list | grep -E "(fastmcp|pydantic)"
   ```

3. **Try a completely fresh virtual environment:**
   ```bash
   cd {project_path}
   rm -rf venv
   python3 -m venv fresh_venv
   source fresh_venv/bin/activate
   pip install -e .
   ```

## 📝 Notes

- Always use absolute paths (full path starting with /)
- Python environment matters - Claude must use the same Python that has the dependencies
- "Failed" status is generic - always test manually to find the real error
- Some systems require specific Python versions or virtual environments"""


def generate_readme_content(project_name: str, description: str) -> str:
    """Generate README.md content
    
    Args:
        project_name: Name of the project
        description: Project description
        
    Returns:
        README.md content
    """
    return README_TEMPLATE.format(
        project_name=project_name,
        description=description
    )