"""Tiny local dashboard (video style). Serves dashboard/index.html and state/status.json on 127.0.0.1."""
from http.server import BaseHTTPRequestHandler, HTTPServer
from .config import ROOT, STATE


class H(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith("/status.json"):
            p, ctype = STATE / "status.json", "application/json"
        elif self.path.startswith("/brain"):
            p, ctype = ROOT / "dashboard" / "brain.html", "text/html; charset=utf-8"
        else:
            p, ctype = ROOT / "dashboard" / "index.html", "text/html; charset=utf-8"
        body = p.read_bytes() if p.exists() else b"{}"
        self.send_response(200)
        self.send_header("Content-Type", ctype)
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *a):
        pass


def serve(port=8787):
    print(f"Dashboard: http://127.0.0.1:{port}   (Ctrl+C to stop)")
    HTTPServer(("127.0.0.1", port), H).serve_forever()
