#!/usr/bin/env python3
"""
Health check script for MCP server Docker container.

This script verifies that the MCP server environment is healthy
and ready to accept connections.
"""

import os
import sys
from pathlib import Path


def check_environment():
    """Check that required environment variables are set."""
    required_vars = ["GATEWAY_URL"]
    missing = []

    for var in required_vars:
        if not os.environ.get(var):
            missing.append(var)

    if missing:
        print(f"ERROR: Missing environment variables: {', '.join(missing)}")
        return False

    return True


def check_gateway_connectivity():
    """Check if the gateway URL is reachable."""
    import httpx

    gateway_url = os.environ.get("GATEWAY_URL", "http://localhost:8000")

    try:
        # Try to connect to gateway health endpoint
        with httpx.Client(timeout=5.0) as client:
            response = client.get(f"{gateway_url}/health")

            if response.status_code == 200:
                print(f"OK: Gateway reachable at {gateway_url}")
                return True
            else:
                print(f"WARNING: Gateway returned status {response.status_code}")
                return True  # Still healthy, gateway might just be starting

    except Exception as e:
        print(f"WARNING: Cannot reach gateway at {gateway_url}: {e}")
        # Don't fail health check just because gateway is down
        # MCP server can still start and wait for gateway
        return True


def check_python_modules():
    """Check that required Python modules are available."""
    required_modules = ["mcp", "httpx"]
    missing = []

    for module in required_modules:
        try:
            __import__(module)
        except ImportError:
            missing.append(module)

    if missing:
        print(f"ERROR: Missing Python modules: {', '.join(missing)}")
        return False

    print("OK: All required Python modules available")
    return True


def check_tools_directory():
    """Check if tools directory exists and is readable."""
    tools_paths = [
        "/app/generated_tools",
        "./generated_tools",
        "../generated_tools"
    ]

    found = False
    for path in tools_paths:
        if Path(path).exists():
            print(f"OK: Tools directory found at {path}")
            found = True
            break

    if not found:
        print("INFO: No local tools directory found (will fetch from gateway)")

    return True  # Not critical if missing


def main():
    """Run all health checks."""
    print("=== MCP Server Health Check ===")

    checks = [
        ("Environment", check_environment),
        ("Python Modules", check_python_modules),
        ("Gateway Connectivity", check_gateway_connectivity),
        ("Tools Directory", check_tools_directory)
    ]

    all_passed = True

    for name, check_func in checks:
        print(f"\nChecking {name}...")
        try:
            if not check_func():
                all_passed = False
        except Exception as e:
            print(f"ERROR: {name} check failed with exception: {e}")
            all_passed = False

    print("\n=== Health Check Summary ===")
    if all_passed:
        print("Status: HEALTHY")
        sys.exit(0)
    else:
        print("Status: UNHEALTHY")
        sys.exit(1)


if __name__ == "__main__":
    main()
