"""Health check endpoints and models."""

import time
from datetime import datetime, timezone
from typing import Any

from fastapi import APIRouter
from sqlalchemy import text

from src.database import SessionLocal
from src.schemas.system import (
    DatabaseHealth,
    DatabaseHealthResponse,
    DiskHealth,
    HealthChecks,
    HealthResponse,
)

router = APIRouter()

# Track start time for uptime
_start_time = time.time()


@router.get(
    "/health",
    response_model=HealthResponse,
    summary="Health check",
    description="Returns overall system health status including database and disk checks.",
    tags=["Health"],
)
async def health_check() -> dict[str, Any]:
    """Check overall system health.

    Returns:
        HealthResponse with status, timestamp, version, checks, and uptime.
    """
    checks = HealthChecks()
    overall_status = "healthy"

    # Database check
    try:
        import time as time_module

        start = time_module.perf_counter()
        async with SessionLocal() as session:
            await session.execute(text("SELECT 1"))
        db_time = (time_module.perf_counter() - start) * 1000
        checks.database = DatabaseHealth(
            status="healthy",
            response_time_ms=round(db_time, 2),
        )
    except Exception:
        checks.database = DatabaseHealth(
            status="unhealthy",
            response_time_ms=0.0,
        )
        overall_status = "degraded"

    # Disk check
    try:
        import shutil

        disk = shutil.disk_usage("/")
        free_gb = disk.free / (1024**3)
        total_gb = disk.total / (1024**3)
        disk_status = "healthy" if free_gb > 1.0 else "degraded"
        if disk_status == "degraded":
            overall_status = "degraded"
        checks.disk = DiskHealth(
            status=disk_status,
            free_gb=round(free_gb, 2),
            total_gb=round(total_gb, 2),
        )
    except Exception:
        checks.disk = None

    return HealthResponse(
        status=overall_status,
        timestamp=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
        version="0.1.0",
        checks=checks,
        uptime_seconds=round(time.time() - _start_time, 2),
    ).model_dump()


@router.get(
    "/health/db",
    response_model=DatabaseHealthResponse,
    summary="Database health check",
    description="Returns database-specific health status with response time.",
    tags=["Health"],
)
async def health_check_db() -> dict[str, Any]:
    """Check database health.

    Returns:
        DatabaseHealthResponse with status and response time.
    """
    import time as time_module

    try:
        start = time_module.perf_counter()
        async with SessionLocal() as session:
            await session.execute(text("SELECT 1"))
        db_time = (time_module.perf_counter() - start) * 1000
        return DatabaseHealthResponse(
            status="healthy",
            response_time_ms=round(db_time, 2),
        ).model_dump()
    except Exception:
        return DatabaseHealthResponse(
            status="unhealthy",
            response_time_ms=0.0,
        ).model_dump()
