"""
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 (simple README.md pointing to root)
    
    Args:
        project_path: Path to project directory
        plan: Generation plan
        project_name: Name of the project
        python_version: Python version requirement
    """
    # Create a simple README.md that points to the root documentation
    simple_readme = f"""# {project_name}

This is the MCP server directory for {project_name}.

For complete documentation, see:
- **../README.md** - Project overview and description
- **../help.md** - Comprehensive setup and troubleshooting guide

To run this MCP server, use:
```bash
./run_server.py
```
"""
    (project_path / "README.md").write_text(simple_readme)


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
- Verify all dependencies are installed  
- Test the MCP server startup
- Provide specific fix recommendations

### Step 2: Check Claude Logs

If diagnostics don't help, check the actual error:

#### macOS:
```bash
# Find and view the log
log_file=$(ls -t ~/Library/Logs/Claude/mcp*.log | head -1)
tail -50 "$log_file" | grep -A5 -B5 {project_name}
```

#### Windows:
```powershell
# In PowerShell
$log = Get-ChildItem "$env:APPDATA\\Claude\\logs\\mcp*.log" | Sort LastWriteTime -Desc | Select -First 1
Select-String -Path $log -Pattern "{project_name}" -Context 5,5
```

#### Linux:
```bash
# Find and view the log
log_file=$(ls -t ~/.config/Claude/logs/mcp*.log 2>/dev/null | head -1)
if [ -f "$log_file" ]; then
    tail -50 "$log_file" | grep -A5 -B5 {project_name}
else
    echo "No Claude logs found. Check: ~/.config/Claude/logs/"
fi
```

### Step 3: Manual Fixes Based on Common Errors

#### 1. Missing Dependencies
If you see "ModuleNotFoundError: No module named 'fastmcp'":

```bash
cd {project_path}
{python_version} -m pip install -r requirements.txt
```

#### 2. Modern Linux Installation Issues
If you see "error: externally-managed-environment":

```bash
# Option 1: User install with break-system-packages (recommended)
python3 -m pip install --user --break-system-packages -r requirements.txt

# Option 2: Virtual environment (safer but more complex)
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install -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

1. ✓ Run `python3 diagnose.py` first
2. ✓ Check Claude logs for specific error
3. ✓ Verify Python version >= {python_version}
4. ✓ Install dependencies: `pip install -r requirements.txt`
5. ✓ Use absolute paths in `claude mcp add`
6. ✓ Restart Claude Code after changes
7. ✓ Try virtual environment if all else fails

## 🚀 Still Having Issues?

1. **Run full diagnostics**: `python3 diagnose.py --verbose`
2. **Test manually**: `cd {project_path} && python3 server.py`
3. **Check GitHub Issues**: Search for similar problems in the KEN-MCP repository
4. **Report New Issue**: Include diagnostics output and error logs"""


def generate_management_section(project_name: str, project_path: Path) -> str:
    """Generate management section for help.md
    
    Args:
        project_name: Name of the project
        project_path: Path to project directory
        
    Returns:
        Management section content
    """
    return f"""
## 📦 Managing Your MCP

### Update MCP Code
After modifying the server.py:
```bash
# No reinstall needed - changes take effect after Claude restart
# Just restart Claude Code to load the new code
```

### View MCP Status
```bash
claude mcp list
# Should show: {project_name} ✓ (Active)
```

### Remove MCP
```bash
claude mcp remove {project_name}
```

### Check MCP Connection in Claude
Type `/mcp` in Claude Code to see:
- Connection status (✓ or ✗)
- Available tools
- Resource endpoints
- Any error messages"""


def generate_quick_test_section(project_path: Path, project_name: str) -> str:
    """Generate quick test section showing how to verify the MCP works
    
    Args:
        project_path: Path to project directory
        project_name: Name of the project
        
    Returns:
        Quick test section content
    """
    return f"""
## 🧪 Quick Test

After adding to Claude, test your MCP:

1. **Check connection**: Type `/mcp` - should show {project_name} as connected (✓)
2. **Test tools**: Try using one of the MCP's tools
3. **Check resources**: Access any resources provided by the MCP
4. **View logs**: If issues occur, check the Claude logs as shown above

### Manual Testing
```bash
# Test the server directly
cd {project_path}
python3 -c "from server import mcp; print('✓ Server imports successfully')"

# Run the test suite
cd ..
python3 scripts/test.py

# Check for implementation issues
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"""


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 for root directory
    """
    # Start with quick start section
    content = HELP_QUICK_START.format(
        project_name=project_name,
        project_path=project_path
    )
    
    # Replace references to scripts being in project directory
    content = content.replace("python3 diagnose.py", "python3 scripts/diagnose.py")
    content = content.replace("python3 test.py", "python3 scripts/test.py")
    content = content.replace("python3 verify.py", "python3 scripts/verify.py")
    
    # Add testing section with corrected paths
    content += "\n" + HELP_TESTING_SECTION.format(
        project_path=project_path,
        project_name=project_name
    ).replace("python3 test.py", "python3 scripts/test.py")
    
    # Add troubleshooting section
    content += "\n" + generate_troubleshooting_section(
        project_path, project_name, python_version
    ).replace("python3 diagnose.py", "python3 scripts/diagnose.py")
    
    # Add management section
    content += "\n" + generate_management_section(project_name, project_path)
    
    # Add quick test section with corrected paths
    content += "\n" + generate_quick_test_section(project_path, project_name).replace(
        "python3 scripts/test.py", "cd .. && python3 scripts/test.py"
    ).replace(
        "python3 scripts/verify.py", "python3 scripts/verify.py"
    ).replace(
        "python3 scripts/diagnose.py", "python3 scripts/diagnose.py"
    )
    
    # Add footer
    content += """

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


def generate_readme_to_root(
    root_path: Path,
    project_name: str,
    description: str
) -> None:
    """Generate README.md in root directory
    
    Args:
        root_path: Path to root directory
        project_name: Name of the project
        description: Project description
    """
    readme_content = generate_readme_content(project_name, description)
    (root_path / "README.md").write_text(readme_content)