#!/usr/bin/env python3
"""X4 briefing-card server.

Serves /opt/x4-cards statically (card PNGs/BMPs) plus one smart endpoint:

    /cards/auto.bmp  ->  morning or nightstand card, chosen by
                         America/Toronto time (weekend variants Sat/Sun).

Lets the X4 auto-switch between morning/night cards from a single slot URL.
"""

import datetime
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from zoneinfo import ZoneInfo

ROOT = "/opt/x4-cards"
TZ = ZoneInfo("America/Toronto")

# Night card shown 21:00 -> 05:59 (wind-down ~21:41, briefing ~07:00).
NIGHT_START = 21
MORNING_START = 6


def pick_card(now=None):
    now = now or datetime.datetime.now(TZ)
    part = "nightstand" if (now.hour >= NIGHT_START or now.hour < MORNING_START) else "morning"
    suffix = "_weekend" if now.weekday() >= 5 else ""
    return os.path.join(ROOT, "cards", "%s%s.bmp" % (part, suffix))


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

    def log_message(self, *args):
        pass  # quiet

    def do_GET(self):
        if self.path.split("?")[0] == "/cards/auto.bmp":
            fp = pick_card()
            try:
                with open(fp, "rb") as f:
                    body = f.read()
            except OSError:
                self.send_error(404, "card not rendered yet")
                return
            self.send_response(200)
            self.send_header("Content-Type", "image/bmp")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-cache, no-store")
            self.end_headers()
            self.wfile.write(body)
            return
        return super().do_GET()


if __name__ == "__main__":
    srv = ThreadingHTTPServer(("0.0.0.0", 8080), Handler)
    print("x4-cards serving on :8080  (auto.bmp -> %s)" % pick_card(), flush=True)
    srv.serve_forever()
