from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text

from src.infrastructure.cache.redis_cache import redis_cache
from src.infrastructure.database.session import get_db_session
from src.infrastructure.messaging.rabbitmq import rabbitmq_client
from src.api.v1.dependencies.auth import get_current_user
from src.services.auth.security import TokenData

router = APIRouter(prefix="/system", tags=["System"])


class HealthStatus(BaseModel):
    status: str
    version: str
    services: dict[str, str]


class ReadinessStatus(BaseModel):
    status: str
    checks: dict[str, bool]


@router.get("/health", response_model=HealthStatus)
async def health_check():
    return HealthStatus(
        status="healthy",
        version="0.1.0",
        services={
            "api": "healthy",
        },
    )


@router.get("/ready", response_model=ReadinessStatus)
async def readiness_check(db: AsyncSession = Depends(get_db_session)):
    checks: dict[str, bool] = {}

    try:
        # Check database connection
        await db.execute(text("SELECT 1"))
        db_ok = True
    except Exception:
        db_ok = False
    checks["database"] = db_ok

    redis_ok = await redis_cache.health_check()
    checks["redis"] = redis_ok

    mq_ok = await rabbitmq_client.health_check()
    checks["rabbitmq"] = mq_ok

    overall = all(checks.values())
    return ReadinessStatus(
        status="ready" if overall else "degraded",
        checks=checks,
    )


@router.get("/status")
async def system_status(current_user: TokenData = Depends(get_current_user)):
    return {
        "platform": "Pharmacy Integration Platform",
        "version": "0.1.0",
        "environment": "production",
        "services": {
            "auth": "active",
            "pharmacy": "active",
            "medication": "active",
            "connector": "active",
            "synchronization": "active",
            "audit": "active",
            "notification": "active",
        },
    }
