"""FastAPI application factory for the scraping service."""

import logging
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from src.services.database import db_service
from src.services.cache_service import cache_service
from src.scrapers.multi_engine_manager import multi_engine_manager
from src.config.settings import LOG_LEVEL, LOG_FORMAT
from src.core.middleware import RequestLoggingMiddleware, ErrorHandlingMiddleware

# Configure logging
logging.basicConfig(level=getattr(logging, LOG_LEVEL), format=LOG_FORMAT)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager with fast startup."""
    # Startup
    logger.info("Starting up the fast Selenium application...")
    
    # Initialize database
    try:
        await db_service.connect()
        logger.info("Database connected")
    except Exception as e:
        logger.warning(f"Database connection failed: {e}")
    
    # Initialize cache
    try:
        cache_service.connect()
        logger.info("Cache connected")
    except Exception as e:
        logger.warning(f"Cache connection failed: {e}")
    
    # Skip engine performance test during startup for faster initialization
    skip_startup_test = os.getenv("SKIP_STARTUP_TEST", "true").lower() == "true"
    
    if not skip_startup_test:
        try:
            performance_results = multi_engine_manager.test_engine_performance()
            logger.info(f"Engine performance test completed: {len(performance_results)} engines tested")
        except Exception as e:
            logger.warning(f"Engine performance test failed: {e}")
    else:
        logger.info("Skipping startup engine test for faster initialization")
    
    logger.info("Fast Selenium application started successfully")
    
    yield
    
    # Shutdown
    logger.info("Shutting down the application...")
    
    # Close connections
    try:
        await db_service.disconnect()
    except:
        pass
    
    try:
        cache_service.disconnect()
    except:
        pass
    
    try:
        multi_engine_manager.close()
    except:
        pass
    
    logger.info("Application shut down successfully")


def create_app() -> FastAPI:
    """Create and configure FastAPI application."""
    app = FastAPI(
        title="Fast Multi-Threaded Selenium Scraper API",
        description="High-performance multi-engine search scraper with fast Selenium and parallel processing",
        version="3.0.0",
        lifespan=lifespan
    )

    # Add middleware
    app.add_middleware(ErrorHandlingMiddleware)
    app.add_middleware(RequestLoggingMiddleware)
    
    # Add CORS middleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Register routers
    from src.api.routes import health, scraping, performance, cache, debug
    
    app.include_router(health.router, prefix="/health", tags=["health"])
    app.include_router(scraping.router, prefix="/scrape", tags=["scraping"])
    app.include_router(performance.router, prefix="/performance", tags=["performance"])
    app.include_router(cache.router, prefix="/cache", tags=["cache"])
    app.include_router(debug.router, prefix="/debug", tags=["debug"])
    
    # Root endpoint
    @app.get("/")
    async def root():
        """Root endpoint."""
        return {
            "message": "Fast Multi-Threaded Selenium Scraper API",
            "version": "3.0.0",
            "status": "ready",
            "features": [
                "Multi-threaded Selenium scraping",
                "Ultra-fast optimized Chrome drivers",
                "Parallel engine processing",
                "Performance monitoring",
                "Redis caching",
                "Real-time statistics"
            ],
            "engines": multi_engine_manager.get_available_engines()
        }
    
    @app.get("/engines")
    async def get_engines():
        """Get available search engines."""
        return {
            "available_engines": multi_engine_manager.get_available_engines(),
            "descriptions": multi_engine_manager.get_engine_descriptions()
        }

    return app
