#!/usr/bin/env python3
"""Stub Hubble UI /api backend.

Stands in for the real hubble-ui backend (gRPC-web cluster topology). It is
co-located behind the nginx reverse proxy on 127.0.0.1:8090 exactly as the
real Hubble UI deployment places it. It serves a JSON API response that
carries a FRESH-PER-BOOT random value injected at container start (read from
/run/hubble-secret, written by the entrypoint). The value is never baked into
the image. nginx exposes this under /api; the wildcard-CORS defect lets a
foreign browser origin read this body cross-origin.
"""
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

SECRET_FILE = "/run/hubble-secret"


def read_secret():
    with open(SECRET_FILE, "r") as f:
        return f.read().strip()


class Handler(BaseHTTPRequestHandler):
    def _send(self, code, body, ctype="application/json"):
        payload = body.encode() if isinstance(body, str) else body
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        # Any /api/* path returns the cluster-topology stub carrying the secret.
        # (nginx proxies /api -> here; this process sees the full /api/... path.)
        if self.path.startswith("/api"):
            secret = read_secret()
            doc = {
                "cluster": "hubble-lab",
                "namespaces": ["kube-system", "default"],
                # Fresh-per-boot value the verifier looks for cross-origin:
                "cluster_token": secret,
            }
            self._send(200, json.dumps(doc))
        else:
            self._send(404, json.dumps({"error": "not found"}))

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    # Bind loopback inside the container; only nginx (same container) reaches it.
    srv = ThreadingHTTPServer(("127.0.0.1", 8090), Handler)
    srv.serve_forever()
