"""
Python documentation generation logic for Storm Logger development
"""

import json
import ast
import re
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple


def generate_documentation(
    file_path: str,
    doc_type: str = "comprehensive",
    output_format: str = "markdown",
    include_examples: bool = True
) -> str:
    """
    Generate comprehensive documentation for Python code
    
    Args:
        file_path: Path to Python file or directory to document
        doc_type: "api", "readme", "docstrings", "changelog", "comprehensive"
        output_format: "markdown", "rst", "html", "json"
        include_examples: Whether to include code examples
        
    Returns:
        JSON string with generated documentation and analysis
    """
    path = Path(file_path)
    
    if not path.exists():
        return json.dumps({"error": f"Path {file_path} does not exist"}, indent=2)
    
    documentation = {
        "file_path": str(path),
        "doc_type": doc_type,
        "output_format": output_format,
        "include_examples": include_examples,
        "timestamp": "2025-01-18",
        "generated_docs": {},
        "analysis": {},
        "storm_logger_integration": {},
        "recommendations": []
    }
    
    try:
        if path.is_file():
            if path.suffix == '.py':
                file_docs = generate_file_documentation(path, doc_type, output_format, include_examples)
                documentation["generated_docs"] = file_docs
            else:
                return json.dumps({"error": f"File {file_path} is not a Python file"}, indent=2)
        else:
            project_docs = generate_project_documentation(path, doc_type, output_format, include_examples)
            documentation["generated_docs"] = project_docs
        
        # Add analysis and recommendations
        documentation["analysis"] = analyze_documentation_quality(documentation["generated_docs"])
        documentation["storm_logger_integration"] = generate_storm_logger_docs(path, doc_type)
        documentation["recommendations"] = generate_documentation_recommendations(documentation["analysis"])
        
        return json.dumps(documentation, indent=2)
        
    except Exception as e:
        return json.dumps({"error": f"Documentation generation failed: {str(e)}"}, indent=2)


def generate_file_documentation(
    file_path: Path,
    doc_type: str,
    output_format: str,
    include_examples: bool
) -> Dict[str, Any]:
    """
    Generate documentation for a single Python file
    
    Args:
        file_path: Path to Python file
        doc_type: Type of documentation
        output_format: Output format
        include_examples: Whether to include examples
        
    Returns:
        File documentation results
    """
    try:
        content = file_path.read_text(encoding='utf-8')
        tree = ast.parse(content)
    except Exception as e:
        return {"error": f"Cannot parse file {file_path}: {str(e)}"}
    
    file_docs = {
        "file_name": file_path.name,
        "module_docstring": ast.get_docstring(tree) or "",
        "classes": [],
        "functions": [],
        "constants": [],
        "imports": [],
        "api_documentation": "",
        "examples": []
    }
    
    # Extract documentation elements
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            class_doc = extract_class_documentation(node, content, include_examples)
            file_docs["classes"].append(class_doc)
        elif isinstance(node, ast.FunctionDef):
            func_doc = extract_function_documentation(node, content, include_examples)
            file_docs["functions"].append(func_doc)
        elif isinstance(node, ast.Assign):
            const_doc = extract_constant_documentation(node, content)
            if const_doc:
                file_docs["constants"].append(const_doc)
        elif isinstance(node, (ast.Import, ast.ImportFrom)):
            import_doc = extract_import_documentation(node)
            file_docs["imports"].append(import_doc)
    
    # Generate formatted documentation
    if doc_type == "api":
        file_docs["api_documentation"] = generate_api_documentation(file_docs, output_format)
    elif doc_type == "docstrings":
        file_docs["docstring_improvements"] = generate_docstring_improvements(file_docs)
    elif doc_type == "comprehensive":
        file_docs["api_documentation"] = generate_api_documentation(file_docs, output_format)
        file_docs["docstring_improvements"] = generate_docstring_improvements(file_docs)
        file_docs["usage_examples"] = generate_usage_examples(file_docs)
    
    return file_docs


def generate_project_documentation(
    project_path: Path,
    doc_type: str,
    output_format: str,
    include_examples: bool
) -> Dict[str, Any]:
    """
    Generate documentation for a project directory
    
    Args:
        project_path: Path to project directory
        doc_type: Type of documentation
        output_format: Output format
        include_examples: Whether to include examples
        
    Returns:
        Project documentation results
    """
    python_files = list(project_path.glob("**/*.py"))
    
    if not python_files:
        return {"error": f"No Python files found in {project_path}"}
    
    project_docs = {
        "project_name": project_path.name,
        "total_files": len(python_files),
        "modules": [],
        "project_structure": {},
        "readme_content": "",
        "api_overview": "",
        "installation_guide": "",
        "usage_examples": []
    }
    
    # Process each Python file
    for py_file in python_files[:10]:  # Limit to first 10 files for performance
        try:
            file_docs = generate_file_documentation(py_file, doc_type, output_format, include_examples)
            if "error" not in file_docs:
                project_docs["modules"].append({
                    "file_path": str(py_file.relative_to(project_path)),
                    "documentation": file_docs
                })
        except Exception as e:
            project_docs["modules"].append({
                "file_path": str(py_file.relative_to(project_path)),
                "error": str(e)
            })
    
    # Generate project-level documentation
    project_docs["project_structure"] = analyze_project_structure(project_path)
    
    if doc_type in ["readme", "comprehensive"]:
        project_docs["readme_content"] = generate_readme_content(project_docs, output_format)
    
    if doc_type in ["api", "comprehensive"]:
        project_docs["api_overview"] = generate_project_api_overview(project_docs, output_format)
    
    if doc_type == "comprehensive":
        project_docs["installation_guide"] = generate_installation_guide(project_path, output_format)
        project_docs["usage_examples"] = generate_project_usage_examples(project_docs)
    
    return project_docs


def extract_class_documentation(
    node: ast.ClassDef,
    content: str,
    include_examples: bool
) -> Dict[str, Any]:
    """
    Extract documentation for a class
    
    Args:
        node: Class AST node
        content: File content
        include_examples: Whether to include examples
        
    Returns:
        Class documentation
    """
    class_doc = {
        "name": node.name,
        "line": node.lineno,
        "docstring": ast.get_docstring(node) or "",
        "methods": [],
        "attributes": [],
        "inheritance": [base.id if isinstance(base, ast.Name) else str(base) for base in node.bases],
        "decorators": [d.id if isinstance(d, ast.Name) else str(d) for d in node.decorator_list],
        "examples": []
    }
    
    # Extract methods
    for item in node.body:
        if isinstance(item, ast.FunctionDef):
            method_doc = extract_function_documentation(item, content, include_examples)
            class_doc["methods"].append(method_doc)
        elif isinstance(item, ast.Assign):
            attr_doc = extract_attribute_documentation(item, content)
            if attr_doc:
                class_doc["attributes"].append(attr_doc)
    
    # Generate examples if requested
    if include_examples:
        class_doc["examples"] = generate_class_examples(class_doc)
    
    return class_doc


def extract_function_documentation(
    node: ast.FunctionDef,
    content: str,
    include_examples: bool
) -> Dict[str, Any]:
    """
    Extract documentation for a function
    
    Args:
        node: Function AST node
        content: File content
        include_examples: Whether to include examples
        
    Returns:
        Function documentation
    """
    func_doc = {
        "name": node.name,
        "line": node.lineno,
        "docstring": ast.get_docstring(node) or "",
        "parameters": [],
        "return_type": node.returns.id if isinstance(node.returns, ast.Name) else str(node.returns) if node.returns else None,
        "decorators": [d.id if isinstance(d, ast.Name) else str(d) for d in node.decorator_list],
        "is_async": isinstance(node, ast.AsyncFunctionDef),
        "is_method": False,  # Will be set by caller if in class
        "complexity": calculate_function_complexity(node),
        "examples": []
    }
    
    # Extract parameters
    for arg in node.args.args:
        param_doc = {
            "name": arg.arg,
            "type": arg.annotation.id if isinstance(arg.annotation, ast.Name) else str(arg.annotation) if arg.annotation else None,
            "default": None  # TODO: Extract default values
        }
        func_doc["parameters"].append(param_doc)
    
    # Generate examples if requested
    if include_examples:
        func_doc["examples"] = generate_function_examples(func_doc)
    
    return func_doc


def extract_constant_documentation(
    node: ast.Assign,
    content: str
) -> Optional[Dict[str, Any]]:
    """
    Extract documentation for constants
    
    Args:
        node: Assignment AST node
        content: File content
        
    Returns:
        Constant documentation or None
    """
    if len(node.targets) != 1:
        return None
    
    target = node.targets[0]
    if not isinstance(target, ast.Name):
        return None
    
    # Check if it's a constant (uppercase name)
    if not target.id.isupper():
        return None
    
    const_doc = {
        "name": target.id,
        "line": node.lineno,
        "value": get_constant_value(node.value),
        "type": type(node.value).__name__,
        "comment": extract_inline_comment(node.lineno, content)
    }
    
    return const_doc


def extract_attribute_documentation(
    node: ast.Assign,
    content: str
) -> Optional[Dict[str, Any]]:
    """
    Extract documentation for class attributes
    
    Args:
        node: Assignment AST node
        content: File content
        
    Returns:
        Attribute documentation or None
    """
    if len(node.targets) != 1:
        return None
    
    target = node.targets[0]
    if not isinstance(target, ast.Name):
        return None
    
    attr_doc = {
        "name": target.id,
        "line": node.lineno,
        "type": type(node.value).__name__,
        "comment": extract_inline_comment(node.lineno, content)
    }
    
    return attr_doc


def extract_import_documentation(node: ast.AST) -> Dict[str, Any]:
    """
    Extract documentation for imports
    
    Args:
        node: Import AST node
        
    Returns:
        Import documentation
    """
    if isinstance(node, ast.Import):
        return {
            "type": "import",
            "modules": [alias.name for alias in node.names],
            "line": node.lineno
        }
    else:  # ast.ImportFrom
        return {
            "type": "from_import",
            "module": node.module,
            "names": [alias.name for alias in node.names],
            "line": node.lineno
        }


def calculate_function_complexity(node: ast.FunctionDef) -> int:
    """
    Calculate cyclomatic complexity of a function
    
    Args:
        node: Function AST node
        
    Returns:
        Complexity score
    """
    complexity = 1  # Base complexity
    
    for child in ast.walk(node):
        if isinstance(child, (ast.If, ast.While, ast.For, ast.Try)):
            complexity += 1
        elif isinstance(child, ast.ExceptHandler):
            complexity += 1
        elif isinstance(child, ast.BoolOp):
            complexity += len(child.values) - 1
    
    return complexity


def get_constant_value(node: ast.AST) -> str:
    """
    Extract string representation of constant value
    
    Args:
        node: AST node
        
    Returns:
        String representation of value
    """
    if isinstance(node, ast.Constant):
        return repr(node.value)
    elif isinstance(node, ast.Name):
        return node.id
    elif isinstance(node, ast.List):
        return f"[{len(node.elts)} items]"
    elif isinstance(node, ast.Dict):
        return f"{{{len(node.keys)} items}}"
    else:
        return str(node)


def extract_inline_comment(line_no: int, content: str) -> Optional[str]:
    """
    Extract inline comment from a line
    
    Args:
        line_no: Line number
        content: File content
        
    Returns:
        Comment text or None
    """
    lines = content.splitlines()
    if line_no <= len(lines):
        line = lines[line_no - 1]
        if '#' in line:
            return line.split('#', 1)[1].strip()
    return None


def generate_api_documentation(
    file_docs: Dict[str, Any],
    output_format: str
) -> str:
    """
    Generate API documentation
    
    Args:
        file_docs: File documentation data
        output_format: Output format
        
    Returns:
        Formatted API documentation
    """
    if output_format == "markdown":
        return generate_markdown_api_docs(file_docs)
    elif output_format == "rst":
        return generate_rst_api_docs(file_docs)
    elif output_format == "html":
        return generate_html_api_docs(file_docs)
    else:
        return json.dumps(file_docs, indent=2)


def generate_markdown_api_docs(file_docs: Dict[str, Any]) -> str:
    """
    Generate Markdown API documentation
    
    Args:
        file_docs: File documentation data
        
    Returns:
        Markdown formatted documentation
    """
    md_content = f"# {file_docs['file_name']}\n\n"
    
    if file_docs['module_docstring']:
        md_content += f"{file_docs['module_docstring']}\n\n"
    
    # Classes
    if file_docs['classes']:
        md_content += "## Classes\n\n"
        for class_doc in file_docs['classes']:
            md_content += f"### {class_doc['name']}\n\n"
            if class_doc['docstring']:
                md_content += f"{class_doc['docstring']}\n\n"
            
            if class_doc['inheritance']:
                md_content += f"**Inherits from:** {', '.join(class_doc['inheritance'])}\n\n"
            
            # Methods
            if class_doc['methods']:
                md_content += "#### Methods\n\n"
                for method in class_doc['methods']:
                    md_content += f"##### {method['name']}\n\n"
                    if method['docstring']:
                        md_content += f"{method['docstring']}\n\n"
                    
                    if method['parameters']:
                        md_content += "**Parameters:**\n"
                        for param in method['parameters']:
                            param_type = f" ({param['type']})" if param['type'] else ""
                            md_content += f"- `{param['name']}`{param_type}\n"
                        md_content += "\n"
    
    # Functions
    if file_docs['functions']:
        md_content += "## Functions\n\n"
        for func_doc in file_docs['functions']:
            md_content += f"### {func_doc['name']}\n\n"
            if func_doc['docstring']:
                md_content += f"{func_doc['docstring']}\n\n"
            
            if func_doc['parameters']:
                md_content += "**Parameters:**\n"
                for param in func_doc['parameters']:
                    param_type = f" ({param['type']})" if param['type'] else ""
                    md_content += f"- `{param['name']}`{param_type}\n"
                md_content += "\n"
            
            if func_doc['return_type']:
                md_content += f"**Returns:** {func_doc['return_type']}\n\n"
    
    # Constants
    if file_docs['constants']:
        md_content += "## Constants\n\n"
        for const_doc in file_docs['constants']:
            md_content += f"### {const_doc['name']}\n\n"
            md_content += f"**Value:** `{const_doc['value']}`\n\n"
            if const_doc['comment']:
                md_content += f"{const_doc['comment']}\n\n"
    
    return md_content


def generate_rst_api_docs(file_docs: Dict[str, Any]) -> str:
    """
    Generate reStructuredText API documentation
    
    Args:
        file_docs: File documentation data
        
    Returns:
        RST formatted documentation
    """
    rst_content = f"{file_docs['file_name']}\n"
    rst_content += "=" * len(file_docs['file_name']) + "\n\n"
    
    if file_docs['module_docstring']:
        rst_content += f"{file_docs['module_docstring']}\n\n"
    
    # Classes
    if file_docs['classes']:
        rst_content += "Classes\n"
        rst_content += "-------\n\n"
        for class_doc in file_docs['classes']:
            rst_content += f"{class_doc['name']}\n"
            rst_content += "~" * len(class_doc['name']) + "\n\n"
            if class_doc['docstring']:
                rst_content += f"{class_doc['docstring']}\n\n"
    
    # Functions
    if file_docs['functions']:
        rst_content += "Functions\n"
        rst_content += "---------\n\n"
        for func_doc in file_docs['functions']:
            rst_content += f"{func_doc['name']}\n"
            rst_content += "~" * len(func_doc['name']) + "\n\n"
            if func_doc['docstring']:
                rst_content += f"{func_doc['docstring']}\n\n"
    
    return rst_content


def generate_html_api_docs(file_docs: Dict[str, Any]) -> str:
    """
    Generate HTML API documentation
    
    Args:
        file_docs: File documentation data
        
    Returns:
        HTML formatted documentation
    """
    html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>{file_docs['file_name']} API Documentation</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; }}
        h1, h2, h3 {{ color: #333; }}
        .class {{ background-color: #f8f9fa; padding: 20px; margin: 20px 0; border-radius: 5px; }}
        .function {{ background-color: #e9ecef; padding: 15px; margin: 15px 0; border-radius: 5px; }}
        .parameter {{ color: #007bff; }}
        .docstring {{ font-style: italic; color: #6c757d; }}
    </style>
</head>
<body>
    <h1>{file_docs['file_name']}</h1>
    
    {f'<p class="docstring">{file_docs["module_docstring"]}</p>' if file_docs["module_docstring"] else ''}
"""
    
    # Classes
    if file_docs['classes']:
        html_content += "<h2>Classes</h2>\n"
        for class_doc in file_docs['classes']:
            html_content += f'<div class="class">\n'
            html_content += f'<h3>{class_doc["name"]}</h3>\n'
            if class_doc['docstring']:
                html_content += f'<p class="docstring">{class_doc["docstring"]}</p>\n'
            html_content += '</div>\n'
    
    # Functions
    if file_docs['functions']:
        html_content += "<h2>Functions</h2>\n"
        for func_doc in file_docs['functions']:
            html_content += f'<div class="function">\n'
            html_content += f'<h3>{func_doc["name"]}</h3>\n'
            if func_doc['docstring']:
                html_content += f'<p class="docstring">{func_doc["docstring"]}</p>\n'
            html_content += '</div>\n'
    
    html_content += """
</body>
</html>
"""
    
    return html_content


def generate_docstring_improvements(file_docs: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    Generate suggestions for improving docstrings
    
    Args:
        file_docs: File documentation data
        
    Returns:
        List of improvement suggestions
    """
    improvements = []
    
    # Check module docstring
    if not file_docs['module_docstring']:
        improvements.append({
            "type": "module_docstring",
            "line": 1,
            "severity": "high",
            "message": "Module is missing a docstring",
            "suggestion": "Add a module-level docstring describing the module's purpose"
        })
    
    # Check class docstrings
    for class_doc in file_docs['classes']:
        if not class_doc['docstring']:
            improvements.append({
                "type": "class_docstring",
                "line": class_doc['line'],
                "severity": "high",
                "message": f"Class {class_doc['name']} is missing a docstring",
                "suggestion": "Add a class docstring describing the class purpose and usage"
            })
    
    # Check function docstrings
    for func_doc in file_docs['functions']:
        if not func_doc['docstring']:
            improvements.append({
                "type": "function_docstring",
                "line": func_doc['line'],
                "severity": "medium",
                "message": f"Function {func_doc['name']} is missing a docstring",
                "suggestion": "Add a function docstring with Args, Returns, and description"
            })
        elif func_doc['parameters'] and 'Args:' not in func_doc['docstring']:
            improvements.append({
                "type": "docstring_format",
                "line": func_doc['line'],
                "severity": "low",
                "message": f"Function {func_doc['name']} docstring missing Args section",
                "suggestion": "Add Args section to document parameters"
            })
    
    return improvements


def generate_usage_examples(file_docs: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    Generate usage examples for classes and functions
    
    Args:
        file_docs: File documentation data
        
    Returns:
        List of usage examples
    """
    examples = []
    
    # Generate class examples
    for class_doc in file_docs['classes']:
        example = {
            "type": "class_usage",
            "name": class_doc['name'],
            "code": f"""
# Create instance of {class_doc['name']}
instance = {class_doc['name']}()

# Example usage
# TODO: Add specific usage examples
"""
        }
        examples.append(example)
    
    # Generate function examples
    for func_doc in file_docs['functions']:
        if not func_doc['name'].startswith('_'):  # Skip private functions
            params = ', '.join([f"{p['name']}" for p in func_doc['parameters']])
            example = {
                "type": "function_usage",
                "name": func_doc['name'],
                "code": f"""
# Call {func_doc['name']} function
result = {func_doc['name']}({params})
"""
            }
            examples.append(example)
    
    return examples


def generate_class_examples(class_doc: Dict[str, Any]) -> List[str]:
    """
    Generate usage examples for a class
    
    Args:
        class_doc: Class documentation
        
    Returns:
        List of example code strings
    """
    examples = []
    
    # Basic instantiation
    examples.append(f"# Create an instance of {class_doc['name']}\ninstance = {class_doc['name']}()")
    
    # Method usage examples
    for method in class_doc['methods']:
        if not method['name'].startswith('_') and method['name'] != '__init__':
            params = ', '.join([f"{p['name']}" for p in method['parameters']])
            examples.append(f"# Call {method['name']} method\nresult = instance.{method['name']}({params})")
    
    return examples


def generate_function_examples(func_doc: Dict[str, Any]) -> List[str]:
    """
    Generate usage examples for a function
    
    Args:
        func_doc: Function documentation
        
    Returns:
        List of example code strings
    """
    examples = []
    
    # Basic function call
    params = ', '.join([f"{p['name']}" for p in func_doc['parameters']])
    examples.append(f"# Call {func_doc['name']} function\nresult = {func_doc['name']}({params})")
    
    # With example values
    if func_doc['parameters']:
        example_params = []
        for param in func_doc['parameters']:
            if param['type'] == 'str':
                example_params.append(f'{param["name"]}="example"')
            elif param['type'] == 'int':
                example_params.append(f'{param["name"]}=42')
            elif param['type'] == 'bool':
                example_params.append(f'{param["name"]}=True')
            else:
                example_params.append(f'{param["name"]}=None')
        
        examples.append(f"# Example with values\nresult = {func_doc['name']}({', '.join(example_params)})")
    
    return examples


def generate_readme_content(project_docs: Dict[str, Any], output_format: str) -> str:
    """
    Generate README content for a project
    
    Args:
        project_docs: Project documentation data
        output_format: Output format
        
    Returns:
        README content
    """
    readme_content = f"""# {project_docs['project_name']}

## Overview

This project contains {project_docs['total_files']} Python files with comprehensive Storm Logger integration.

## Installation

```bash
pip install storm-logger
pip install -r requirements.txt
```

## Quick Start

```python
from storm_logger import StormLogger

# Initialize logger
logger = StormLogger()
logger.info("Application started")
```

## Project Structure

```
{project_docs['project_name']}/
├── src/
│   └── {project_docs['project_name']}/
│       ├── __init__.py
│       ├── main.py
│       └── ...
├── tests/
│   ├── unit/
│   ├── integration/
│   └── functional/
├── docs/
├── requirements.txt
└── README.md
```

## API Documentation

{generate_project_api_summary(project_docs)}

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License
"""
    
    return readme_content


def generate_project_api_overview(project_docs: Dict[str, Any], output_format: str) -> str:
    """
    Generate project API overview
    
    Args:
        project_docs: Project documentation data
        output_format: Output format
        
    Returns:
        API overview content
    """
    overview = f"# {project_docs['project_name']} API Overview\n\n"
    
    total_classes = 0
    total_functions = 0
    
    for module in project_docs['modules']:
        if 'documentation' in module:
            docs = module['documentation']
            total_classes += len(docs.get('classes', []))
            total_functions += len(docs.get('functions', []))
    
    overview += f"## Summary\n\n"
    overview += f"- **Total Modules**: {len(project_docs['modules'])}\n"
    overview += f"- **Total Classes**: {total_classes}\n"
    overview += f"- **Total Functions**: {total_functions}\n\n"
    
    overview += "## Modules\n\n"
    for module in project_docs['modules']:
        if 'documentation' in module:
            docs = module['documentation']
            overview += f"### {module['file_path']}\n\n"
            if docs.get('module_docstring'):
                overview += f"{docs['module_docstring']}\n\n"
    
    return overview


def generate_project_api_summary(project_docs: Dict[str, Any]) -> str:
    """
    Generate a brief API summary for README
    
    Args:
        project_docs: Project documentation data
        
    Returns:
        API summary content
    """
    summary = "### Available Components\n\n"
    
    for module in project_docs['modules']:
        if 'documentation' in module:
            docs = module['documentation']
            if docs.get('classes'):
                summary += f"**{module['file_path']}**\n"
                for class_doc in docs['classes']:
                    summary += f"- `{class_doc['name']}`: {class_doc['docstring'][:100]}...\n"
                summary += "\n"
    
    return summary


def generate_installation_guide(project_path: Path, output_format: str) -> str:
    """
    Generate installation guide
    
    Args:
        project_path: Project path
        output_format: Output format
        
    Returns:
        Installation guide content
    """
    guide = """# Installation Guide

## Prerequisites

- Python 3.10 or higher
- pip package manager

## Installation Steps

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd {project_name}
   ```

2. **Create virtual environment**
   ```bash
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\\Scripts\\activate
   ```

3. **Install dependencies**
   ```bash
   pip install -r requirements.txt
   ```

4. **Install Storm Logger**
   ```bash
   pip install storm-logger
   ```

5. **Run tests**
   ```bash
   pytest tests/
   ```

## Configuration

Set up environment variables:
```bash
export STORM_LOGGER_LEVEL=INFO
export STORM_LOGGER_FORMAT=json
```

## Verification

```python
from storm_logger import StormLogger
logger = StormLogger()
logger.info("Installation successful!")
```
""".format(project_name=project_path.name)
    
    return guide


def generate_project_usage_examples(project_docs: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    Generate usage examples for the project
    
    Args:
        project_docs: Project documentation data
        
    Returns:
        List of usage examples
    """
    examples = []
    
    # Basic usage example
    examples.append({
        "title": "Basic Usage",
        "description": "Basic project setup and usage",
        "code": f"""
from storm_logger import StormLogger
from {project_docs['project_name']} import main

# Initialize logger
logger = StormLogger()

# Run main application
main()
"""
    })
    
    # Advanced usage example
    examples.append({
        "title": "Advanced Usage",
        "description": "Advanced features and configuration",
        "code": f"""
from storm_logger import StormLogger, StormLoggerConfig
from {project_docs['project_name']} import advanced_features

# Configure logger
config = StormLoggerConfig(
    level="DEBUG",
    format="json",
    enable_metrics=True
)
logger = StormLogger(config)

# Use advanced features
result = advanced_features.process_data(logger)
"""
    })
    
    return examples


def analyze_project_structure(project_path: Path) -> Dict[str, Any]:
    """
    Analyze project structure
    
    Args:
        project_path: Project path
        
    Returns:
        Project structure analysis
    """
    structure = {
        "directories": [],
        "python_files": [],
        "config_files": [],
        "documentation_files": [],
        "test_files": []
    }
    
    for item in project_path.rglob("*"):
        if item.is_dir():
            structure["directories"].append(str(item.relative_to(project_path)))
        elif item.suffix == ".py":
            if "test" in item.name.lower():
                structure["test_files"].append(str(item.relative_to(project_path)))
            else:
                structure["python_files"].append(str(item.relative_to(project_path)))
        elif item.suffix in [".md", ".rst", ".txt"]:
            structure["documentation_files"].append(str(item.relative_to(project_path)))
        elif item.name in ["pyproject.toml", "setup.py", "requirements.txt", ".gitignore"]:
            structure["config_files"].append(str(item.relative_to(project_path)))
    
    return structure


def analyze_documentation_quality(generated_docs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Analyze documentation quality
    
    Args:
        generated_docs: Generated documentation data
        
    Returns:
        Quality analysis
    """
    analysis = {
        "overall_score": 0,
        "completeness": {},
        "quality_metrics": {},
        "improvement_areas": []
    }
    
    if "modules" in generated_docs:
        # Project-level analysis
        total_modules = len(generated_docs["modules"])
        modules_with_docstrings = sum(1 for m in generated_docs["modules"] 
                                     if m.get("documentation", {}).get("module_docstring"))
        
        analysis["completeness"]["module_docstrings"] = {
            "total": total_modules,
            "documented": modules_with_docstrings,
            "percentage": (modules_with_docstrings / total_modules * 100) if total_modules > 0 else 0
        }
    else:
        # Single file analysis
        classes = generated_docs.get("classes", [])
        functions = generated_docs.get("functions", [])
        
        classes_with_docstrings = sum(1 for c in classes if c.get("docstring"))
        functions_with_docstrings = sum(1 for f in functions if f.get("docstring"))
        
        analysis["completeness"]["class_docstrings"] = {
            "total": len(classes),
            "documented": classes_with_docstrings,
            "percentage": (classes_with_docstrings / len(classes) * 100) if classes else 0
        }
        
        analysis["completeness"]["function_docstrings"] = {
            "total": len(functions),
            "documented": functions_with_docstrings,
            "percentage": (functions_with_docstrings / len(functions) * 100) if functions else 0
        }
    
    # Calculate overall score
    completeness_scores = [item["percentage"] for item in analysis["completeness"].values()]
    analysis["overall_score"] = sum(completeness_scores) / len(completeness_scores) if completeness_scores else 0
    
    return analysis


def generate_storm_logger_docs(path: Path, doc_type: str) -> Dict[str, Any]:
    """
    Generate Storm Logger specific documentation
    
    Args:
        path: File or project path
        doc_type: Documentation type
        
    Returns:
        Storm Logger documentation
    """
    storm_docs = {
        "integration_guide": generate_storm_logger_integration_guide(),
        "configuration_examples": generate_storm_logger_config_examples(),
        "best_practices": generate_storm_logger_best_practices(),
        "troubleshooting": generate_storm_logger_troubleshooting()
    }
    
    return storm_docs


def generate_storm_logger_integration_guide() -> str:
    """
    Generate Storm Logger integration guide
    
    Returns:
        Integration guide content
    """
    guide = """# Storm Logger Integration Guide

## Basic Setup

```python
from storm_logger import StormLogger

# Initialize logger
logger = StormLogger()
logger.info("Application started")
```

## Professional Setup

```python
from storm_logger.professional_logger import ProfessionalStormLogger
from storm_logger.config import StormLoggerConfig

config = StormLoggerConfig(
    level="INFO",
    format="json",
    enable_console=True,
    enable_metrics=True
)

logger = ProfessionalStormLogger(config)
```

## Business Event Tracking

```python
logger.track_business_event("user_registration", {
    "user_id": 123,
    "registration_method": "email",
    "timestamp": "2025-01-18T10:30:00Z"
})
```

## Error Handling

```python
try:
    risky_operation()
except Exception as e:
    logger.error("Operation failed", exc_info=True, extra={
        "error_type": type(e).__name__,
        "operation": "risky_operation"
    })
```
"""
    
    return guide


def generate_storm_logger_config_examples() -> str:
    """
    Generate Storm Logger configuration examples
    
    Returns:
        Configuration examples
    """
    examples = """# Storm Logger Configuration Examples

## Environment Variables

```bash
# Basic configuration
export STORM_LOGGER_LEVEL=INFO
export STORM_LOGGER_FORMAT=json

# Console configuration
export STORM_CONSOLE_THEME=midnight
export STORM_CONSOLE_WIDTH=120

# Feature flags
export STORM_ENABLE_METRICS=true
export STORM_ENABLE_SANITIZATION=true
```

## Python Configuration

```python
from storm_logger.config import StormLoggerConfig

config = StormLoggerConfig(
    level="DEBUG",
    format="json",
    enable_console=True,
    enable_metrics=True,
    enable_sanitization=True,
    console_theme="midnight",
    console_width=120
)
```

## Django Integration

```python
# settings.py
STORM_LOGGER = {
    'level': 'INFO',
    'format': 'json',
    'enable_console': True,
    'enable_metrics': True,
    'handlers': ['console', 'file', 'database']
}
```
"""
    
    return examples


def generate_storm_logger_best_practices() -> str:
    """
    Generate Storm Logger best practices
    
    Returns:
        Best practices content
    """
    practices = """# Storm Logger Best Practices

## Logging Levels

- **DEBUG**: Detailed debugging information
- **INFO**: General information about application flow
- **WARNING**: Something unexpected happened
- **ERROR**: Serious problem occurred
- **CRITICAL**: Very serious error occurred

## Structured Logging

```python
# Good
logger.info("User logged in", extra={
    "user_id": user.id,
    "login_method": "oauth",
    "ip_address": request.remote_addr
})

# Bad
logger.info(f"User {user.id} logged in via {method}")
```

## Business Event Tracking

```python
# Track meaningful business events
logger.track_business_event("purchase_completed", {
    "user_id": user.id,
    "order_id": order.id,
    "amount": order.total,
    "currency": "USD"
})
```

## Error Context

```python
# Include relevant context with errors
try:
    process_order(order)
except Exception as e:
    logger.error("Order processing failed", extra={
        "order_id": order.id,
        "user_id": order.user_id,
        "error_type": type(e).__name__
    })
```
"""
    
    return practices


def generate_storm_logger_troubleshooting() -> str:
    """
    Generate Storm Logger troubleshooting guide
    
    Returns:
        Troubleshooting guide
    """
    guide = """# Storm Logger Troubleshooting

## Common Issues

### 1. Logger Not Outputting
- Check log level configuration
- Verify handler configuration
- Ensure proper initialization

### 2. Console Not Showing Colors
- Check if running in TTY environment
- Verify STORM_CONSOLE_NO_COLOR setting
- Check terminal color support

### 3. Metrics Not Collecting
- Ensure STORM_ENABLE_METRICS=true
- Check metrics collector initialization
- Verify business event tracking calls

### 4. Performance Issues
- Review log level settings
- Check for excessive logging
- Consider async logging for high-volume applications

## Debug Mode

```python
import storm_logger
storm_logger.enable_debug_mode()
```

## Support

- Documentation: https://docs.stormdevelopment.com/storm-logger
- Issues: GitHub Issues
- Email: support@stormdevelopment.com
"""
    
    return guide


def generate_documentation_recommendations(analysis: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    Generate documentation improvement recommendations
    
    Args:
        analysis: Documentation quality analysis
        
    Returns:
        List of recommendations
    """
    recommendations = []
    
    overall_score = analysis.get("overall_score", 0)
    
    if overall_score < 70:
        recommendations.append({
            "priority": "high",
            "category": "completeness",
            "title": "Improve Documentation Coverage",
            "description": "Documentation coverage is below 70%. Focus on adding docstrings to classes and functions.",
            "action_items": [
                "Add module-level docstrings",
                "Document all public classes",
                "Document all public functions",
                "Add parameter and return type documentation"
            ]
        })
    
    if overall_score < 90:
        recommendations.append({
            "priority": "medium",
            "category": "quality",
            "title": "Enhance Documentation Quality",
            "description": "Consider adding examples and improving docstring format.",
            "action_items": [
                "Add usage examples",
                "Follow Google docstring format",
                "Include type hints",
                "Add exception documentation"
            ]
        })
    
    recommendations.append({
        "priority": "low",
        "category": "automation",
        "title": "Automate Documentation Generation",
        "description": "Set up automated documentation generation in CI/CD pipeline.",
        "action_items": [
            "Configure Sphinx for API documentation",
            "Set up automated README generation",
            "Add documentation tests",
            "Configure GitHub Pages for docs hosting"
        ]
    })
    
    return recommendations