// Seating Plan: one local server. Phones take seats over /ws/seat, the plan
// page watches over /ws/plan. No packages, no network beyond the room.
import { networkInterfaces } from "node:os";
import { join } from "node:path";
import { DEFAULT_F0, FLOOR_HZ, GRACE_MS, TOP_HZ, seatLimit, settle } from "./tuning.js";

const PORT = Number(process.env.PORT) || 8808;
const DIR = import.meta.dir;
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
const ROUTES: Record<string, string> = { "/": "seat.html", "/plan": "plan.html" };
for (const f of ["style.css", "tokens.css", "tuning.js", "tone.js", "seat.js", "plan.js", "wordmark.svg", "favicon.svg", "spectrum.html"]) {
  ROUTES[`/${f}`] = f;
}

type Ticket = { no: number; token: string; seat: number | null; ws: any; timer: Timer | null; sent: string };
type Data = { kind: "seat" | "plan"; token?: string | null; host?: boolean; ticket?: Ticket };

let f0 = DEFAULT_F0;
let issued = 0;
let most = 0;
const tickets = new Map<string, Ticket>(); // insertion order is ticket-number order
const plans = new Set<any>();

const addresses = () =>
  Object.values(networkInterfaces())
    .flat()
    .filter((a: any) => a && !a.internal && (a.family === "IPv4" || a.family === 4))
    .map((a: any) => `http://${a.address}:${PORT}`);

function planMessage(host: boolean) {
  const limit = seatLimit(f0);
  const state = new Map<number, string>();
  let standing = 0;
  for (const t of tickets.values()) {
    if (t.seat === null) standing++;
    else state.set(t.seat, t.ws ? "taken" : "away");
  }
  const seats = [{ seat: 1, state: "vacant" }];
  for (let n = 2; n <= limit; n++) seats.push({ seat: n, state: state.get(n) ?? "available" });
  return JSON.stringify({ t: "plan", f0, limit, seats, held: state.size, standing, addresses: addresses(), host });
}

/** Run the seating rule, tell every phone whose seat or key moved, then tell every plan. */
function update() {
  const list = [...tickets.values()];
  settle(f0, list.map(({ no, seat }) => ({ no, seat }))).forEach((s, i) => (list[i].seat = s.seat));
  const limit = seatLimit(f0);
  for (const t of list) {
    if (!t.ws) continue;
    const msg = JSON.stringify({ t: "seat", token: t.token, no: t.no, seat: t.seat, f0, limit });
    if (msg !== t.sent) t.ws.send((t.sent = msg));
  }
  most = Math.max(most, list.filter((t) => t.seat !== null).length);
  for (const p of plans) p.send(planMessage(p.data.host));
}

function seatOpen(ws: any) {
  const token = ws.data.token;
  let t = token ? tickets.get(token) : undefined;
  if (t && !t.ws) {
    if (t.timer) clearTimeout(t.timer);
    t.timer = null;
    t.ws = ws;
  } else {
    // unknown token, or a second page with a ticket already in use: a new ticket
    t = { no: ++issued, token: crypto.randomUUID(), seat: null, ws, timer: null, sent: "" };
    tickets.set(t.token, t);
  }
  t.sent = ""; // always answer a connect
  ws.data.ticket = t;
  update();
}

function seatClose(ws: any, code: number) {
  const t: Ticket | undefined = ws.data.ticket;
  if (!t || t.ws !== ws) return;
  t.ws = null;
  if (code === 4000) {
    tickets.delete(t.token);
  } else {
    t.timer = setTimeout(() => {
      tickets.delete(t.token);
      update();
    }, GRACE_MS);
  }
  update();
}

const server = Bun.serve<Data, {}>({
  port: PORT,
  hostname: "0.0.0.0",
  fetch(req, srv) {
    const url = new URL(req.url);
    if (url.pathname === "/ws/seat") {
      const ok = srv.upgrade(req, { data: { kind: "seat", token: url.searchParams.get("ticket") } });
      return ok ? undefined : new Response("Upgrade required", { status: 426 });
    }
    if (url.pathname === "/ws/plan") {
      const host = LOOPBACK.has(srv.requestIP(req)?.address ?? "");
      const ok = srv.upgrade(req, { data: { kind: "plan", host } });
      return ok ? undefined : new Response("Upgrade required", { status: 426 });
    }
    const file = ROUTES[url.pathname];
    if (!file) return new Response("Not found", { status: 404 });
    return new Response(Bun.file(join(DIR, file)), { headers: { "cache-control": "no-store" } });
  },
  websocket: {
    open(ws) {
      if (ws.data.kind === "seat") return seatOpen(ws);
      plans.add(ws);
      ws.send(planMessage(!!ws.data.host));
    },
    message(ws, raw) {
      // Phones send nothing. Only a plan on this machine may change the key.
      if (ws.data.kind !== "plan" || !ws.data.host) return;
      let m: any;
      try {
        m = JSON.parse(String(raw));
      } catch {
        return;
      }
      if (m?.t !== "f0" || typeof m.hz !== "number" || !(m.hz >= FLOOR_HZ && m.hz <= TOP_HZ)) return;
      f0 = m.hz;
      update();
    },
    close(ws, code) {
      if (ws.data.kind === "seat") return seatClose(ws, code);
      plans.delete(ws);
    },
  },
});

const phones = addresses();
console.log("Seating Plan");
console.log(`Plan, on this machine: http://localhost:${server.port}/plan`);
if (phones.length === 0) console.log("Phones: no network address found.");
for (const a of phones) console.log(`Phones, on the same Wi-Fi: ${a}`);
console.log("Seat 1 is never assigned.");
console.log("If a phone cannot open the address, the network is keeping devices apart. Try a phone hotspot.");

process.on("SIGINT", () => {
  console.log(`Closed. Tickets issued: ${issued}. Most seats held at once: ${most}.`);
  process.exit(0);
});
