/* 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.

   Locally `Bun.serve` answers Range for a Bun.file by itself; `app.fetch` doesn't, so the media paths
   get their 206 here, from a slice of the file's Blob (never read whole). */

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

/* 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 key (not paired, or disconnected at /runner): how often to look for one in .env */
const KEY_CHECK_MS = 30_000;
/* a refused key pairs again by itself at most this often (the approval page opens on this Mac) */
const PAIR_EVERY_MS = 60 * 60_000;
/* with no login (never entered, signed out, or disconnected at the studio) the approval page opens on this computer by
   itself, at most this often: it asks for a click, and someone who closed it didn't want it every hour */
const LOGIN_EVERY_MS = 6 * 60 * 60_000;
/* An approval page nobody answered (the code ran out, the tab was closed) comes back this soon, so the screen's "volta
   sozinho assim que você aprovar" stays true; after UNANSWERED_BURST of them in a row the long waits above apply again.
   Those waits also apply after a refusal on the page (that is an answer) and after a "Desconectar" (the user's own
   decision). Before this, one unanswered page meant 1 h (a key) or 6 h (a login) with nothing to approve. */
const UNANSWERED_RETRY_MS = 60_000;
const UNANSWERED_BURST = 3;

/** A "no" on the approval page, as opposed to a page that ran out (tools/lib/pairing.mjs and oauth-client.mjs word it
 *  "recusado na página"). */
export const refusedOnPage = (e: unknown) => /recusad[oa]/i.test((e as Error)?.message ?? "");

/** When an approval page may open: at once the first time, soon after one nobody answered (a few times in a row), and
 *  only after the long wait after a refusal, an approval, a "Desconectar" or a burst nobody answered. */
export function approvalGate(longMs: number, soonMs = UNANSWERED_RETRY_MS, burst = UNANSWERED_BURST) {
  let endedAt = 0;
  let wait = 0;
  let unanswered = 0;
  return {
    due: () => endedAt === 0 || Date.now() - endedAt >= wait,
    /** approved, or refused on the page: the long wait */
    answered() {
      endedAt = Date.now();
      wait = longMs;
      unanswered = 0;
    },
    /** the page ran out: soon, unless the user disconnected this machine on purpose (`patient`) or it is too many in a row */
    unanswered(patient = false) {
      endedAt = Date.now();
      unanswered += 1;
      if (patient || unanswered >= burst) {
        wait = longMs;
        unanswered = 0;
      } else wait = soonMs;
    },
  };
}

/** 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 repair would open a pairing page for a computer that
 *  is already signed in. */
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 the Phase 1 key (OMNIVIDEO_RUNNER_TOKEN, from `node tools/runner.mjs login`)
   *  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) */
  checkKey?: (token: string) => Promise<{ valid: boolean | null }>;
  /** pairs this Mac again (opens the approval page, waits, saves the new key): the key, or null. Called when
   *  the cloud refuses the key, never after a "Desconectar", which is the user's own decision */
  pair?: () => Promise<string | null>;
  /** signs this computer in again: opens the approval page in the browser and waits for the user to approve
   *  (tools/lib/oauth-client.mjs login). Called when there is no usable login, so nobody has to open a terminal or
   *  Claude Code to get back in; the user only approves */
  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 */
  keyCheckMs?: number;
  loginEveryMs?: number;
  retryUnansweredMs?: number;
  protocolRetryMs?: number;
};

/** 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;
  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;
  let warned = false;
  let socket: WebSocket | null = null;
  let timer: ReturnType<typeof setTimeout> | null = null;
  let revoked = "";
  let hinted = false;
  let pairing = false;
  const keyCheckMs = o.keyCheckMs ?? KEY_CHECK_MS;
  const pairGate = approvalGate(PAIR_EVERY_MS, o.retryUnansweredMs);
  const signInGate = approvalGate(o.loginEveryMs ?? LOGIN_EVERY_MS, o.retryUnansweredMs);
  let signingIn = false;
  /* "Desconectar" at /runner: the user's decision, so an unanswered page isn't pushed again soon */
  let disconnectedByUser = false;

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

  const connect = async () => {
    /* an unreachable studio while refreshing says nothing about the login: try again later */
    const token = await Promise.resolve(o.token()).catch(() => "");
    if (!token || token === revoked) {
      if (!hinted) log("aviso: esta máquina não está conectada ao studio hospedado");
      hinted = true;
      void signIn();
      /* a refused key, not a "Desconectar": the gate says whether a new approval page is due */
      if (token && !disconnectedByUser) void pairAgain();
      timer = setTimeout(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$/, "")),
      },
    } as unknown as string[]);
    ws.binaryType = "arraybuffer";
    socket = ws;
    let peer: Peer | null = null;
    let lastPong = Date.now();
    let ping: ReturnType<typeof setInterval> | null = null;

    ws.onopen = () => {
      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,
      });
      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();
        return;
      }
      peer?.receive(e.data as ArrayBuffer);
    };
    ws.onclose = e => {
      if (ping) clearInterval(ping);
      const was = !!peer;
      peer?.close("o studio hospedado desconectou");
      peer = null;
      if (stopped) return;
      /* another studio took the hosted one over: retrying would only knock it off in turn */
      if (e.code === REPLACED) {
        stopped = true;
        return log("aviso: outro studio assumiu o studio hospedado; este parou de atender por ele");
      }
      /* the key was deleted at /runner: wait for a new pairing instead of knocking with the old key */
      if (e.code === REVOKED) {
        revoked = token;
        disconnectedByUser = true;
        log("aviso: esta máquina foi desconectada do studio hospedado");
        hinted = true;
        /* the next look finds no login and opens the approval page (once): the user can approve or refuse it */
        timer = setTimeout(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(connect, o.protocolRetryMs ?? 60_000);
        return;
      }
      if (was || !warned) {
        log(`cloud: sem conexão com o studio hospedado (${e.code}${e.reason ? ` ${e.reason}` : ""}); tentando de novo`);
        warned = true;
      }
      const retry = () => {
        timer = setTimeout(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 && o.pair) void repair(token).then(handled => handled || retry());
      else retry();
    };
    ws.onerror = () => {
      /* onclose follows */
    };
  };
  /* No usable login: opens the approval page on this computer and waits for the user to approve, then connects with
     the login it stored. At most once in a while, and never twice at the same time. */
  const signIn = async () => {
    if (!o.login || stopped || signingIn || !signInGate.due()) return;
    signingIn = true;
    log("aviso: abri a página de aprovação no navegador desta máquina: aprove para reconectar");
    try {
      await o.login();
      signInGate.answered();
      log("cloud: login refeito");
      delay = 1000;
      hinted = false;
      revoked = "";
      disconnectedByUser = false;
      if (!stopped) {
        if (timer) clearTimeout(timer);
        void connect();
      }
    } catch (e) {
      const refused = refusedOnPage(e);
      log(
        `aviso: o login não terminou (${(e as Error).message}); ${refused ? "não pergunto de novo agora" : "abro a página de novo daqui a pouco"}`,
      );
      if (refused) signInGate.answered();
      else signInGate.unanswered(disconnectedByUser);
    } finally {
      signingIn = false;
    }
  };
  /* Asks for a new pairing when the gate allows it: the approval page opens on this Mac and the new key goes into
     .env. Called when the key is first refused and again at every look while it stays refused, so a page that ran out
     is followed by another (before, the retry the log promised never came: `connect` skips a refused key). */
  const pairAgain = async () => {
    if (stopped || pairing || !o.pair || !pairGate.due()) return;
    pairing = true;
    log(
      "aviso: o studio hospedado recusou a chave desta máquina; abri a página de aprovação no navegador: aprove para reconectar",
    );
    const key = await o.pair().catch(e => {
      const refused = refusedOnPage(e);
      log(
        `aviso: o pareamento não terminou (${(e as Error).message}); ${refused ? "não pergunto de novo agora" : "abro a página de novo daqui a pouco"}`,
      );
      if (refused) pairGate.answered();
      else pairGate.unanswered();
      return null;
    });
    pairing = false;
    if (stopped || !key) return;
    pairGate.answered();
    log("cloud: máquina pareada de novo");
    delay = 1000;
    hinted = false;
    if (timer) clearTimeout(timer);
    void connect();
  };
  /* The key was refused (the login was redone, the key went missing in the cloud…): pair again. True when it took
     over the retry; the next looks (every keyCheckMs, while the key stays refused) come back to `pairAgain`. */
  const repair = async (token: string): Promise<boolean> => {
    if (stopped || pairing) return true;
    const k = await o.checkKey!(token).catch(() => ({ valid: null }));
    if (k.valid !== false) return false;
    revoked = token;
    timer = setTimeout(connect, keyCheckMs);
    void pairAgain();
    return true;
  };

  void connect();
  return {
    stop() {
      stopped = true;
      if (timer) clearTimeout(timer);
      socket?.close(1000, "runner parou");
    },
  };
}
