// bun check.ts           the pure rules
// bun check.ts --live    the server end to end, real sockets, each part on a fresh server
// bun check.ts --hold N  take N seats, print them one per line, hold them for 60 s
import { networkInterfaces } from "node:os";
import { DEFAULT_F0, caption, hz, seatLimit, settle } from "./tuning.js";

const PORT = Number(process.env.PORT) || 18808;
let failed = 0;

function ok(cond: unknown, what: string) {
  console.log(`${cond ? "ok  " : "FAIL"} ${what}`);
  if (!cond) failed++;
}
const eq = (got: unknown, want: unknown, what: string) =>
  ok(JSON.stringify(got) === JSON.stringify(want), `${what}: ${JSON.stringify(got)}${JSON.stringify(got) === JSON.stringify(want) ? "" : ` (want ${JSON.stringify(want)})`}`);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/* pure */

function pure() {
  const table: [number, string, string][] = [
    [2, "392.00", "G4, 0.0 cents"],
    [3, "587.99", "D5, 2.0 cents sharp"],
    [4, "783.99", "G5, 0.0 cents"],
    [5, "979.99", "B5, 13.7 cents flat"],
    [6, "1175.99", "D6, 2.0 cents sharp"],
    [7, "1371.98", "F6, 31.2 cents flat"],
    [8, "1567.98", "G6, 0.0 cents"],
    [9, "1763.98", "A6, 3.9 cents sharp"],
    [10, "1959.98", "B6, 13.7 cents flat"],
    [11, "2155.97", "C#7, 48.7 cents flat"],
    [12, "2351.97", "D7, 2.0 cents sharp"],
    [13, "2547.97", "D#7, 40.5 cents sharp"],
    [14, "2743.97", "F7, 31.2 cents flat"],
    [15, "2939.97", "F#7, 11.7 cents flat"],
  ];
  for (const [n, h, c] of table) eq([hz(n, DEFAULT_F0).toFixed(2), caption(hz(n, DEFAULT_F0))], [h, c], `seat ${n}`);
  eq(DEFAULT_F0.toFixed(4), "195.9977", "DEFAULT_F0");
  eq([seatLimit(150), seatLimit(DEFAULT_F0), seatLimit(260)], [20, 15, 11], "seatLimit at 150, default, 260");
  eq(hz(2, 150), 300, "hz(2, 150)");
  eq(caption(440), "A4, 0.0 cents", "caption(440)");
  eq(caption(450), "A4, 38.9 cents sharp", "caption(450)");

  const seats = (list: { seat: number | null }[]) => list.map((t) => t.seat);
  const fresh = (n: number) => Array.from({ length: n }, (_, i) => ({ no: i + 1, seat: null as number | null }));

  let s = settle(DEFAULT_F0, fresh(3));
  eq(seats(s), [2, 3, 4], "three new tickets");
  s = settle(DEFAULT_F0, [...s.filter((t) => t.no !== 2), { no: 4, seat: null }]);
  eq(seats(s), [2, 4, 3], "ticket 2 gone, the next new ticket takes 3");

  s = settle(DEFAULT_F0, fresh(12));
  eq(seats(s), [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], "tickets 1 to 12 at the default");
  s = settle(260, s);
  eq(seats(s), [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, null, null], "key 260: tickets 1 to 10 keep 2 to 11, 11 and 12 stand");
  s = settle(260, s.filter((t) => t.no !== 3));
  eq(seats(s), [2, 3, 5, 6, 7, 8, 9, 10, 11, 4, null], "ticket 3 deleted: ticket 11 takes 4, ticket 12 stands");

  eq(seats(settle(DEFAULT_F0, [{ no: 1, seat: 5 }, { no: 2, seat: 5 }])), [5, 2], "two claim seat 5: the lower number keeps it");
  eq(seats(settle(DEFAULT_F0, [{ no: 1, seat: 1 }, { no: 2, seat: 16 }, { no: 3, seat: 0 }])), [2, 3, 4], "seat 1, 16 and 0 are never kept");
  const crowd = settle(150, fresh(40));
  ok(crowd.every((t) => t.seat === null || (t.seat >= 2 && t.seat <= 20)), "40 tickets at 150: no seat 1, none above 20");
  eq(crowd.filter((t) => t.seat !== null).length, 19, "40 tickets at 150: 19 seated");
}

/* sockets */

type Msg = any;
class Client {
  ws: WebSocket;
  msgs: Msg[] = [];
  private waiters: (() => void)[] = [];
  closed = false;
  constructor(url: string) {
    this.ws = new WebSocket(url);
    this.ws.onmessage = (e) => {
      this.msgs.push(JSON.parse(String(e.data)));
      for (const w of this.waiters.splice(0)) w();
    };
    this.ws.onclose = () => (this.closed = true);
  }
  get last() {
    return this.msgs[this.msgs.length - 1];
  }
  /** Resolve with the first message from index `from` on that passes `pred`. */
  async until(pred: (m: Msg) => boolean, ms = 2000, from = 0): Promise<Msg> {
    const end = Date.now() + ms;
    for (;;) {
      const hit = this.msgs.slice(from).find(pred);
      if (hit) return hit;
      const left = end - Date.now();
      if (left <= 0) throw new Error(`no matching message within ${ms} ms`);
      await Promise.race([new Promise<void>((r) => this.waiters.push(r)), sleep(left)]);
    }
  }
  close(code?: number) {
    this.ws.close(code);
  }
}

const seatUrl = (host: string, token?: string) => `ws://${host}:${PORT}/ws/seat${token ? `?ticket=${token}` : ""}`;
const planUrl = (host: string) => `ws://${host}:${PORT}/ws/plan`;
const stateOf = (m: Msg, n: number) => m.seats.find((s: Msg) => s.seat === n)?.state;

async function seat(host = "localhost", token?: string) {
  const c = new Client(seatUrl(host, token));
  await c.until((m) => m.t === "seat");
  return c;
}

async function startServer() {
  const proc = Bun.spawn(["bun", "serve.ts"], { cwd: import.meta.dir, env: { ...process.env, PORT: String(PORT) }, stdout: "pipe" });
  const reader = proc.stdout.getReader();
  const dec = new TextDecoder();
  let out = "";
  const pump = (async () => {
    for (;;) {
      const { value, done } = await reader.read();
      if (done) return;
      out += dec.decode(value);
    }
  })();
  const end = Date.now() + 5000;
  while (!out.includes("Try a phone hotspot.")) {
    if (Date.now() > end) throw new Error(`server did not start: ${out}`);
    await sleep(20);
  }
  return {
    lines: () => out.trimEnd().split("\n"),
    async stop() {
      proc.kill("SIGINT");
      const code = await proc.exited;
      await pump;
      return { code, lines: out.trimEnd().split("\n") };
    },
  };
}

function checkStartText(lines: string[]) {
  const phones = lines.filter((l) => l.startsWith("Phones"));
  console.log(lines.slice(0, 4 + phones.length).map((l) => `     | ${l}`).join("\n"));
  eq(lines[0], "Seating Plan", "start line 1");
  eq(lines[1], `Plan, on this machine: http://localhost:${PORT}/plan`, "start line 2");
  ok(phones.length >= 1 && phones.every((l) => /^Phones, on the same Wi-Fi: http:\/\/[\d.]+:\d+$/.test(l) || l === "Phones: no network address found."), "Phones lines");
  eq(lines[2 + phones.length], "Seat 1 is never assigned.", "start Seat 1 line");
  eq(lines[3 + phones.length], "If a phone cannot open the address, the network is keeping devices apart. Try a phone hotspot.", "start hotspot line");
}

async function liveSeating() {
  console.log("\n# check 2: seating, away, grace, leave");
  const srv = await startServer();
  checkStartText(srv.lines());
  const plan = new Client(planUrl("localhost"));
  await plan.until((m) => m.t === "plan");
  const [A, B, C, D] = [await seat(), await seat(), await seat(), await seat()];
  eq([A, B, C, D].map((c) => [c.last.no, c.last.seat]), [[1, 2], [2, 3], [3, 4], [4, 5]], "A B C D: [ticket, seat]");
  let m = await plan.until((p) => p.held === 4);
  eq(m.seats.map((s: Msg) => s.state), ["vacant", "taken", "taken", "taken", "taken", ...Array(10).fill("available")], "plan states");
  eq(m.held, 4, "held");

  let from = plan.msgs.length;
  const tB = Date.now();
  B.close();
  await plan.until((p) => stateOf(p, 3) === "away", 500, from);
  ok(true, `seat 3 away after ${Date.now() - tB} ms`);

  const E = await seat();
  eq(E.last.seat, 6, "E takes seat 6");

  const cToken = C.last.token;
  C.close();
  await sleep(3000);
  const C2 = await seat("localhost", cToken);
  eq([C2.last.no, C2.last.seat], [3, 4], "C back after 3 s: [ticket, seat]");

  await sleep(Math.max(0, tB + 16000 - Date.now()));
  eq(stateOf(plan.last, 3), "available", `seat 3 at ${((Date.now() - tB) / 1000).toFixed(1)} s after B closed`);
  const F = await seat();
  eq(F.last.seat, 3, "F takes seat 3");

  const G = await seat();
  eq(G.last.seat, 7, "G takes seat 7");
  from = plan.msgs.length;
  const tG = Date.now();
  G.close(4000);
  await plan.until((p) => stateOf(p, 7) === "available", 500, from);
  ok(true, `seat 7 available after ${Date.now() - tG} ms`);
  ok(!plan.msgs.slice(from).some((p) => stateOf(p, 7) === "away"), "seat 7 never shown away after Leave");

  const { code, lines } = await srv.stop();
  console.log(`     | ${lines[lines.length - 1]}`);
  eq(lines[lines.length - 1], "Closed. Tickets issued: 7. Most seats held at once: 6.", "closing line");
  eq(code, 0, "exit code");
}

function lanAddress() {
  return Object.values(networkInterfaces())
    .flat()
    .find((a: any) => a && !a.internal && (a.family === "IPv4" || a.family === 4))?.address;
}

async function liveHost() {
  console.log("\n# check 3: host control and its limits");
  const srv = await startServer();
  const S = [await seat(), await seat()];
  const plan = new Client(planUrl("localhost"));
  await plan.until((m) => m.t === "plan");
  eq(plan.last.host, true, "localhost plan is host");

  const setKey = async (value: number) => {
    const from = plan.msgs.length;
    plan.ws.send(JSON.stringify({ t: "f0", hz: value }));
    try {
      return await plan.until(() => true, 500, from);
    } catch {
      return null;
    }
  };
  let m = await setKey(220);
  for (const s of S) await s.until((x) => x.f0 === 220);
  ok(S.every((s) => s.last.f0 === 220), "every seat client got f0 220");
  eq(`Key of the house: ${m.f0.toFixed(3)} Hz, ${caption(m.f0)}`, "Key of the house: 220.000 Hz, A3, 0.0 cents", "plan key");
  eq(m.limit, 13, "limit at 220");
  eq([await setKey(100), await setKey(300), plan.last.f0], [null, null, 220], "100 and 300 ignored, f0 still 220");
  m = await setKey(150);
  eq([m?.f0, m?.limit], [150, 20], "150 accepted");
  m = await setKey(260);
  eq([m?.f0, m?.limit], [260, 11], "260 accepted");

  const lan = lanAddress();
  if (!lan) {
    console.log("note: no LAN address on this machine, remote plan check skipped");
  } else {
    const remote = new Client(planUrl(lan));
    await remote.until((x) => x.t === "plan");
    eq(remote.last.host, false, `plan via ${lan} is not host`);
    const from = plan.msgs.length;
    remote.ws.send(JSON.stringify({ t: "f0", hz: 220 }));
    await sleep(500);
    eq([plan.msgs.length - from, plan.last.f0], [0, 260], "key change from the LAN plan ignored");
  }
  const { code } = await srv.stop();
  eq(code, 0, "exit code");
}

async function liveFloorGap() {
  console.log("\n# check 7: floor, ceiling and gap");
  const srv = await startServer();
  const plan = new Client(planUrl("localhost"));
  await plan.until((m) => m.t === "plan");
  plan.ws.send(JSON.stringify({ t: "f0", hz: 150 }));
  let m = await plan.until((x) => x.f0 === 150);
  eq([m.seats.length, `${hz(2, m.f0).toFixed(2)} Hz`], [20, "300.00 Hz"], "key 150: cells, seat 2");
  plan.ws.send(JSON.stringify({ t: "f0", hz: 260 }));
  m = await plan.until((x) => x.f0 === 260);
  eq(m.seats.length, 11, "key 260: cells");

  const X = [await seat(), await seat(), await seat()];
  eq(X.map((c) => c.last.seat), [2, 3, 4], "three seated");
  const t = Date.now();
  X[1].close();
  await sleep(1000);
  eq((await seat()).last.seat, 5, "join 1 s after seat 3 closed takes 5");
  await sleep(t + 14000 - Date.now());
  eq((await seat()).last.seat, 6, "join 14 s after takes 6");
  await sleep(t + 15600 - Date.now());
  eq((await seat()).last.seat, 3, "join 15.6 s after takes 3");
  const { code } = await srv.stop();
  eq(code, 0, "exit code");
}

async function hold(n: number) {
  const held: Client[] = [];
  for (let i = 0; i < n; i++) {
    const c = await seat();
    held.push(c);
    console.log(c.last.seat ?? "standing");
  }
  await sleep(60000);
  for (const c of held) c.close(4000);
}

const args = process.argv.slice(2);
if (args[0] === "--hold") {
  await hold(Number(args[1]) || 1);
  process.exit(0);
}
pure();
if (args[0] === "--live") {
  await liveSeating();
  await liveHost();
  await liveFloorGap();
}
console.log(failed ? `\n${failed} failed` : "\nall passed");
process.exit(failed ? 1 : 0);
