/* Sound timeline: the effects of beats and transitions and the bed, edited from the UI. The reads and writes over the folder are tools/lib/sound-edit.mjs (the studio and the
   agent answer the page with the same functions); what stays here is what needs the studio's own sessions and uploads. Each change is planned by tools/sound.mjs itself in a
   draft outside the video dir, and the UI plays the ready WAVs over the voice: what you hear is what assemble mixes. Saving writes to scenes.json; the export only changes on
   reassembly. */

import { sleep, spawn } from "../lib/runtime";
import { existsSync } from "node:fs";
import { join, resolve, sep } from "node:path";
import { NODE, ROOT, TOOLS_DIR, channelEnvOf, channelRoot, run } from "./root";
import { kitsOf } from "../../../tools/sound.mjs";
import {
  downloadEffect as downloadLib,
  planDraft as planLib,
  saveSound as saveLib,
  soundData,
} from "../../../tools/lib/sound-edit.mjs";
import { captureRequest } from "../../../tools/lib/sound-capture.mjs";
import { receiveUpload, trackUpload } from "../../../tools/lib/uploads.mjs";
import { chatWith } from "./create";
import type { ApiResult } from "./sessions";

type Result = { ok: true; output: string } | { ok: false; error: string };
/* the drafts live in the channel: two channels may have a video with the same slug */
const draftsDir = () => join(channelRoot(), ".sound-draft");

export const getSoundData = (dir: string) => soundData(dir);
export const planDraft = (slug: string, dir: string, draft: unknown) => planLib(channelRoot(), slug, dir, draft);
/* writes the draft to scenes.json: the sound of each beat, each transition, the bed and the cuts */
export const saveSound = (dir: string, draft: unknown): Promise<Result> => saveLib(dir, draft);
/* adds an Epidemic effect to the video's list: sound.mjs download itself (only the URL captured in the player gets in) */
export const downloadEffect = (dir: string, body: unknown): Promise<Result> =>
  downloadLib(dir, body, {
    run: async command => run(command, { OMNIVIDEO_ORIGIN: "studio" }),
    node: NODE,
    tools: TOOLS_DIR,
  });

/* draft WAV: only inside .sound-draft/<slug>/ */
export function draftFile(slug: string, rest: string): string | null {
  /* a slug is a name: one that brings a slash back after the decoding (`..%2F…`) would leave the drafts' folder */
  if (!/^[\w-]+$/.test(slug)) return null;
  const base = resolve(draftsDir(), slug);
  const abs = resolve(base, rest);
  return abs.startsWith(base + sep) && abs.endsWith(".wav") && existsSync(abs) ? abs : null;
}

/* a file of a kit, for the waveform: the ref "kit/name.mp3" (the catalog's name for a kit effect) */
export function kitFile(ref: string): string | null {
  const i = ref.indexOf("/");
  const kit = i > 0 ? ref.slice(0, i) : "";
  const name = i > 0 ? ref.slice(i + 1) : "";
  /* the kits as the request's channel sees them: its own "library" (Meus sons), the account's other kits */
  const kits = kitsOf(channelRoot());
  if (!/^[a-z0-9][a-z0-9-]*$/.test(kit) || !kits.names().includes(kit) || !name.endsWith(".mp3")) return null;
  /* a library effect is a file in the user's own folder (tools/lib/sound-library.mjs); any other is the MP3 in the kit's folder */
  const abs = kits.effectFile(kit, name);
  return abs && existsSync(abs) ? abs : null;
}

/* A track the user sends from the editor (the upload): tools/lib/uploads.mjs receives it (whole, or in pieces when the file is big) and `sound.mjs import` turns it into an MP3
   in the video's sfx/, with the origin "upload". The answer's output starts with the file name, like the Epidemic download's. */
export async function uploadTrack(dir: string, request: Request): Promise<Result> {
  const done = await receiveUpload({
    root: ROOT,
    request,
    ...trackUpload({
      dir,
      node: NODE,
      tools: TOOLS_DIR,
      run: async command => run(command, { OMNIVIDEO_ORIGIN: "studio" }),
    }),
  });
  return done.ok ? { ok: true, output: String(done.output ?? "") } : done;
}

/* adds a sound from an Epidemic page (playlist, theme, search): the editor's agent session opens it in Chrome, plays the tracks, takes the lqmp3 URL from the player and
   runs sound.mjs download. The timeline reloads when the agent stops. */
export function captureFromPage(slug: string, body: unknown): ApiResult {
  const asked = captureRequest(slug, body as { url?: unknown; name?: unknown });
  return asked.ok ? chatWith("edit", slug, asked.message) : asked;
}

/* reassembles the export with the new sound: assemble.mjs waits in the queue and the stage follows it */
export async function reassemble(dir: string): Promise<Result> {
  const p = spawn([NODE, join(TOOLS_DIR, "assemble.mjs"), dir], {
    cwd: ROOT,
    stdout: "pipe",
    stderr: "pipe",
    /* the editor's lane: up to three videos export at once (job_queue.py EDITOR_SLOTS) */
    env: { ...channelEnvOf(), OMNIVIDEO_ORIGIN: "studio", OMNIVIDEO_LANE: "editor" },
  });
  const output = Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
  const early = await Promise.race([p.exited, sleep(2500).then(() => null)]);
  if (early !== null && early !== 0) {
    const [o, e] = await output;
    return { ok: false, error: (e || o).trim() || `assemble.mjs saiu com ${early}` };
  }
  return { ok: true, output: early === 0 ? (await output)[0].trim() : "remontando (acompanhe na fila)" };
}
