/* What this computer says to the user's cloud about each video's folder, so the list can be shown when the computer is
   off (cloud/studio/src/cloud-video.mjs, "facts"). The fact is the studio's own summary of the video, as the list shows
   it, with the folder's path taken out (the cloud has no use for where it is on this disk).

   It says everything once at the start, then a video again whenever the studio notices it changed, and only when the
   summary is not what was last said. A failure is told once and tried again at the next change and at the next full
   round; nothing here ever blocks the studio. */

import { createHash } from "node:crypto";

export type Summary = { slug: string; dir?: string } & Record<string, unknown>;

export type FactsOptions = {
  /** the hosted studio's address */
  url: string;
  /** the Omni login's token; "" when there is none for the moment */
  token: () => string | Promise<string>;
  all: () => Promise<Summary[]>;
  one: (slug: string) => Promise<Summary | null>;
  log?: (line: string) => void;
  fetchFn?: typeof fetch;
  /** how long a burst of changes of one video waits before it is said (ms) */
  debounceMs?: number;
  /** the full round: at the start after `startMs`, then every `roundMs` */
  startMs?: number;
  roundMs?: number;
};

export function startFacts(o: FactsOptions) {
  const log = o.log ?? ((line: string) => console.log(line));
  const send = o.fetchFn ?? fetch;
  const sent = new Map<string, string>();
  const timers = new Map<string, ReturnType<typeof setTimeout>>();
  let told = false;
  let stopped = false;
  let chain: Promise<void> = Promise.resolve();

  const tell = (line: string) => {
    if (told) return;
    told = true;
    log(line);
  };

  async function say(summary: Summary): Promise<boolean> {
    const facts = { ...summary, dir: "" };
    const body = JSON.stringify({ facts });
    const hash = createHash("sha1").update(body).digest("hex");
    if (sent.get(summary.slug) === hash) return true;
    const token = await o.token();
    if (!token) return false;
    try {
      const r = await send(`${o.url.replace(/\/+$/, "")}/api/cloud/videos/${encodeURIComponent(summary.slug)}/facts`, {
        method: "PUT",
        headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
        body,
        signal: AbortSignal.timeout(20_000),
      });
      if (!r.ok) {
        tell(`aviso: a nuvem não aceitou o resumo dos vídeos (${r.status}); tento de novo na próxima mudança`);
        return false;
      }
      sent.set(summary.slug, hash);
      told = false;
      return true;
    } catch (e) {
      tell(`aviso: não consegui falar com a nuvem sobre os vídeos (${(e as Error).message}); tento de novo depois`);
      return false;
    }
  }

  /* one at a time: a round and a change never write the same video together */
  const later = <T>(work: () => Promise<T>) => {
    const next = chain.then(work, work);
    chain = next.then(
      () => {},
      () => {},
    );
    return next;
  };

  async function round() {
    if (stopped) return;
    try {
      for (const s of await o.all()) {
        if (stopped) return;
        await say(s);
      }
    } catch (e) {
      tell(`aviso: não consegui ler a lista de vídeos para a nuvem (${(e as Error).message})`);
    }
  }

  const start = setTimeout(() => void later(round), o.startMs ?? 2000);
  const every = setInterval(() => void later(round), o.roundMs ?? 10 * 60_000);
  start.unref?.();
  every.unref?.();

  return {
    /** a video changed on disk: say it again soon */
    changed(slug: string) {
      if (stopped) return;
      clearTimeout(timers.get(slug));
      const t = setTimeout(() => {
        timers.delete(slug);
        void later(async () => {
          try {
            const s = await o.one(slug);
            if (s && !stopped) await say(s);
          } catch (e) {
            tell(`aviso: não consegui ler o vídeo ${slug} para a nuvem (${(e as Error).message})`);
          }
        });
      }, o.debounceMs ?? 1500);
      t.unref?.();
      timers.set(slug, t);
    },
    /** everything now, and wait for it (tests) */
    flush: () => later(round),
    stop() {
      stopped = true;
      clearTimeout(start);
      clearInterval(every);
      for (const t of timers.values()) clearTimeout(t);
      timers.clear();
    },
  };
}
