#!/usr/bin/env python3
"""
Genesis Health Check Server
============================
Simple HTTP server for health monitoring.
Exposes /health endpoint for external monitoring.

Part of Genesis System Hardening (Post-Mortem 2026-01-14)
"""

import os
import sys
import json
import subprocess
from http.server import HTTPServer, BaseHTTPRequestHandler
from datetime import datetime
from pathlib import Path
from typing import Dict

# Try to import redis
try:
    import redis
    HAS_REDIS = True
except ImportError:
    HAS_REDIS = False

# Configuration
HEALTH_PORT = int(os.environ.get("GENESIS_HEALTH_PORT", 8765))
GENESIS_DIR = Path("/mnt/e/genesis-system")

# Redis config
REDIS_CONFIG = {
    "host": "redis-genesis-u50607.vm.elestio.app",
    "port": 26379,
    "password": "e2ZyYYr4oWRdASI2CaLc-",
    "decode_responses": True,
}


def check_process(pattern: str) -> Dict:
    """Check if a process matching pattern is running."""
    try:
        result = subprocess.run(
            ["pgrep", "-f", pattern],
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            pids = [int(p) for p in result.stdout.strip().split('\n') if p]
            return {"running": True, "pids": pids}
        return {"running": False, "pids": []}
    except Exception as e:
        return {"running": False, "error": str(e)}


def check_redis() -> Dict:
    """Check Redis connectivity."""
    if not HAS_REDIS:
        return {"connected": False, "error": "redis module not installed"}

    try:
        r = redis.Redis(**REDIS_CONFIG)
        r.ping()

        # Get queue stats
        pending = r.zcard('genesis:task_queue') or 0
        completed = r.hlen('genesis:completed_tasks') or 0

        return {
            "connected": True,
            "pending_tasks": pending,
            "completed_tasks": completed,
        }
    except Exception as e:
        return {"connected": False, "error": str(e)}


def get_health_status() -> Dict:
    """Get complete health status."""
    status = {
        "timestamp": datetime.now().isoformat(),
        "status": "healthy",
        "components": {},
    }

    # Check processes
    processes = {
        "aiva_orchestrator": "aiva_orchestrator.py",
        "aiva_daemon": "aiva_daemon.py",
        "ralph_orchestrator": "ralph_enhanced_orchestrator.py",
        "watchdog": "aiva_watchdog.py",
    }

    process_status = {}
    unhealthy_count = 0

    for name, pattern in processes.items():
        check = check_process(pattern)
        process_status[name] = check
        if not check.get("running"):
            unhealthy_count += 1

    status["components"]["processes"] = process_status

    # Check Redis
    redis_status = check_redis()
    status["components"]["redis"] = redis_status

    if not redis_status.get("connected"):
        unhealthy_count += 1

    # Overall status
    if unhealthy_count > 2:
        status["status"] = "unhealthy"
    elif unhealthy_count > 0:
        status["status"] = "degraded"

    status["unhealthy_components"] = unhealthy_count

    return status


class HealthHandler(BaseHTTPRequestHandler):
    """HTTP request handler for health checks."""

    def log_message(self, format, *args):
        """Suppress default logging."""
        pass

    def do_GET(self):
        """Handle GET requests."""
        if self.path == "/health" or self.path == "/":
            self._send_health()
        elif self.path == "/health/processes":
            self._send_processes()
        elif self.path == "/health/redis":
            self._send_redis()
        else:
            self._send_404()

    def _send_json(self, data: Dict, status_code: int = 200):
        """Send JSON response."""
        self.send_response(status_code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(json.dumps(data, indent=2).encode())

    def _send_health(self):
        """Send full health status."""
        status = get_health_status()
        code = 200 if status["status"] == "healthy" else 503
        self._send_json(status, code)

    def _send_processes(self):
        """Send process status only."""
        processes = {
            "aiva_orchestrator": check_process("aiva_orchestrator.py"),
            "aiva_daemon": check_process("aiva_daemon.py"),
            "ralph_orchestrator": check_process("ralph_enhanced_orchestrator.py"),
            "watchdog": check_process("aiva_watchdog.py"),
        }
        self._send_json({"processes": processes})

    def _send_redis(self):
        """Send Redis status only."""
        self._send_json({"redis": check_redis()})

    def _send_404(self):
        """Send 404 response."""
        self._send_json({"error": "Not found"}, 404)


def main():
    """Start health check server."""
    print(f"Starting Genesis Health Server on port {HEALTH_PORT}")
    print(f"Endpoints:")
    print(f"  http://localhost:{HEALTH_PORT}/health")
    print(f"  http://localhost:{HEALTH_PORT}/health/processes")
    print(f"  http://localhost:{HEALTH_PORT}/health/redis")

    server = HTTPServer(("0.0.0.0", HEALTH_PORT), HealthHandler)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nShutting down health server")
        server.shutdown()


if __name__ == "__main__":
    main()
