"""
FastAPI main application.
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import structlog

from app.api.routes import datasets, transformations, exports, health
from app.core.config import settings
from app.core.logging import configure_logging


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager."""
    # Startup
    configure_logging()
    logger = structlog.get_logger()
    logger.info("DataShaper AI starting", version=settings.app_version)
    
    # Create necessary directories
    settings.create_directories()
    
    # Start cleanup service
    from app.core.cleanup import CleanupService
    import asyncio
    
    cleanup_service = CleanupService()
    cleanup_task = asyncio.create_task(cleanup_service.start())
    
    # Connect to Redis
    from app.core.redis import redis_client
    await redis_client.connect()
    
    yield
    
    # Shutdown
    cleanup_service.stop()
    try:
        await asyncio.wait_for(cleanup_task, timeout=5.0)
    except asyncio.TimeoutError:
        logger.warning("cleanup_service_shutdown_timeout")
    
    # Disconnect Redis
    await redis_client.disconnect()
        
    logger.info("DataShaper AI shutting down")


# Create FastAPI application
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="Full-stack data automation and transformation platform with autonomous multi-agent workflow",
    lifespan=lifespan,
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Rate Limiting
from app.core.rate_limiter import RateLimitMiddleware
app.add_middleware(RateLimitMiddleware, requests_per_minute=100)

# Security Headers
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.gzip import GZipMiddleware

if settings.environment == "production":
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=["*.datashaper.ai", "datashaper.ai"])

app.add_middleware(GZipMiddleware, minimum_size=1000)

@app.middleware("http")
async def add_security_headers(request, call_next):
    response = await call_next(request)
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    return response

# Include routers
app.include_router(health.router, prefix=settings.api_v1_prefix, tags=["health"])
app.include_router(datasets.router, prefix=settings.api_v1_prefix, tags=["datasets"])
app.include_router(transformations.router, prefix=settings.api_v1_prefix, tags=["transformations"])
app.include_router(exports.router, prefix=settings.api_v1_prefix, tags=["exports"])

from app.api.routes import history
app.include_router(history.router, prefix=f"{settings.api_v1_prefix}/history", tags=["history"])

from app.api.routes import teams
app.include_router(teams.router, prefix=f"{settings.api_v1_prefix}/teams", tags=["teams"])

from app.api.routes import oauth
app.include_router(oauth.router, prefix=f"{settings.api_v1_prefix}/oauth", tags=["oauth"])


@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "name": settings.app_name,
        "version": settings.app_version,
        "status": "running",
    }
