"""
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: Run Automatic Diagnostics

We've included a diagnostic script that checks for common issues:

```bash
cd {project_path}
python3 diagnose.py
```

This will check:
- ✅ Python version compatibility
- ✅ All dependencies installed
- ✅ No print() statements breaking the protocol
- ✅ Proper logging configuration
- ✅ Server syntax and imports
- ✅ JSON-RPC compliance

Fix any ❌ failures shown, then re-run the diagnostic.

### Step 2: Manual System Diagnosis

If diagnostics pass but MCP still fails, 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 3: 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 (Global scope - recommended):
claude mcp add {project_name} -s user "python3 {project_path}/server.py"
# OR
claude mcp add {project_name} -s user "/usr/bin/python3 {project_path}/server.py"
# OR
claude mcp add {project_name} -s user "python3.11 {project_path}/server.py"

# Alternative (Local scope - only works from current directory):
# claude mcp add {project_name} -s user "python3 {project_path}/server.py"

# EXIT Claude Code and restart again
```

#### 2. Missing Dependencies
```bash
cd {project_path}

# Modern Linux (Ubuntu 22.04+, Debian 12+) - recommended method
python3 -m pip install --user --break-system-packages -r requirements.txt

# If you get "externally managed environment" error, try these options:
# Option 1: Use --break-system-packages (recommended)
python3 -m pip install --user --break-system-packages -r requirements.txt

# Option 2: Create a virtual environment (best for development)
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install -r requirements.txt

# Option 3: System packages (if available)
sudo apt install python3-fastmcp python3-httpx python3-pydantic

# Option 4: Older Linux systems
python3 -m pip install --user -r requirements.txt
```

#### 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} -s user "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} -s user "python3.11 {project_path}/server.py"
```

### Step 4: 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 -r requirements.txt

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

## 📋 Quick Fix Checklist

Run through this checklist when troubleshooting:

□ Run diagnostics: `cd {project_path} && python3 diagnose.py`
□ Fix any issues reported by diagnostics
□ Test manually: `python3 server.py`
□ Check Python path: `which python3`
□ Install dependencies: `pip install -r requirements.txt`
□ Use absolute paths in `claude mcp add` with `-s user` for global access
□ EXIT and restart Claude Code after EVERY change
□ Check MCP status: `claude mcp list`

## 🔍 About the Diagnostic Script

The `diagnose.py` script included in this project checks for:
- **Protocol Issues**: print() statements that break JSON-RPC
- **Dependencies**: Missing packages that prevent startup
- **Configuration**: Proper logging setup to stderr
- **Compatibility**: Python version requirements
- **Syntax**: Code errors that prevent loading

Always run diagnostics first when troubleshooting!"""


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
pip install -r requirements.txt

# Re-add the MCP
claude mcp add {project_name} -s user "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
    )


def generate_help_to_root(
    root_path: Path,
    project_path: Path,
    plan: GenerationPlan,
    project_name: str,
    python_version: str = "3.10"
) -> None:
    """Generate help.md in root directory with updated paths for new file structure
    
    Args:
        root_path: Path to root directory
        project_path: Path to MCP project directory
        plan: Generation plan
        project_name: Name of the project
        python_version: Python version requirement
    """
    help_content = generate_help_content_for_root(
        root_path, project_path, project_name, python_version
    )
    (root_path / "help.md").write_text(help_content)


def generate_help_content_for_root(
    root_path: Path, 
    project_path: Path, 
    project_name: str, 
    python_version: str
) -> str:
    """Generate help.md content for root directory with updated script paths
    
    Args:
        root_path: Path to root directory
        project_path: Path to MCP project directory
        project_name: Name of the project
        python_version: Python version requirement
        
    Returns:
        Complete help.md content with updated paths for new structure
    """
    # Updated quick start section with scripts/ paths
    content = f"""# {project_name} MCP Server - Complete Setup & Troubleshooting Guide

## 🚀 Quick Start

### 1. Test the MCP Server
```bash
# Run the test suite
cd {root_path}
python3 scripts/test.py

# Check for implementation issues
python3 scripts/verify.py

# Run diagnostics if there are issues
python3 scripts/diagnose.py
```

### 2. Add to Claude Code
```bash
# Add the MCP to Claude Code (Global - Recommended)
claude mcp add {project_name} -s user "python3 {project_path}/server.py"

# Alternative (Local - only works from current directory)
# claude mcp add {project_name} "python3 {project_path}/server.py"

# Exit Claude Code (type 'exit' or press Ctrl+C)
# Restart Claude Code
claude

# Check that it's active
claude mcp list
# Should show: ✓ {project_name} (Active)

# 💡 Global (-s user) = Works from any directory
# 💡 Local (no flag) = Only works from current directory
```

### 3. Verify Connection
In Claude Code, type: `/mcp`
You should see: `✔ {project_name}` (connected)

"""
    
    # Add testing section with updated paths
    content += f"""
## 🧪 Testing the MCP Server

### Automated Testing
```bash
cd {root_path}

# Run the full test suite
python3 scripts/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
# ==================================================
```

### Implementation Verification
```bash
# Check for incomplete implementations
python3 scripts/verify.py

# This finds:
# - TODO/FIXME comments that need completion
# - Placeholder/mock data that needs replacing
# - Empty function implementations
# - Missing required resources
```

### Manual Testing
```bash
cd {project_path}

# Test the server directly
python3 server.py
# Should start without errors and wait for JSON-RPC input
# Press Ctrl+C to stop
```
"""
    
    # Add troubleshooting section with updated paths
    content += generate_troubleshooting_section_for_root(
        root_path, project_path, project_name, python_version
    )
    
    # Add management section with updated paths
    content += generate_management_section_for_root(project_name, project_path)
    
    # Add footer
    content += """

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


def generate_troubleshooting_section_for_root(
    root_path: Path, 
    project_path: Path, 
    project_name: str, 
    python_version: str
) -> str:
    """Generate troubleshooting section for root help.md with updated paths"""
    return f"""
## 🔧 Troubleshooting Failed MCP Connection

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

### Step 1: Run Automatic Diagnostics

We've included a diagnostic script that checks for common issues:

```bash
cd {root_path}
python3 scripts/diagnose.py
```

This will check:
- ✅ Python version compatibility
- ✅ All dependencies installed
- ✅ No print() statements breaking the protocol
- ✅ Proper logging configuration
- ✅ Server syntax and imports
- ✅ JSON-RPC compliance

Fix any ❌ failures shown, then re-run the diagnostic.

### Step 2: Manual System Diagnosis

If diagnostics pass but MCP still fails, 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 3: 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 (Global scope - recommended):
claude mcp add {project_name} -s user "python3 {project_path}/server.py"
# OR
claude mcp add {project_name} -s user "/usr/bin/python3 {project_path}/server.py"
# OR
claude mcp add {project_name} -s user "python3.11 {project_path}/server.py"

# Alternative (Local scope - only works from current directory):
# claude mcp add {project_name} -s user "python3 {project_path}/server.py"

# EXIT Claude Code and restart again
```

#### 2. Missing Dependencies
```bash
cd {project_path}

# Modern Linux (Ubuntu 22.04+, Debian 12+) - recommended method
python3 -m pip install --user --break-system-packages -r requirements.txt

# If you get "externally managed environment" error, try these options:
# Option 1: Use --break-system-packages (recommended)
python3 -m pip install --user --break-system-packages -r requirements.txt

# Option 2: Create a virtual environment (best for development)
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install -r requirements.txt

# Option 3: System packages (if available)
sudo apt install python3-fastmcp python3-httpx python3-pydantic

# Option 4: Older Linux systems
python3 -m pip install --user -r requirements.txt
```

#### 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} -s user "python3 $(pwd)/{project_path.name}/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} -s user "python3.11 {project_path}/server.py"
```

### Step 4: 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 -r requirements.txt

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

## 📋 Quick Fix Checklist

Run through this checklist when troubleshooting:

□ Run diagnostics: `cd {root_path} && python3 scripts/diagnose.py`
□ Fix any issues reported by diagnostics
□ Test manually: `cd {project_path} && python3 server.py`
□ Check Python path: `which python3`
□ Install dependencies: `cd {project_path} && pip install -r requirements.txt`
□ Use absolute paths in `claude mcp add` with `-s user` for global access
□ EXIT and restart Claude Code after EVERY change
□ Check MCP status: `claude mcp list`

## 🔍 About the Diagnostic Script

The `scripts/diagnose.py` script included in this project checks for:
- **Protocol Issues**: print() statements that break JSON-RPC
- **Dependencies**: Missing packages that prevent startup
- **Configuration**: Proper logging setup to stderr
- **Compatibility**: Python version requirements
- **Syntax**: Code errors that prevent loading

Always run diagnostics first when troubleshooting!"""


def generate_management_section_for_root(project_name: str, project_path: Path) -> str:
    """Generate MCP management section for root help.md"""
    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
pip install -r requirements.txt

# Re-add the MCP
claude mcp add {project_name} -s user "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 .
   ```

## 📝 Development Scripts

This project includes development tools in the `scripts/` directory:

- **`scripts/test.py`**: Comprehensive test suite for all MCP functionality
- **`scripts/verify.py`**: Checks for incomplete implementations and TODOs
- **`scripts/diagnose.py`**: Cross-platform diagnostic tool for troubleshooting

Always run these scripts from the root directory:
```bash
cd {project_path.parent}
python3 scripts/test.py
python3 scripts/verify.py
python3 scripts/diagnose.py
```

## 📝 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"""