from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any
from datetime import datetime
from ...api.dependencies import get_search_repository
from ....core.database import database
from ....core.kafka_client import kafka_client
from ....infrastructure.cache.redis_cache import redis_cache
import logging

logger = logging.getLogger(__name__)

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

@router.get("/")
async def health_check():
    """Basic health check"""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "service": "search-coordinator"
    }

@router.get("/detailed")
async def detailed_health_check():
    """Detailed health check with dependencies"""
    health_status = {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat(),
        "service": "search-coordinator",
        "dependencies": {}
    }
    
    # Check MongoDB
    try:
        if database.client:
            await database.client.admin.command('ping')
            health_status["dependencies"]["mongodb"] = {"status": "healthy"}
        else:
            health_status["dependencies"]["mongodb"] = {"status": "disconnected"}
    except Exception as e:
        health_status["dependencies"]["mongodb"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        health_status["status"] = "degraded"
    
    # Check Redis
    try:
        if redis_cache.redis_client:
            await redis_cache.redis_client.ping()
            health_status["dependencies"]["redis"] = {"status": "healthy"}
        else:
            health_status["dependencies"]["redis"] = {"status": "disconnected"}
    except Exception as e:
        health_status["dependencies"]["redis"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        health_status["status"] = "degraded"
    
    # Check Kafka
    try:
        if kafka_client.producer:
            health_status["dependencies"]["kafka"] = {"status": "healthy"}
        else:
            health_status["dependencies"]["kafka"] = {"status": "disconnected"}
    except Exception as e:
        health_status["dependencies"]["kafka"] = {
            "status": "unhealthy",
            "error": str(e)
        }
        health_status["status"] = "degraded"
    
    return health_status

@router.get("/metrics")
async def get_service_metrics(search_repository = Depends(get_search_repository)):
    """Get service metrics"""
    try:
        # Get basic metrics
        pending_requests = await search_repository.get_pending_requests()
        
        metrics = {
            "timestamp": datetime.utcnow().isoformat(),
            "pending_requests": len(pending_requests),
            "uptime_seconds": (datetime.utcnow() - datetime.utcnow()).total_seconds(),
            "memory_usage": {},  # Could add psutil for memory metrics
            "cpu_usage": {}      # Could add psutil for CPU metrics
        }
        
        return metrics
        
    except Exception as e:
        logger.error(f"Error getting service metrics: {e}")
        raise HTTPException(status_code=500, detail="Failed to get service metrics")
