"""
Documentation Generator - Creates comprehensive project documentation

Generates:
- README.md with installation, usage, examples, and features
- API.md with endpoint documentation
- ARCHITECTURE.md with design and component information
- SETUP.md with development setup instructions
"""


class DocumentationGenerator:
    """Generate comprehensive project documentation from project context"""

    @staticmethod
    def generate_comprehensive_readme(
        project_name: str,
        description: str,
        tech_stack: list[str] | None = None,
        requirements: list[str] | None = None,
        features: list[str] | None = None,
        deployment_target: str = "Local/Server",
        code_structure: dict[str, str] | None = None,
        author: str = "Generated by Socrates AI",
    ) -> str:
        """
        Generate detailed README.md with comprehensive project information.

        Args:
            project_name: Name of the project
            description: Project description
            tech_stack: List of technologies used
            requirements: List of requirements/constraints
            features: List of key features
            deployment_target: Deployment target information
            code_structure: Dictionary of generated files for structure overview
            author: Project author

        Returns:
            Comprehensive README.md content
        """
        if tech_stack is None:
            tech_stack = []
        if requirements is None:
            requirements = []
        if features is None:
            features = []
        if code_structure is None:
            code_structure = {}

        readme = f"""# {project_name}

{description}

## Table of Contents

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Project Structure](#project-structure)
- [Configuration](#configuration)
- [Usage](#usage)
- [Testing](#testing)
- [Development](#development)
- [Deployment](#deployment)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

## Features

"""

        if features:
            for feature in features:
                readme += f"- {feature}\n"
        else:
            readme += """- Modular architecture
- Production-ready configuration
- Comprehensive test coverage
- Docker support
- CI/CD ready
"""

        readme += """
## Requirements

### System Requirements
"""
        if requirements:
            for req in requirements:
                readme += f"- {req}\n"
        else:
            readme += """- Python 3.9 or higher
- pip (Python package manager)
- Git (for version control)
"""

        if "docker" in str(code_structure).lower():
            readme += "- Docker (optional, for containerized deployment)\n"

        readme += """
### Technology Stack

"""
        if tech_stack:
            for tech in tech_stack:
                readme += f"- {tech}\n"
        else:
            readme += """- Python 3.9+
- Standard library modules
"""

        readme += f"""
## Installation

### Prerequisites

Ensure you have Python 3.9+ installed:

```bash
python --version
```

### Setup from Source

1. **Clone or extract the repository:**

```bash
cd {project_name}
```

2. **Create a virtual environment (recommended):**

```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
```

3. **Install the project with development dependencies:**

```bash
pip install -e ".[dev]"
```

### Installation via pip

Once published to PyPI, install with:

```bash
pip install {project_name}
```

## Quick Start

### Basic Usage

```python
# Import the module
from src import models, services, controllers

# Your code here
```

### Running the Application

```bash
python main.py
```

### Running with Docker

```bash
docker-compose up --build
```

The application will start on `http://localhost:8000`

## Project Structure

```
{project_name}/
├── src/                      # Source code package
│   ├── __init__.py
│   ├── models.py            # Data models and entities
│   ├── controllers.py       # API controllers and handlers
│   ├── services.py          # Business logic and services
│   └── utils.py             # Utility functions
├── config/                  # Configuration
│   ├── __init__.py
│   └── settings.py          # Configuration settings
├── tests/                   # Test suite
│   ├── __init__.py
│   └── test_main.py         # Test cases
├── docs/                    # Documentation
├── main.py                  # Application entry point
├── requirements.txt         # Python dependencies
├── pyproject.toml           # Project metadata and build config
├── setup.py                 # Setup configuration
├── setup.cfg                # Additional setup config
├── pytest.ini               # Pytest configuration
├── Makefile                 # Development tasks
├── Dockerfile               # Docker configuration
├── docker-compose.yml       # Docker compose for local development
├── .env.example             # Environment variables template
├── .gitignore               # Git ignore rules
├── .pre-commit-config.yaml  # Pre-commit hooks
├── README.md                # This file
├── LICENSE                  # License information
├── CHANGELOG.md             # Version history
├── CONTRIBUTING.md          # Contribution guidelines
└── .github/
    └── workflows/
        ├── ci.yml           # CI pipeline
        ├── lint.yml         # Linting checks
        └── publish.yml      # PyPI publishing
```

## Configuration

### Environment Variables

Create a `.env` file in the project root based on `.env.example`:

```bash
cp .env.example .env
```

Edit `.env` with your configuration:

```env
# Application
APP_NAME={project_name}
DEBUG=False
LOG_LEVEL=INFO

# Add other environment variables as needed
```

### Configuration Files

- **pyproject.toml**: Project metadata, build system, and tool configurations
- **setup.py**: Package setup and dependencies
- **.pre-commit-config.yaml**: Pre-commit hooks for code quality
- **pytest.ini**: Testing configuration

## Usage

### Running Tests

Run the entire test suite:

```bash
make test
```

Or use pytest directly:

```bash
pytest -v
```

Run with coverage:

```bash
pytest --cov=src
```

### Code Quality

Format code with Black and Ruff:

```bash
make format
```

Run linting checks:

```bash
make lint
```

Run type checking with mypy:

```bash
make type-check
```

### Development Workflow

1. **Install with development dependencies:**
   ```bash
   make install-dev
   ```

2. **Set up pre-commit hooks:**
   ```bash
   pre-commit install
   ```

3. **Make changes and commit:**
   ```bash
   git commit -m "Your commit message"
   ```
   Pre-commit hooks will automatically run checks.

4. **Run tests before pushing:**
   ```bash
   make test
   ```

## Testing

### Test Structure

Tests are located in the `tests/` directory with a `test_` prefix.

### Writing Tests

```python
import pytest
from src.models import YourModel

def test_model_creation():
    model = YourModel(param="value")
    assert model.param == "value"

@pytest.mark.integration
def test_integration():
    # Integration test
    pass
```

### Running Specific Tests

```bash
# Run a specific test file
pytest tests/test_main.py -v

# Run tests matching a pattern
pytest -k "test_model" -v

# Run with markers
pytest -m "unit" -v
```

## Development

### Making Changes

1. Create a feature branch:
   ```bash
   git checkout -b feature/your-feature
   ```

2. Make your changes and add tests

3. Ensure all checks pass:
   ```bash
   make lint
   make type-check
   make test
   ```

4. Commit with clear messages:
   ```bash
   git commit -m "feat: Add your feature description"
   ```

5. Push and create a pull request:
   ```bash
   git push origin feature/your-feature
   ```

### Documentation

Update documentation as you add features:
- Keep README.md current
- Document complex functions with docstrings
- Update CHANGELOG.md with notable changes

## Deployment

### Deployment Target

This project is configured for deployment to: **{deployment_target}**

### Deployment Steps

1. **Prepare for deployment:**
   ```bash
   make clean
   make test
   ```

2. **Build distribution packages:**
   ```bash
   make build
   ```

3. **Deploy to your target:**

   **For {deployment_target}:**
   - Follow the platform-specific deployment guide
   - Set environment variables in your deployment environment
   - Run database migrations if applicable
   - Start the application

### Docker Deployment

```bash
# Build the Docker image
docker build -t {project_name} .

# Run the container
docker run -p 8000:8000 {project_name}
```

### Environment Setup in Production

Set all required environment variables in your production environment:
- Use `.env.example` as a reference
- Never commit `.env` to version control
- Use secure secret management for sensitive values

## Troubleshooting

### Common Issues

**Issue: Import errors when running the application**

Solution: Ensure the package is installed:
```bash
pip install -e .
```

**Issue: Tests not running**

Solution: Install test dependencies:
```bash
pip install -e ".[dev]"
```

**Issue: Port 8000 already in use (Docker)**

Solution: Use a different port:
```bash
docker run -p 8001:8000 {project_name}
```

### Getting Help

- Check the documentation in the `docs/` folder
- Review test cases for usage examples
- Check GitHub issues for known problems
- See CONTRIBUTING.md for support options

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on:
- Reporting bugs
- Proposing enhancements
- Submitting pull requests
- Code style and standards

## License

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

---

**Generated by Socrates AI**

For more information, visit the project documentation or create an issue on GitHub.
"""  # nosec B608
        return readme

    @staticmethod
    def generate_api_documentation(
        endpoints: list[dict] | None = None,
    ) -> str:
        """
        Generate API.md documentation from endpoint information.

        Args:
            endpoints: List of endpoint dictionaries with method, path, description

        Returns:
            API documentation content
        """
        api_doc = """# API Documentation

This document describes the API endpoints available in this project.

## Authentication

All endpoints support the following authentication methods:
- Bearer Token (JWT)
- API Key (if configured)

Include the token in the Authorization header:

```bash
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/endpoint
```

## Base URL

```
http://localhost:8000
```

## Endpoints

"""

        if endpoints:
            for endpoint in endpoints:
                method = endpoint.get("method", "GET").upper()
                path = endpoint.get("path", "/")
                description = endpoint.get("description", "")
                params = endpoint.get("params", [])
                response = endpoint.get("response", "")

                api_doc += f"""### {method} {path}

{description}

"""
                if params:
                    api_doc += "**Parameters:**\n\n"
                    for param in params:
                        param_name = param.get("name", "param")
                        param_type = param.get("type", "string")
                        param_desc = param.get("description", "")
                        api_doc += f"- `{param_name}` ({param_type}): {param_desc}\n"
                    api_doc += "\n"

                if response:
                    api_doc += f"**Response:**\n\n```json\n{response}\n```\n\n"

        else:
            api_doc += """### Example Endpoints

#### GET /health

Check the health status of the API.

**Response:**
```json
{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

#### GET /users

Retrieve a list of users.

**Parameters:**
- `limit` (integer): Maximum number of results (default: 100)
- `offset` (integer): Pagination offset (default: 0)

**Response:**
```json
{
  "data": [
    {"id": 1, "name": "User 1"},
    {"id": 2, "name": "User 2"}
  ],
  "total": 2,
  "limit": 100,
  "offset": 0
}
```

#### POST /users

Create a new user.

**Request:**
```json
{
  "name": "New User",
  "email": "user@example.com"
}
```

**Response:**
```json
{
  "id": 3,
  "name": "New User",
  "email": "user@example.com",
  "created_at": "2024-01-15T10:30:00Z"
}
```

"""

        api_doc += """## Error Responses

All errors follow this format:

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human readable error message",
    "details": {}
  }
}
```

### Common Error Codes

- `400`: Bad Request - Invalid input parameters
- `401`: Unauthorized - Authentication required or failed
- `403`: Forbidden - Insufficient permissions
- `404`: Not Found - Resource not found
- `409`: Conflict - Resource conflict (e.g., duplicate)
- `500`: Internal Server Error - Unexpected server error

## Rate Limiting

API requests are rate limited to prevent abuse:
- **Free tier**: 100 requests per hour
- **Premium tier**: 10,000 requests per hour

Rate limit information is included in response headers:
- `X-RateLimit-Limit`: Maximum requests per hour
- `X-RateLimit-Remaining`: Requests remaining in current hour
- `X-RateLimit-Reset`: Unix timestamp when limit resets

## Pagination

Endpoints that return lists support pagination:

```bash
GET /users?limit=50&offset=100
```

Response includes pagination metadata:
```json
{
  "data": [...],
  "pagination": {
    "limit": 50,
    "offset": 100,
    "total": 1000,
    "pages": 20
  }
}
```

## Filtering and Sorting

List endpoints support filtering and sorting:

```bash
GET /users?filter=active&sort=-created_at
```

- Filter: Use query parameters to filter results
- Sort: Use `-` prefix for descending order

## Webhooks

Subscribe to events with webhooks:

```bash
POST /webhooks
{
  "url": "https://your-domain.com/webhook",
  "events": ["user.created", "user.updated"]
}
```

---

For more details on specific endpoints, refer to the inline code documentation.
"""
        return api_doc

    @staticmethod
    def generate_architecture_docs(
        project_name: str,
        description: str,
        tech_stack: list[str] | None = None,
        architecture_notes: str = "",
    ) -> str:
        """
        Generate ARCHITECTURE.md documenting system design.

        Args:
            project_name: Project name
            description: Project description
            tech_stack: Technologies used
            architecture_notes: Additional architecture notes

        Returns:
            Architecture documentation content
        """
        if tech_stack is None:
            tech_stack = []

        arch_doc = f"""# {project_name} - Architecture Documentation

## Overview

{description}

This document describes the architecture, design patterns, and component interactions in {project_name}.

## Table of Contents

- [Architecture Overview](#architecture-overview)
- [System Components](#system-components)
- [Technology Stack](#technology-stack)
- [Design Patterns](#design-patterns)
- [Data Flow](#data-flow)
- [Database Schema](#database-schema)
- [API Design](#api-design)
- [Security](#security)
- [Scalability](#scalability)
- [Deployment Architecture](#deployment-architecture)

## Architecture Overview

{project_name} follows a **modular, layered architecture** designed for maintainability, testability, and scalability.

### Core Layers

1. **Presentation Layer** - User interfaces and API endpoints
2. **Service Layer** - Business logic and data processing
3. **Data Layer** - Database access and persistence
4. **Infrastructure Layer** - External services and utilities

## System Components

### Core Modules

#### 1. Models (`src/models.py`)

**Responsibility:** Define data structures and entities

- Project entities and data models
- Type definitions and schemas
- Validation logic

**Key Classes:**
- `ProjectModel`: Core project entity
- Related models for associated data

#### 2. Controllers (`src/controllers.py`)

**Responsibility:** Handle API requests and responses

- Route handlers
- Request validation
- Response formatting
- HTTP status management

**Key Methods:**
- Request processing pipelines
- Error handling and logging
- Response serialization

#### 3. Services (`src/services.py`)

**Responsibility:** Implement business logic

- Core business operations
- Data processing and transformation
- External service integration
- Complex calculations or workflows

**Key Responsibilities:**
- Business rule enforcement
- State management
- Interaction between models

#### 4. Utilities (`src/utils.py`)

**Responsibility:** Common helper functions

- String formatting and parsing
- Data validation helpers
- File operations
- Logging utilities

## Technology Stack

### Backend
"""
        for tech in tech_stack:
            arch_doc += f"- {tech}\n"

        arch_doc += """
### Infrastructure
- Docker & Docker Compose (containerization)
- GitHub Actions (CI/CD)
- PostgreSQL (optional, for data persistence)
- Redis (optional, for caching)

### Development Tools
- pytest (testing framework)
- Black (code formatting)
- Ruff (linting)
- mypy (type checking)
- pre-commit (git hooks)

## Design Patterns

### 1. Model-View-Controller (MVC)

The application separates concerns into three tiers:

```
Request → Controller → Service → Model → Database
  ↑                                         ↓
  └─────────────── Response ──────────────┘
```

### 2. Dependency Injection

Services receive their dependencies through constructor arguments, enabling:
- Easy testing with mocks
- Loose coupling between components
- Clear dependency visibility

### 3. Repository Pattern

Data access is abstracted behind repository interfaces:
- Models interact with repositories, not directly with databases
- Easy to swap implementations
- Centralizes data access logic

### 4. Factory Pattern

Complex object creation is delegated to factory functions:
- Cleaner initialization code
- Consistent object creation
- Centralized configuration

## Data Flow

### Request Processing Pipeline

```
1. Request arrives at API endpoint
2. Controller receives and validates request
3. Controller calls appropriate service method
4. Service processes request and calls models/repositories
5. Repository performs database operations
6. Results flow back through layers
7. Controller formats and returns response
```

### Asynchronous Processing

For long-running operations:

```
1. Request received
2. Task queued for async processing
3. Immediate response returned to client
4. Background worker processes task
5. Results stored and notified (if needed)
```

## Database Schema

### Core Tables

```sql
-- Projects table
CREATE TABLE projects (
  id UUID PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  owner_id UUID NOT NULL,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Users table (if applicable)
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  created_at TIMESTAMP DEFAULT NOW()
);
```

### Relationships

- Projects have one owner (User)
- Users can have many projects
- Additional relationships as needed

## API Design

### RESTful Principles

The API follows REST conventions:

- **GET** `/resource` - List resources
- **GET** `/resource/:id` - Get single resource
- **POST** `/resource` - Create resource
- **PUT/PATCH** `/resource/:id` - Update resource
- **DELETE** `/resource/:id` - Delete resource

### Response Format

All responses follow a consistent format:

```json
{
  "success": true,
  "status": "success",
  "data": { /* response data */ },
  "message": "Operation successful"
}
```

### Error Handling

Errors include proper HTTP status codes and error details:

```json
{
  "success": false,
  "status": "error",
  "message": "Detailed error message",
  "error": "ERROR_CODE"
}
```

## Security

### Authentication

- JWT tokens for API authentication
- Token expiration and refresh mechanisms
- Secure token storage in httpOnly cookies

### Authorization

- Role-based access control (RBAC)
- Resource-level permission checks
- Policy enforcement middleware

### Data Protection

- Input validation and sanitization
- SQL injection prevention (via ORM)
- XSS protection in responses
- CSRF tokens for state-changing operations

### Environment Security

- Secrets managed via environment variables
- No secrets in version control
- Secure configuration management

## Scalability

### Horizontal Scaling

The application is designed for horizontal scaling:

```
Load Balancer
├── Instance 1
├── Instance 2
├── Instance 3
└── Instance N

Shared Resources:
├── Database (PostgreSQL)
├── Cache (Redis)
└── Message Queue (if applicable)
```

### Performance Optimization

- **Caching**: Redis for frequently accessed data
- **Indexing**: Database indexes on common queries
- **Pagination**: Limit response sizes
- **Lazy Loading**: Load data on demand
- **Async Processing**: Background tasks for heavy operations

### Bottleneck Mitigation

- Database connection pooling
- API rate limiting
- Request batching
- Response compression

## Deployment Architecture

### Development Environment

```yaml
Local Machine:
├── Python virtual environment
├── Local database (SQLite or Docker PostgreSQL)
└── Redis (optional, via Docker)
```

### Production Environment

```yaml
Cloud/Server:
├── Application Servers (Kubernetes pods)
├── Load Balancer (nginx, cloud LB)
├── PostgreSQL Database (managed or self-hosted)
├── Redis Cache (managed or self-hosted)
├── CDN for static assets (optional)
└── Monitoring & Logging (optional)
```

### Docker Architecture

```yaml
docker-compose.yml:
├── app (application container)
├── postgres (database)
└── redis (cache)
```

Each service is independently scalable and can be replaced or updated.

## Development Workflow

### Local Development

1. Clone repository
2. Set up virtual environment
3. Install dependencies
4. Configure `.env` file
5. Run `docker-compose up` for supporting services
6. Start application: `python main.py`

### Testing

```
Code Changes → Run Tests → Code Review → Merge → Deploy
```

### CI/CD Pipeline

GitHub Actions automatically:
1. Run tests on every commit
2. Check code quality
3. Build Docker image
4. Deploy to staging (optional)
5. Run integration tests

## Future Improvements

- Microservices architecture (if needed)
- Event-driven architecture for certain features
- Advanced caching strategies
- GraphQL API alternative
- WebSocket support for real-time features

"""

        if architecture_notes:
            arch_doc += f"""
## Additional Notes

{architecture_notes}

"""

        arch_doc += """---

**Last Updated:** Generated by Socrates AI

For questions or clarifications about the architecture, see CONTRIBUTING.md for support options.
"""
        return arch_doc

    @staticmethod
    def generate_setup_guide(project_name: str = "project") -> str:
        """Generate development setup guide."""
        return f"""# Development Setup Guide for {project_name}

## Prerequisites

- Python 3.9 or higher
- pip and virtualenv
- Git
- Docker and Docker Compose (optional, for database services)
- Text editor or IDE (VS Code, PyCharm, etc.)

## Initial Setup

### 1. Clone the Repository

```bash
git clone https://github.com/yourusername/{project_name}.git
cd {project_name}
```

### 2. Create Virtual Environment

```bash
python -m venv venv

# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate

# On Windows:
venv\\Scripts\\activate
```

### 3. Install Dependencies

```bash
pip install --upgrade pip
pip install -e ".[dev]"
```

### 4. Set Up Environment Variables

```bash
cp .env.example .env
# Edit .env with your configuration
```

### 5. Install Git Hooks

```bash
pre-commit install
```

## Running the Application

### Local Development

```bash
python main.py
```

### With Docker

```bash
docker-compose up
```

## Running Tests

```bash
# Run all tests
pytest

# Run with verbose output
pytest -v

# Run with coverage
pytest --cov=src

# Run specific test file
pytest tests/test_main.py
```

## Code Quality

### Formatting

```bash
# Format code with Black
black .

# Fix import sorting
ruff check . --fix
```

### Linting

```bash
# Check code style
ruff check .

# Check type hints
mypy .
```

### Pre-commit Checks

Hooks run automatically on commit:
```bash
black .
ruff check . --fix
mypy .
```

To skip hooks (not recommended):
```bash
git commit --no-verify
```

## Common Development Tasks

### Add a New Dependency

```bash
pip install package-name
pip freeze > requirements.txt
```

### Create a Database Migration

```bash
# If using Alembic
alembic revision --autogenerate -m "Description"
alembic upgrade head
```

### Debug a Test

```bash
pytest tests/test_file.py::test_function -vv
```

### Check Dependency Security

```bash
pip install safety
safety check
```

## Project Structure

```
{project_name}/
├── src/              # Main package
├── tests/            # Test files
├── docs/             # Documentation
├── main.py           # Entry point
├── Makefile          # Development tasks
└── pyproject.toml    # Project config
```

## Useful Commands

See `make help` for available development tasks:

```bash
make help
make test
make lint
make format
make clean
```

## Getting Help

1. Check README.md for general information
2. Review ARCHITECTURE.md for design details
3. Check existing issues on GitHub
4. See CONTRIBUTING.md for support options

## Next Steps

1. Read through the codebase
2. Run tests to ensure everything works
3. Make a small change and commit
4. Submit your first contribution!

Happy coding! 🚀
"""
