import time
from typing import Annotated
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from infrastructure.database.session import get_db
from infrastructure.redis.client import get_redis_client
from apps.api.lifespan import APP_START_TIME

router = APIRouter(prefix="/health", tags=["Health & Diagnostics"])


@router.get("", status_code=status.HTTP_200_OK)
async def liveness_check():
    """Quick liveness probe for orchestrators and load balancers."""
    return {
        "status": "healthy",
        "timestamp": time.time(),
    }


@router.get("/detailed", status_code=status.HTTP_200_OK)
async def readiness_check(
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Detailed health check for database, redis, and system uptime."""
    settings = get_settings()
    health_status = {
        "app_name": settings.APP_NAME,
        "environment": settings.APP_ENV,
        "uptime_seconds": round(time.time() - APP_START_TIME, 2),
        "status": "healthy",
        "dependencies": {},
    }

    # Database check
    db_start = time.time()
    try:
        await db.execute(text("SELECT 1"))
        health_status["dependencies"]["database"] = {
            "status": "healthy",
            "latency_ms": round((time.time() - db_start) * 1000, 2),
        }
    except Exception as exc:
        health_status["status"] = "degraded"
        health_status["dependencies"]["database"] = {
            "status": "unhealthy",
            "error": str(exc),
        }

    # Redis check
    redis_start = time.time()
    try:
        redis = await get_redis_client()
        pong = await redis.ping()
        health_status["dependencies"]["redis"] = {
            "status": "healthy" if pong else "unhealthy",
            "latency_ms": round((time.time() - redis_start) * 1000, 2),
        }
    except Exception as exc:
        health_status["status"] = "degraded"
        health_status["dependencies"]["redis"] = {
            "status": "unhealthy",
            "error": str(exc),
        }

    http_code = (
        status.HTTP_200_OK
        if health_status["status"] == "healthy"
        else status.HTTP_503_SERVICE_UNAVAILABLE
    )
    return JSONResponse(status_code=http_code, content=health_status)
