#!/usr/bin/env python3
import http.server, subprocess, json, os

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory="/root", **kwargs)

    def do_GET(self):
        if self.path == "/status":
            try:
                # Run remote status script via SSH
                result = subprocess.run(
                    ["sshpass", "-p", "elon-is-insane", "ssh",
                     "-o", "ProxyCommand=tailscale nc %h %p",
                     "-o", "StrictHostKeyChecking=no",
                     "-o", "ConnectTimeout=5",
                     "michtest@100.113.88.121",
                     "python3 /tmp/remote_status.py"],
                    capture_output=True, text=True, timeout=15
                )
                body = result.stdout.strip()
                # Validate it's JSON
                json.loads(body)
            except json.JSONDecodeError:
                body = json.dumps({"phase": "parse_error", "detail": body[:200] if body else "empty"})
            except Exception as e:
                body = json.dumps({"phase": "unreachable", "detail": str(e)[:200]})

            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(body.encode())
        else:
            super().do_GET()

    def log_message(self, format, *args):
        pass

if __name__ == "__main__":
    # Upload remote_status.py once at startup
    subprocess.run(
        ["sshpass", "-p", "elon-is-insane", "scp",
         "-o", "ProxyCommand=tailscale nc %h %p",
         "-o", "StrictHostKeyChecking=no",
         "/root/remote_status.py", "michtest@100.113.88.121:/tmp/remote_status.py"],
        capture_output=True, timeout=15
    )
    server = http.server.HTTPServer(("0.0.0.0", 8080), Handler)
    print("Serving on http://0.0.0.0:8080")
    server.serve_forever()
