#!/usr/bin/env python3
"""
Doc Generator Skill - README Generator
=====================================
Auto-generate or update README.md from project analysis.
"""

import json
import subprocess
import sys
from pathlib import Path
from datetime import datetime

def generate_readme():
    """Generate comprehensive README.md from project analysis."""
    print("📖 Generating README.md from project analysis...")
    
    # Run main generator to analyze project
    generate_script = Path(__file__).parent / "generate.py"
    result = subprocess.run([sys.executable, str(generate_script), "all", "."], 
                          capture_output=True, text=True)
    
    # Load generated documentation
    docs_path = Path("docs/generated/documentation-all.json")
    if docs_path.exists():
        with open(docs_path) as f:
            docs = json.load(f)
    else:
        print("⚠️ No documentation data found, creating basic README")
        docs = {"modules": [], "functions": [], "classes": [], "apis": []}
    
    project_name = Path.cwd().name
    
    # Generate comprehensive README
    readme_content = f"""# {project_name}

{_generate_description(docs, project_name)}

## 🚀 Quick Start

```bash
# Install dependencies
pip install -r requirements.txt

# Run the application
python main.py
```

{_generate_features_section(docs)}

{_generate_api_section(docs)}

{_generate_structure_section(docs)}

{_generate_usage_section(docs)}

{_generate_development_section(docs)}

## 📊 Project Stats

- **Modules:** {len(docs.get('modules', []))}
- **Functions:** {len(docs.get('functions', []))}
- **Classes:** {len(docs.get('classes', []))}
- **API Endpoints:** {len(docs.get('apis', []))}

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📝 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

*README generated by MyWork-AI Doc Generator on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""
    
    # Save README
    readme_path = Path("README.md")
    
    # Check if README already exists
    if readme_path.exists():
        response = input(f"README.md already exists. Overwrite? (y/N): ")
        if response.lower() != 'y':
            readme_path = Path("README-generated.md")
            print(f"💡 Saving to {readme_path} instead")
    
    with open(readme_path, 'w') as f:
        f.write(readme_content)
    
    print(f"✅ README generated: {readme_path}")
    line_count = len(readme_content.split('\n'))
    print(f"📊 Generated {line_count} lines of documentation")
    
    return 0

def _generate_description(docs, project_name):
    """Generate project description from analysis."""
    # Look for existing description in main module
    main_modules = [m for m in docs.get('modules', []) if 'main' in m.get('file', '').lower()]
    
    if main_modules and main_modules[0].get('docstring'):
        return main_modules[0]['docstring'].split('\\n')[0]
    
    # Generate based on project structure
    if docs.get('apis'):
        return f"A web API application with {len(docs['apis'])} endpoints."
    elif any('flask' in str(f).lower() for f in docs.get('functions', [])):
        return "A Flask web application."
    elif any('fastapi' in str(f).lower() for f in docs.get('functions', [])):
        return "A FastAPI web application."
    else:
        return f"A Python application with {len(docs.get('functions', []))} functions and {len(docs.get('classes', []))} classes."

def _generate_features_section(docs):
    """Generate features section based on code analysis."""
    features = []
    
    # Detect features from function names and APIs
    function_names = [f.get('name', '') for f in docs.get('functions', [])]
    
    if any('auth' in name.lower() for name in function_names):
        features.append("🔐 Authentication system")
    if any('api' in name.lower() for name in function_names):
        features.append("🔗 RESTful API")
    if any('db' in name.lower() or 'database' in name.lower() for name in function_names):
        features.append("🗄️ Database integration")
    if any('test' in name.lower() for name in function_names):
        features.append("🧪 Comprehensive testing")
    if docs.get('apis'):
        features.append(f"📡 {len(docs['apis'])} API endpoints")
    
    if features:
        return f"""## ✨ Features

{chr(10).join(f'- {feature}' for feature in features)}
"""
    return ""

def _generate_api_section(docs):
    """Generate API documentation section."""
    apis = docs.get('apis', [])
    if not apis:
        return ""
    
    api_section = "## 🔗 API Endpoints\\n\\n"
    
    methods_grouped = {}
    for api in apis:
        if 'endpoint' in api:
            method = api.get('method', 'GET')
            endpoint = api['endpoint']
            desc = api.get('description', '').replace('\\n', ' ').strip()
            
            if method not in methods_grouped:
                methods_grouped[method] = []
            methods_grouped[method].append((endpoint, desc))
    
    for method, endpoints in methods_grouped.items():
        api_section += f"### {method} Endpoints\\n\\n"
        for endpoint, desc in endpoints:
            api_section += f"- `{method} {endpoint}`"
            if desc:
                api_section += f" - {desc[:100]}"
            api_section += "\\n"
        api_section += "\\n"
    
    return api_section

def _generate_structure_section(docs):
    """Generate project structure section."""
    if not docs.get('modules'):
        return ""
    
    structure = "## 📁 Project Structure\\n\\n```\\n"
    
    # Group by directory
    dirs = {}
    for module in docs['modules']:
        file_path = Path(module['file'])
        dir_name = str(file_path.parent) if file_path.parent != Path('.') else 'root'
        
        if dir_name not in dirs:
            dirs[dir_name] = []
        dirs[dir_name].append(file_path.name)
    
    for dir_name, files in dirs.items():
        if dir_name != 'root':
            structure += f"{dir_name}/\\n"
            for file in files:
                structure += f"  ├── {file}\\n"
        else:
            for file in files:
                structure += f"{file}\\n"
    
    structure += "```\\n\\n"
    return structure

def _generate_usage_section(docs):
    """Generate usage examples section."""
    # Look for main functions or app initialization
    main_functions = [f for f in docs.get('functions', []) if f.get('name') in ['main', 'run', 'app', 'start']]
    
    if main_functions:
        usage = "## 🔧 Usage\\n\\n"
        for func in main_functions[:3]:  # Limit to first 3
            if func.get('docstring'):
                usage += f"### {func['name']}\\n\\n"
                usage += f"{func['docstring']}\\n\\n"
                
                args = func.get('args', [])
                if args:
                    usage += f"```python\\n{func['name']}({', '.join(args)})\\n```\\n\\n"
        return usage
    
    return ""

def _generate_development_section(docs):
    """Generate development section."""
    return """## 🛠️ Development

### Setup Development Environment

```bash
# Clone the repository
git clone <repository-url>
cd """ + Path.cwd().name + """

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate

# Install development dependencies
pip install -r requirements.txt
```

### Running Tests

```bash
# Run all tests
python -m pytest

# Run with coverage
python -m pytest --cov=.
```

### Code Quality

```bash
# Run linting
mw lint scan

# Run security scan
mw skills run security-scan scan
```
"""

def main():
    """Main README generation function."""
    return generate_readme()

if __name__ == '__main__':
    sys.exit(main())