"""Health check endpoints."""

import time
from fastapi import APIRouter
from fastapi.responses import JSONResponse

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

router = APIRouter()


@router.get("/")
async def health_check():
    """Basic health check endpoint."""
    services = {
        "selenium_manager": True,
        "database": db_service.client is not None,
        "cache": cache_service.connected if cache_service else False,
    }
    
    status = "healthy" if all(services.values()) else "unhealthy"
    
    return {
        "status": status,
        "services": services,
        "timestamp": time.time()
    }


@router.get("/detailed")
async def detailed_health_check():
    """Detailed health check with engine status."""
    try:
        engine_health = multi_engine_manager.get_engine_health()
        
        overall_health = all(engine['healthy'] for engine in engine_health.values())
        
        return JSONResponse(content={
            "status": "healthy" if overall_health else "degraded",
            "engines": engine_health,
            "total_engines": len(engine_health),
            "healthy_engines": sum(1 for e in engine_health.values() if e['healthy']),
            "timestamp": time.time()
        })
    except Exception as e:
        return JSONResponse(content={
            "status": "unhealthy",
            "error": str(e),
            "timestamp": time.time()
        }, status_code=500)
