"""
Data Service - Web scraping service for collecting articles from search engines
"""
import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from app.config.database import connect_to_mongo, close_mongo_connection
from app.config.settings import get_settings
from app.services.kafka_service import KafkaService
from app.api import scraper, articles

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Get settings
settings = get_settings()

# Initialize Kafka service
kafka_service = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    global kafka_service
    
    # Startup
    logger.info("Starting Data Service...")
    
    try:
        # Connect to MongoDB
        await connect_to_mongo()
        logger.info("Connected to MongoDB")
        
        # Initialize Kafka service
        kafka_service = KafkaService()
        logger.info("Kafka service initialized")
        
    except Exception as e:
        logger.error(f"Failed to initialize services: {e}")
        # Don't raise here to allow service to start even if some components fail
    
    yield
    
    # Shutdown
    logger.info("Shutting down Data Service...")
    
    try:
        # Close MongoDB connection
        await close_mongo_connection()
        logger.info("MongoDB connection closed")
        
        # Close Kafka service
        if kafka_service:
            await kafka_service.close()
            logger.info("Kafka service closed")
        
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")


# Create FastAPI application
app = FastAPI(
    title="Data Service",
    description="Web scraping service for collecting articles from search engines",
    version="1.0.0",
    lifespan=lifespan
)

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

# Include routers
app.include_router(scraper.router, prefix="/api/v1")
app.include_router(articles.router, prefix="/api/v1")


@app.exception_handler(404)
async def not_found_handler(request, exc):
    """Handle 404 errors"""
    return JSONResponse(
        status_code=404,
        content={"detail": "Resource not found"}
    )


@app.exception_handler(500)
async def internal_error_handler(request, exc):
    """Handle 500 errors"""
    logger.error(f"Internal server error: {exc}")
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    """Handle HTTP exceptions"""
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "service": "data-service",
        "version": "1.0.0"
    }


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": "Data Service API",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/health"
    }