#!/usr/bin/env python3
import subprocess
from http.server import HTTPServer, BaseHTTPRequestHandler

class H(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            uptime = subprocess.check_output(["uptime", "-p"], text=True).strip()
        except:
            uptime = "unknown"
        try:
            with open("/proc/loadavg") as f:
                load = f.read().split()[0]
        except:
            load = "?"
        try:
            with open("/proc/meminfo") as f:
                lines = f.readlines()
                total = int(lines[0].split()[1]) // 1024
                avail = int(lines[2].split()[1]) // 1024
                mem = str(total - avail) + "/" + str(total) + " MB"
        except:
            mem = "?"

        out = []
        out.append("<!DOCTYPE html><html><head><title>VPS Hetzner Status</title>")
        out.append("<meta charset='utf-8'>")
        out.append("<meta http-equiv='refresh' content='10'>")
        out.append("<style>")
        out.append("body{font-family:sans-serif;background:#0a0e27;color:#e0e0e0;padding:30px;margin:0;}")
        out.append("h1{color:#4fc3f7;}h2{color:#4fc3f7;margin-top:30px;}")
        out.append(".card{background:#1a1f3a;padding:20px;border-radius:8px;margin:10px 0;}")
        out.append(".ok{color:#4caf50;}.err{color:#f44336;}.warn{color:#ff9800;}")
        out.append("code{background:#0a0e27;padding:2px 6px;border-radius:3px;color:#4fc3f7;}")
        out.append("</style></head><body>")
        out.append("<h1>Charter VPS Hetzner - Live Status</h1>")
        out.append("<div class='card'>")
        out.append("<p>Uptime: <code>" + uptime + "</code></p>")
        out.append("<p>Load: <code>" + load + "</code></p>")
        out.append("<p>Memory: <code>" + mem + "</code></p>")
        out.append("</div>")
        out.append("<h2>Servizi Python</h2><div class='card'><ul>")
        for proc in ["webhook_receiver", "trailing_stop_watchdog", "integrity_watchdog", "rettangolo_runner", "mavis_supervisor_3", "generate_tableau"]:
            running = subprocess.run(["pgrep", "-f", proc], capture_output=True).returncode == 0
            color = "ok" if running else "err"
            status = "RUNNING" if running else "STOPPED"
            out.append("<li class='" + color + "'>" + proc + ": " + status + "</li>")
        out.append("</ul></div>")
        out.append("</body></html>")
        body = "".join(out).encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def do_HEAD(self):
        """UptimeRobot usa HEAD (non GET) per i check veloci.
        Rispondo 200 OK senza body."""
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", "1036")
        self.end_headers()

    def log_message(self, *a): pass

HTTPServer(("0.0.0.0", 10001), H).serve_forever()
