#!/usr/bin/env python3
"""Unified health check endpoint for TipSharks stack.

Runs on port 8082 by default.
Reports health status of all three services.
Zero external dependencies — uses only stdlib.
"""

import json
import urllib.request
import urllib.error
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
from datetime import datetime

SERVICES = {
    "tab-api-ingest": "http://localhost:9090/health",
    "tipsharks-elo-api": "http://localhost:8000/health",
    "tipsharks-client-backend": "http://localhost:8001/api/health",
}


def check_service(name: str, url: str) -> dict:
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            body = resp.read()
            data = json.loads(body) if body else {}
            return {
                "name": name,
                "url": url,
                "status": "healthy" if resp.status == 200 else "degraded",
                "response": data,
            }
    except urllib.error.HTTPError as e:
        return {
            "name": name,
            "url": url,
            "status": "degraded",
            "error": f"HTTP {e.code}: {e.reason}",
        }
    except urllib.error.URLError as e:
        return {
            "name": name,
            "url": url,
            "status": "unhealthy",
            "error": f"Connection failed: {e.reason}",
        }
    except Exception as e:
        return {
            "name": name,
            "url": url,
            "status": "unhealthy",
            "error": str(e),
        }


class HealthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/health":
            results = {name: check_service(name, url) for name, url in SERVICES.items()}
            overall = (
                "healthy"
                if all(r["status"] == "healthy" for r in results.values())
                else "degraded"
            )

            response = {
                "status": overall,
                "services": results,
                "timestamp": datetime.utcnow().isoformat() + "Z",
            }

            status_code = 200 if overall == "healthy" else 503
            body = json.dumps(response, indent=2).encode()

            self.send_response(status_code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(
                json.dumps({"error": "Not found", "path": self.path}).encode()
            )

    def log_message(self, format, *args):
        pass  # Suppress default HTTP log spam


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="TipSharks unified health check server"
    )
    parser.add_argument(
        "--port", type=int, default=8082, help="Port to listen on (default: 8082)"
    )
    parser.add_argument(
        "--bind",
        type=str,
        default="0.0.0.0",
        help="Address to bind to (default: 0.0.0.0)",
    )
    args = parser.parse_args()

    server = HTTPServer((args.bind, args.port), HealthHandler)
    print(f"Health check server running on http://{args.bind}:{args.port}/health")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nShutting down health check server.")
        server.server_close()
