/* The runner: this studio, reached from the hosted one (cloud/studio). It opens a WebSocket to the
   cloud's RunnerHub and answers each request that arrives on it with the same Hono app the local
   server uses, so every route, check and tool call is the one that runs at 127.0.0.1. Protocol in
   tools/lib/channel.mjs; the plan in docs/specs/phase-1-split-api.md.

   The file routes answer Range themselves (api/lib/runtime.ts `fileResponse`); a media response that does not
   (a Blob from somewhere else) still gets its 206 here, from a slice of the Blob. */

import { hostname } from "node:os";
import { PROTOCOL, Peer, REPLACED, REVOKED, UPGRADE } from "../../tools/lib/channel.mjs";
import type { ReconnectResult } from "./control";

/* the file routes of api/app.ts (API_PREFIXES) a player may ask a range of */
const MEDIA_PREFIXES = [
  "/media/",
  "/ref/",
  "/kit/",
  "/sound-draft/",
  "/docs/",
  "/api/voice-sample/",
  "/api/voice-original/",
];
const PING_MS = 30_000;
const DEAD_MS = 75_000;
/* without a login or a key (never entered, disconnected at /runner): how often to look for one */
const KEY_CHECK_MS = 30_000;
/* How long the hub has to answer the upgrade: a handshake nobody answers (a hub that is restarting, a request the cloud holds) leaves the socket "connecting" and the runner
   silent, the library giving up only after minutes (undici waits five for an upgrade's answer), and the hosted page says offline all that time. */
const HANDSHAKE_MS = 20_000;
/* a connection that stays down says so again this often, instead of only once */
const DOWN_REMINDER_MS = 5 * 60_000;
/* How long the login (a refresh) and the key check may take before the attempt goes on without them. Both are fetches,
   and one sent just as the network drops can hang with no answer: the attempt waited on it forever and never set its
   next try, so the computer stayed off the hosted studio until the studio was restarted (2026-10-25). */
const CALL_MS = 20_000;
/* The watchdog: not connected, nothing opening and no try for this long means the loop stopped for a reason nobody
   foresaw, and it starts again. Longer than any wait the loop sets for itself (60 s of backoff, a minute for a
   protocol, the key check) plus the calls' own limit. */
const STALL_MS = 3 * 60_000;
const WATCHDOG_MS = 30_000;

/** `p`, or `fallback` once `ms` have passed without an answer */
function within<T>(p: Promise<T>, ms: number, fallback: T): Promise<T> {
  let t: ReturnType<typeof setTimeout> | undefined;
  const late = new Promise<T>(r => (t = setTimeout(() => r(fallback), ms)));
  return Promise.race([p, late]).finally(() => clearTimeout(t));
}
/* The approval page never opens by itself: a computer left on without a login (never entered, signed out, disconnected
   at the studio) waits quietly, looking for a login every keyCheckMs, and connects as soon as one is made: the hosted
   page's "Reconectar agora" (`reconnectNow`), `omni login`, Omni's omni_login or the installer. Before, it opened the
   page at every start, again soon after one nobody answered and every 6 h, on computers nobody was using. */

/** The credential the runner connects with: the account login (refreshed as needed) before the Phase 1 key. A login
 *  that is in the Keychain but can't be refreshed right now (offline, another process renewing it) gives nothing for
 *  the moment, not the old key: the hub refuses that one, and the computer would wait for a login it already has. */
export async function runnerToken(d: {
  login: () => Promise<string | null>;
  hasLogin: () => boolean;
  key: () => string | undefined;
}): Promise<string> {
  const login = await d.login().catch(() => null);
  if (login) return login;
  if (d.hasLogin()) return "";
  return d.key() ?? "";
}

export type RunnerOptions = {
  /** the hosted studio, https://… */
  url: string;
  /** the Mac's credential, read on every attempt: the OAuth access token of `node tools/omni.mjs login`
   *  (refreshed as needed) or a Phase 1 key (OMNIVIDEO_RUNNER_TOKEN, made before the pairing was turned off)
   *  so a fresh login connects without restarting the studio */
  token: () => string | Promise<string>;
  /** the local server's port: the requests are rewritten to it, so `localOnly` admits them */
  port: number;
  handle: (request: Request) => Response | Promise<Response>;
  log?: (line: string) => void;
  /** whether the cloud still takes this key: false only when it says so (tools/lib/pairing.mjs checkKey). A refused
   *  key is set aside, and the computer waits for a login like one that has none */
  checkKey?: (token: string) => Promise<{ valid: boolean | null }>;
  /** signs this computer in: opens the approval page in the browser and waits for the user to approve
   *  (tools/lib/oauth-client.mjs login). Only when the user asks (`reconnectNow`), never by itself */
  login?: () => Promise<void>;
  /** the hub says this machine and the hosted studio speak different protocols (UPGRADE). Which side is old isn't
   *  in the close reason, so whoever answers this looks (tools/lib/self-update.mjs: is there a newer version of
   *  the CLI?) and updates this machine when it is the one behind. Called on every retry, a minute apart. */
  onOutdated?: () => void | Promise<void>;
  /** the waits, in ms; the tests shorten them */
  handshakeMs?: number;
  keyCheckMs?: number;
  protocolRetryMs?: number;
  callMs?: number;
  stallMs?: number;
  watchdogMs?: number;
  /** after another studio took the hosted one over, how often this one asks whether the place is free again */
  replacedCheckMs?: number;
};

/* how often a replaced runner looks for the place to be free again (the other computer turned off, its studio died) */
const REPLACED_CHECK_MS = 2 * 60_000;
/* the header of such a look: the hub connects it only when no other runner holds the place (cloud/studio/src/worker.mjs) */
export const YIELD_HEADER = "x-ov-yield";

/** Range on a media response: 206 from a Blob slice, 416 out of bounds; the rest as it is. */
export async function withRange(request: Request, res: Response): Promise<Response> {
  const path = new URL(request.url).pathname;
  if (!MEDIA_PREFIXES.some(p => path.startsWith(p)) || res.status !== 200 || !res.body) return res;
  /* already ranged by the file route: reading it into a Blob here would load the whole file */
  if (res.headers.has("accept-ranges")) return res;
  const blob = await res.blob();
  const headers = new Headers(res.headers);
  headers.set("accept-ranges", "bytes");
  if (blob.type && !headers.has("content-type")) headers.set("content-type", blob.type);
  const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get("range")?.trim() ?? "");
  if (!range || (range[1] === "" && range[2] === "")) {
    headers.set("content-length", String(blob.size));
    return new Response(blob, { status: 200, headers });
  }
  const size = blob.size;
  let start: number;
  let end: number;
  if (range[1] === "") {
    start = Math.max(0, size - Number(range[2]));
    end = size - 1;
  } else {
    start = Number(range[1]);
    end = range[2] === "" ? size - 1 : Math.min(Number(range[2]), size - 1);
  }
  if (start >= size || start > end)
    return new Response(null, { status: 416, headers: { "content-range": `bytes */${size}` } });
  headers.set("content-range", `bytes ${start}-${end}/${size}`);
  headers.set("content-length", String(end - start + 1));
  return new Response(blob.slice(start, end + 1), { status: 206, headers });
}

/** A request from the channel, as the local server would have received it. */
export function asLocal(request: Request, port: number): Request {
  const u = new URL(request.url);
  const headers = new Headers(request.headers);
  headers.set("host", `127.0.0.1:${port}`);
  /* the Worker already checked the browser's Origin against its own host */
  headers.delete("origin");
  /* it came through the hosted studio: the admin panel reads who sent it (x-ov-user, from the hub) */
  headers.set("x-ov-via", "cloud");
  return new Request(`http://127.0.0.1:${port}${u.pathname}${u.search}`, {
    /* HEAD goes in as GET, as studio.ts does; the channel sends no body back for a HEAD */
    method: request.method === "HEAD" ? "GET" : request.method,
    headers,
    body: request.body,
    signal: request.signal,
    // @ts-expect-error Bun needs it for a streaming request body
    duplex: "half",
  });
}

/** Connects and stays connected (backoff 1 s doubling to 60 s, with jitter). */
export function startRunner(o: RunnerOptions) {
  const log = o.log ?? ((line: string) => console.log(line));
  const target = `${o.url.replace(/^http/, "ws")}/runner/connect`;
  let delay = 1000;
  let stopped = false;
  /* another studio took the hosted one over: this one never knocks it off by itself. It looks, every
     replacedCheckMs, whether the place is free again (a look the hub refuses while the other one is there), and the
     user's "Reconectar agora" takes it back at once. Before, it stopped for good, and a computer the other one left
     stayed off the hosted page until a restart (2026-11-14). */
  let replaced = false;
  const replacedCheckMs = o.replacedCheckMs ?? REPLACED_CHECK_MS;
  let warned = false;
  let lastWarn = 0;
  let socket: WebSocket | null = null;
  let timer: ReturnType<typeof setTimeout> | null = null;
  /* the credential the hub refused or revoked: never knocked with again, a new login replaces it */
  let revoked = "";
  let hinted = false;
  const keyCheckMs = o.keyCheckMs ?? KEY_CHECK_MS;
  let signingIn = false;
  /* the hub has this Mac right now */
  let connected = false;
  const callMs = o.callMs ?? CALL_MS;
  /* Each try has a number, and only the latest one acts: a try the watchdog or "Reconectar agora" overtook (its login
     answered late) must not open a second socket, which the hub would take as this runner being replaced. */
  let attempt = 0;
  let lastTry = Date.now();

  const serve = async (request: Request) => withRange(request, await o.handle(asLocal(request, o.port)));

  /** `ask`: the user asked to reconnect, so with no login the approval page opens; the runner's own looks never open it */
  const connect = async (ask = false) => {
    const mine = ++attempt;
    lastTry = Date.now();
    if (timer) clearTimeout(timer);
    timer = null;
    /* an unreachable studio while refreshing says nothing about the login: try again later; one with no answer at all
       is the same */
    const token = await within(
      Promise.resolve()
        .then(() => o.token())
        .catch(() => ""),
      callMs,
      "",
    );
    if (stopped || mine !== attempt) return;
    if (!token || token === revoked) {
      if (!hinted)
        log(
          'aviso: esta máquina não está conectada ao studio hospedado; ela conecta assim que você entrar (omni login, ou "Reconectar agora" na página)',
        );
      hinted = true;
      if (ask) void signIn();
      timer = setTimeout(() => void connect(), keyCheckMs);
      return;
    }
    hinted = false;
    const ws = new WebSocket(target, {
      headers: {
        authorization: `Bearer ${token}`,
        "x-ov-protocol": String(PROTOCOL),
        /* the hub says which Mac it refused, on the hosted page */
        "x-ov-runner-host": encodeURIComponent(hostname().replace(/\.local$/, "")),
        /* replaced: only a look, never a takeover */
        ...(replaced ? { [YIELD_HEADER]: "1" } : {}),
      },
    } as unknown as string[]);
    ws.binaryType = "arraybuffer";
    socket = ws;
    const handshake = setTimeout(() => {
      if (ws.readyState === WebSocket.CONNECTING) ws.close();
    }, o.handshakeMs ?? HANDSHAKE_MS);
    let peer: Peer | null = null;
    let lastPong = Date.now();
    /* this socket is a replaced runner's look (YIELD_HEADER), not yet confirmed by the hub */
    let looking = replaced;
    let ping: ReturnType<typeof setInterval> | null = null;

    ws.onopen = () => {
      clearTimeout(handshake);
      delay = 1000;
      warned = false;
      peer = new Peer({
        send: (f: Uint8Array) => ws.send(f as Uint8Array<ArrayBuffer>),
        onRequest: serve,
        /* what the uplink still holds: media waits on it, so Omni's lines never queue behind a video */
        backlog: () => ws.bufferedAmount,
      });
      connected = true;
      /* a look the hub turns away still opens before it closes: it counts only once the hub answers a ping */
      if (looking) ws.send("ping");
      else log(`cloud: studio hospedado conectado (${o.url})`);
      /* "ping" is answered by the hub's auto-response without waking it; no pong for a while = dead */
      ping = setInterval(() => {
        if (Date.now() - lastPong > DEAD_MS) return ws.close(4001, "sem resposta da cloud");
        ws.send("ping");
      }, PING_MS);
    };
    ws.onmessage = e => {
      if (typeof e.data === "string") {
        lastPong = Date.now();
        if (looking) {
          looking = false;
          replaced = false;
          log("cloud: o outro studio saiu; este voltou a atender o studio hospedado");
          log(`cloud: studio hospedado conectado (${o.url})`);
        }
        return;
      }
      peer?.receive(e.data as ArrayBuffer);
    };
    ws.onclose = e => {
      clearTimeout(handshake);
      if (ping) clearInterval(ping);
      connected = false;
      const was = !!peer;
      peer?.close("o studio hospedado desconectou");
      peer = null;
      /* a socket a newer try already replaced: that try sets the next step */
      if (stopped || mine !== attempt) return;
      /* another studio took the hosted one over: retrying would only knock it off in turn */
      if (e.code === REPLACED) {
        if (!replaced) log("aviso: outro studio assumiu o studio hospedado; este espera a vaga ficar livre");
        replaced = true;
        timer = setTimeout(() => void connect(), replacedCheckMs);
        return;
      }
      /* the key or the login was disconnected at /runner: wait for a new login instead of knocking with the old one */
      if (e.code === REVOKED) {
        revoked = token;
        log("aviso: esta máquina foi desconectada do studio hospedado");
        hinted = true;
        /* the user's own decision: it waits for a new login, and opens no page */
        timer = setTimeout(() => void connect(), keyCheckMs);
        return;
      }
      /* the hub and this Mac speak different protocols: say which side is old, and look again in a minute
         (the studio may be redeployed, or this Mac updated, without a restart) */
      if (e.code === UPGRADE) {
        if (!warned)
          log(`aviso: esta máquina e o studio hospedado não se entendem (${e.reason}); tento de novo em 1 min`);
        warned = true;
        void Promise.resolve(o.onOutdated?.()).catch(() => {});
        timer = setTimeout(() => void connect(), o.protocolRetryMs ?? 60_000);
        return;
      }
      if (was || !warned || Date.now() - lastWarn > DOWN_REMINDER_MS) {
        log(`cloud: sem conexão com o studio hospedado (${e.code}${e.reason ? ` ${e.reason}` : ""}); tentando de novo`);
        warned = true;
        lastWarn = Date.now();
      }
      const retry = () => {
        timer = setTimeout(() => void connect(), delay * (0.75 + Math.random() / 2));
        delay = Math.min(delay * 2, 60_000);
      };
      /* never opened: the cloud may have refused the key itself (not an unreachable cloud) */
      if (!was && o.checkKey) void refusedKey(token, mine).then(handled => handled || retry());
      else retry();
    };
    ws.onerror = () => {
      /* onclose follows */
    };
  };
  /* The user asked and there is no usable login: opens the approval page on this computer and waits for the user to
     approve, then connects with the login it stored. Never twice at the same time; a page nobody answered, or a "no",
     is not asked again until the user asks again. */
  const signIn = async () => {
    if (!o.login || stopped || signingIn) return;
    signingIn = true;
    log("aviso: abri a página de aprovação no navegador desta máquina: aprove para reconectar");
    try {
      await o.login();
      log("cloud: login refeito");
      delay = 1000;
      hinted = false;
      revoked = "";
      if (!stopped) {
        if (timer) clearTimeout(timer);
        void connect();
      }
    } catch (e) {
      log(`aviso: o login não terminou (${(e as Error).message})`);
    } finally {
      signingIn = false;
    }
  };
  /* A socket that never opened: the cloud may have refused the Phase 1 key itself (not an unreachable cloud). A refused
     key is set aside, and the computer waits for a login like one that has none. True when it took over the retry. */
  const refusedKey = async (token: string, mine: number): Promise<boolean> => {
    if (stopped) return true;
    const k = await within(
      o.checkKey!(token).catch(() => ({ valid: null })),
      callMs,
      { valid: null } as { valid: boolean | null },
    );
    /* stopped, or a newer try took over while the check was out */
    if (stopped || mine !== attempt) return true;
    if (k.valid !== false) return false;
    revoked = token;
    log(
      'aviso: o studio hospedado recusou a chave desta máquina; ela conecta assim que você entrar (omni login, ou "Reconectar agora" na página)',
    );
    hinted = true;
    timer = setTimeout(() => void connect(), keyCheckMs);
    return true;
  };

  /* The loop's guard: whatever left it waiting on nothing (a call with no answer, a timer lost), a computer that is off
     the hosted studio with no socket opening and no try in a while starts trying again by itself. */
  const stallMs = o.stallMs ?? STALL_MS;
  const watchdog = setInterval(() => {
    if (stopped || replaced || connected || signingIn) return;
    if (socket && socket.readyState <= WebSocket.OPEN) return;
    if (Date.now() - lastTry < stallMs) return;
    log("aviso: a reconexão com o studio hospedado tinha parado; tentando de novo");
    delay = 1000;
    void connect();
  }, o.watchdogMs ?? WATCHDOG_MS);
  (watchdog as { unref?: () => void }).unref?.();

  void connect();
  return {
    /** The user asked to reconnect now (the hosted page's button): looks again at once, and a page that was held back
     *  by a wait, a burst nobody answered or a "Desconectar" opens now. What came of it shows on the hosted page,
     *  which keeps asking the hub; this only says whether an approval page is open. */
    async reconnectNow(quiet = false): Promise<ReconnectResult> {
      if (stopped) return { connected: false, asking: null };
      /* the user (or the page, on its own) asked after another studio took over: this one takes the hosted studio back */
      if (replaced) {
        replaced = false;
        log("cloud: reassumindo o studio hospedado a pedido");
      }
      /* a socket already open or opening: a second one would make the hub treat the first as replaced, and this
         runner stops itself when that happens */
      if (socket && socket.readyState <= WebSocket.OPEN)
        return { connected: connected || socket.readyState === WebSocket.OPEN, asking: null };
      delay = 1000;
      if (timer) clearTimeout(timer);
      await connect(!quiet);
      return { connected: false, asking: signingIn ? "login" : null };
    },
    stop() {
      stopped = true;
      clearInterval(watchdog);
      if (timer) clearTimeout(timer);
      socket?.close(1000, "runner parou");
    },
  };
}
