#!/usr/bin/env python3
# Serves the brew dashboard's static files (same as `python3 -m http.server`)
# plus a small JSON API so brew profiles live on the server instead of being
# stuck in one browser's localStorage. That's what makes the dashboard show
# the same active brew/chart from any device or origin (LAN IP vs the
# duckdns HTTPS domain both proxy here).
import json
import threading
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

PORT = 8099
ROOT = Path(__file__).resolve().parent
PROFILES_FILE = ROOT / "profiles.json"
LOCK = threading.Lock()


def read_profiles():
    with LOCK:
        if not PROFILES_FILE.exists():
            return []
        try:
            return json.loads(PROFILES_FILE.read_text())
        except (json.JSONDecodeError, OSError):
            return []


def write_profiles(data):
    tmp = PROFILES_FILE.with_suffix(".json.tmp")
    with LOCK:
        tmp.write_text(json.dumps(data))
        tmp.replace(PROFILES_FILE)


class Handler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(ROOT), **kwargs)

    def do_GET(self):
        if self.path.split("?", 1)[0] == "/api/profiles":
            body = json.dumps(read_profiles()).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(body)
            return
        super().do_GET()

    def do_POST(self):
        if self.path.split("?", 1)[0] != "/api/profiles":
            self.send_error(404)
            return
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length) if length else b"[]"
        try:
            data = json.loads(raw)
        except json.JSONDecodeError:
            self.send_error(400, "Invalid JSON")
            return
        if not isinstance(data, list):
            self.send_error(400, "Expected a JSON array")
            return
        write_profiles(data)
        self.send_response(204)
        self.end_headers()


if __name__ == "__main__":
    server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler)
    print(f"Serving brew dashboard on :{PORT} (profiles backed by {PROFILES_FILE})")
    server.serve_forever()
