"""
Main API v1 router.

This module combines all endpoint routers and provides the main API interface.
"""
from ninja import NinjaAPI
from ninja.security import django_auth

from .endpoints.companies import router as companies_router
from .endpoints.ride_models import router as ride_models_router
from .endpoints.parks import router as parks_router
from .endpoints.rides import router as rides_router
from .endpoints.moderation import router as moderation_router
from .endpoints.versioning import router as versioning_router
from .endpoints.auth import router as auth_router
from .endpoints.photos import router as photos_router
from .endpoints.search import router as search_router


# Create the main API instance
api = NinjaAPI(
    title="ThrillWiki API",
    version="1.0.0",
    description="""
# ThrillWiki REST API

A comprehensive API for amusement park, ride, and company data.

## Features

- **Companies**: Manufacturers, operators, and designers in the amusement industry
- **Ride Models**: Specific ride models from manufacturers
- **Parks**: Theme parks, amusement parks, water parks, and FECs
- **Rides**: Individual rides and roller coasters

## Authentication

The API uses JWT (JSON Web Token) authentication for secure access.

### Getting Started
1. Register: `POST /api/v1/auth/register`
2. Login: `POST /api/v1/auth/login` (returns access & refresh tokens)
3. Use token: Include `Authorization: Bearer <access_token>` header in requests
4. Refresh: `POST /api/v1/auth/token/refresh` when access token expires

### Permissions
- **Public**: Read operations (GET) on entities
- **Authenticated**: Create submissions, manage own profile
- **Moderator**: Approve/reject submissions, moderate content
- **Admin**: Full access, user management, role assignment

### Optional: Multi-Factor Authentication (MFA)
Users can enable TOTP-based 2FA for enhanced security:
1. Enable: `POST /api/v1/auth/mfa/enable`
2. Confirm: `POST /api/v1/auth/mfa/confirm`
3. Login with MFA: Include `mfa_token` in login request

## Pagination

List endpoints return paginated results:
- Default page size: 50 items
- Use `page` parameter to navigate (e.g., `?page=2`)

## Filtering & Search

Most list endpoints support filtering and search parameters.
See individual endpoint documentation for available filters.

## Geographic Search

The parks endpoint includes a special `/parks/nearby/` endpoint for geographic searches:
- **Production (PostGIS)**: Uses accurate distance-based queries
- **Local Development (SQLite)**: Uses bounding box approximation

## Rate Limiting

Rate limiting will be implemented in future versions.

## Data Format

All dates are in ISO 8601 format (YYYY-MM-DD).
All timestamps are in ISO 8601 format with timezone.
UUIDs are used for all entity IDs.
    """,
    docs_url="/docs",
    openapi_url="/openapi.json",
)

# Add authentication router
api.add_router("/auth", auth_router)

# Add routers for each entity
api.add_router("/companies", companies_router)
api.add_router("/ride-models", ride_models_router)
api.add_router("/parks", parks_router)
api.add_router("/rides", rides_router)

# Add moderation router
api.add_router("/moderation", moderation_router)

# Add versioning router
api.add_router("", versioning_router)  # Versioning endpoints are nested under entity paths

# Add photos router
api.add_router("", photos_router)  # Photos endpoints include both /photos and entity-nested routes

# Add search router
api.add_router("/search", search_router)


# Health check endpoint
@api.get("/health", tags=["System"], summary="Health check")
def health_check(request):
    """
    Health check endpoint.
    
    Returns system status and API version.
    """
    return {
        "status": "healthy",
        "version": "1.0.0",
        "api": "ThrillWiki API v1"
    }


# API info endpoint
@api.get("/info", tags=["System"], summary="API information")
def api_info(request):
    """
    Get API information and statistics.
    
    Returns basic API metadata and available endpoints.
    """
    from apps.entities.models import Company, RideModel, Park, Ride
    
    return {
        "version": "1.0.0",
        "title": "ThrillWiki API",
        "endpoints": {
            "auth": "/api/v1/auth/",
            "companies": "/api/v1/companies/",
            "ride_models": "/api/v1/ride-models/",
            "parks": "/api/v1/parks/",
            "rides": "/api/v1/rides/",
            "moderation": "/api/v1/moderation/",
            "photos": "/api/v1/photos/",
            "search": "/api/v1/search/",
        },
        "statistics": {
            "companies": Company.objects.count(),
            "ride_models": RideModel.objects.count(),
            "parks": Park.objects.count(),
            "rides": Ride.objects.count(),
            "coasters": Ride.objects.filter(is_coaster=True).count(),
        },
        "documentation": "/api/v1/docs",
        "openapi_schema": "/api/v1/openapi.json",
    }
