"""Health check utility for monitoring application status."""

import asyncio
import aiohttp
import sys
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)


async def check_health(base_url: str = "http://localhost:8000") -> Dict[str, Any]:
    """Check application health."""
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{base_url}/health") as response:
                if response.status == 200:
                    data = await response.json()
                    return {
                        "status": "healthy",
                        "details": data
                    }
                else:
                    return {
                        "status": "unhealthy",
                        "error": f"HTTP {response.status}"
                    }
    except Exception as e:
        return {
            "status": "unhealthy",
            "error": str(e)
        }


async def check_detailed_health(base_url: str = "http://localhost:8000") -> Dict[str, Any]:
    """Check detailed application health."""
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{base_url}/health/detailed") as response:
                if response.status == 200:
                    data = await response.json()
                    return {
                        "status": "healthy",
                        "details": data
                    }
                else:
                    return {
                        "status": "unhealthy",
                        "error": f"HTTP {response.status}"
                    }
    except Exception as e:
        return {
            "status": "unhealthy",
            "error": str(e)
        }


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Health check utility")
    parser.add_argument("--url", default="http://localhost:8000", help="Base URL to check")
    parser.add_argument("--detailed", action="store_true", help="Run detailed health check")
    args = parser.parse_args()
    
    if args.detailed:
        result = asyncio.run(check_detailed_health(args.url))
    else:
        result = asyncio.run(check_health(args.url))
    
    print(f"Health check result: {result}")
    
    if result["status"] == "healthy":
        sys.exit(0)
    else:
        sys.exit(1)
