/* Sound timeline: the effects of beats and transitions and the bed, edited from the
   UI. Each change is planned by tools/sound.mjs itself (volume relative to the
   voice, ducking, trim, stretch, pitch) 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 { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve, sep, basename } from "node:path";
import { ROOT, NODE, TOOLS_DIR, readJson } from "./root";
import { loadVideo, beatTime } from "../../../tools/timing.mjs";
import {
  planSound,
  applyDraft,
  applyClips,
  soundCatalog,
  sanitizeSound,
  sanitizeBed,
  sanitizeSpeed,
  finalClock,
  kitDirOf,
  kitNames,
} from "../../../tools/sound.mjs";
import { videoClips, lineClips, lineDuration } from "../../../tools/soundtrack.mjs";
import { normalizeCuts } from "../../../tools/cuts.mjs";
import { chatWith } from "./create";
import type { ApiResult } from "./sessions";

type Result = { ok: true; output: string } | { ok: false; error: string };
const DRAFT_DIR = join(ROOT, ".sound-draft");

/* a sound from scenes.json: its kit's effect is shown by the ref "kit/name.mp3", as the catalog names it */
const normalizeSound = (s: any) => {
  const o = typeof s === "string" ? { name: s } : { ...s };
  if (o.kit && typeof o.name === "string" && !o.name.includes("/")) o.name = `${o.kit}/${o.name}`;
  return o;
};
const asList = (sound: any) => (sound == null ? [] : (Array.isArray(sound) ? sound : [sound]).map(normalizeSound));

/* the export's base MP4 (without the speed), for the timeline picture, and the cuts it already has */
function baseExport(
  dir: string,
): { rel: string; cuts: { from: number; to: number }[]; scene_clips: Record<string, unknown> } | null {
  const m = readJson<any>(join(dir, "export", "assembly.json"));
  const rel = m?.base_mp4 ?? m?.mp4;
  return rel && existsSync(join(dir, rel)) ? { rel, cuts: m.cuts ?? [], scene_clips: m.scene_clips ?? {} } : null;
}

/* the export at the chosen speed (assembly.json `mp4` when it isn't the base): once it matches the
   edit, the editor plays it instead of the base, so what plays there is what goes out */
function spedExport(dir: string): { path: string; mtime: number; speed: number } | null {
  const m = readJson<any>(join(dir, "export", "assembly.json"));
  const speed = Number(m?.speed);
  if (!m?.base_mp4 || !m.mp4 || m.mp4 === m.base_mp4 || !(speed > 1) || !existsSync(join(dir, m.mp4))) return null;
  return { path: m.mp4, mtime: Math.round(statSync(join(dir, m.mp4)).mtimeMs), speed };
}

export function getSoundData(dir: string) {
  const video = loadVideo(dir);
  /* each place's instant is in voice time (without the scene clips): the UI maps it onto the animation piece */
  const places: any[] = [];
  video.scenes.forEach((c: any, i: number) => {
    if (i > 0)
      places.push({
        type: "transition",
        scene: c.id,
        element: "transition",
        instant: +c.start.toFixed(3),
        sounds: asList(typeof c.transition === "object" ? c.transition?.sound : null),
      });
    for (const b of c.beats ?? []) {
      let instant: number | null = null,
        error: string | null = null;
      try {
        instant = +(c.start + beatTime(c, b)).toFixed(3);
      } catch (e: any) {
        error = e.message;
      }
      places.push({ type: "beat", scene: c.id, element: b.element, instant, error, sounds: asList(b.sound) });
    }
  });
  const exp = baseExport(dir);
  return {
    total: video.total_duration,
    provisional: video.provisional,
    format: video.format,
    scenes: video.scenes.map((c: any) => {
      const mp4 = c.mp4 ?? `motion/${c.id}.mp4`;
      return {
        id: c.id,
        title: c.title ?? null,
        start: c.start,
        duration: c.duration,
        clips: videoClips(c),
        mp4: existsSync(join(dir, mp4)) ? { path: mp4, mtime: Math.round(statSync(join(dir, mp4)).mtimeMs) } : null,
      };
    }),
    lines: video.scenes.flatMap((c: any) =>
      (c.lines ?? []).map((l: any) => ({
        id: l.id,
        scene: c.id,
        start: +(c.start + l.start).toFixed(3),
        end: +(c.start + l.end).toFixed(3),
        dur: lineDuration(l),
        clips: lineClips(l),
        wav: l.wav && existsSync(join(dir, l.wav)) ? l.wav : null,
        text: l.text,
      })),
    ),
    places,
    bed: video.bed ? normalizeSound(video.bed) : null,
    /* editor area cuts, in scenes.json time (tools/cuts.mjs) */
    cuts: normalizeCuts(video.cuts, video.total_duration, video.format.fps),
    /* the export speed (1 to 1.5); a video that never chose one in the editor keeps the one the old
       export panel left in assembly.json */
    speed: sanitizeSpeed(video.speed ?? readJson<any>(join(dir, "export", "assembly.json"))?.speed),
    catalog: soundCatalog(dir),
    export: exp
      ? {
          path: exp.rel,
          mtime: Math.round(statSync(join(dir, exp.rel)).mtimeMs),
          cuts: exp.cuts,
          scene_clips: exp.scene_clips,
        }
      : null,
    speed_export: spedExport(dir),
    /* scenes.json changed after the export (the timeline save, or another stage): needs reassembly */
    export_outdated: !exp || statSync(join(dir, "scenes.json")).mtimeMs > statSync(join(dir, exp.rel)).mtimeMs,
  };
}

/* one draft per request, in a new dir; those before the previous one are removed (the UI
   may still be downloading the previous one's WAVs) */
let counter = 0;
function draftDir(slug: string) {
  const base = join(DRAFT_DIR, slug);
  mkdirSync(base, { recursive: true });
  const n = `${Date.now()}-${++counter}`;
  const old = readdirSync(base).sort();
  for (const v of old.slice(0, Math.max(0, old.length - 1))) rmSync(join(base, v), { recursive: true, force: true });
  return { dir: join(base, n), rel: n };
}

export function planDraft(slug: string, dir: string, draft: any) {
  try {
    const video = applyDraft(dir, loadVideo(dir), draft);
    const { dir: outDir, rel } = draftDir(slug);
    /* the editor plays at 100%: the bed is made for the draft's cuts, not its speed */
    const r = planSound(dir, video, { outDir, clock: finalClock(video, 1) });
    const url = (file: string) =>
      `/sound-draft/${encodeURIComponent(slug)}/${rel}/${encodeURIComponent(basename(file))}`;
    const withUrl = ({ file, ...x }: any) => ({ ...x, url: url(file) });
    return {
      ok: true as const,
      items: r.items.map(withUrl),
      bed: r.bed ? withUrl(r.bed) : null,
      warnings: r.warnings,
      voice: r.voice,
      ducking: r.ducking,
    };
  } catch (e: any) {
    return { ok: false as const, error: e.message };
  }
}

/* draft WAV: only inside .sound-draft/<slug>/ */
export function draftFile(slug: string, rest: string): string | null {
  const base = resolve(DRAFT_DIR, 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) : "";
  if (!/^[a-z0-9][a-z0-9-]*$/.test(kit) || !kitNames().includes(kit)) return null;
  const dir = kitDirOf(kit);
  const abs = resolve(dir, name);
  return abs.startsWith(resolve(dir) + sep) && abs.endsWith(".mp3") && existsSync(abs) ? abs : null;
}

/* writes the draft to scenes.json: the sound of each beat, each transition, the bed and the cuts */
export function saveSound(dir: string, draft: any): Result {
  const file = join(dir, "scenes.json");
  const raw = readJson<any>(file);
  if (!raw) return { ok: false, error: "scenes.json não existe" };
  const video = loadVideo(dir);
  const total = video.total_duration;
  let changed = 0;
  try {
    for (const l of draft?.places ?? []) {
      const i = raw.scenes.findIndex((c: any) => c.id === l.scene);
      if (i < 0) throw new Error(`cena ${l.scene} não existe`);
      const scene = raw.scenes[i];
      const sounds = (l.sounds ?? []).map((s: any) => sanitizeSound(dir, s));
      const sound = sounds.length === 0 ? null : sounds.length === 1 ? sounds[0] : sounds;
      if (l.type === "transition") {
        if (i === 0) throw new Error("a primeira cena não tem passagem");
        const p = scene.transition && typeof scene.transition === "object" ? { ...scene.transition } : {};
        if (sound) p.sound = sound;
        else delete p.sound;
        if (Object.keys(p).length) scene.transition = p;
        else delete scene.transition;
      } else {
        const beat = (scene.beats ?? []).find((b: any) => b.element === l.element);
        if (!beat) throw new Error(`${l.scene}: beat ${l.element} não existe`);
        if (sound) beat.sound = sound;
        else delete beat.sound;
      }
      changed++;
    }
    /* `bed` and `cuts` right before `scenes`, like the rest of the contract; empty is dropped */
    let next = raw;
    const beforeScenes = (field: string, value: any) => {
      const r: any = {};
      for (const [k, v] of Object.entries(next)) {
        if (k === field) continue;
        if (k === "scenes" && value) r[field] = value;
        r[k] = v;
      }
      if (value && !(field in r)) r[field] = value;
      next = r;
    };
    /* razor and drag clips (animation and voice), validated against the loaded durations; the default one is dropped */
    const ref = structuredClone(video);
    applyClips(ref, draft);
    const match = (target: any, from: any) => {
      delete target.video_em;
      for (const k of ["clips", "video_offset"]) {
        if (from && k in from) target[k] = from[k];
        else delete target[k];
      }
    };
    for (const c of raw.scenes) {
      const rc = ref.scenes.find((x: any) => x.id === c.id);
      if (draft?.scene_clips && c.id in draft.scene_clips) match(c, rc);
      for (const l of c.lines ?? []) {
        if (draft?.line_clips && l.id in draft.line_clips) {
          const rl = rc?.lines?.find((x: any) => x.id === l.id);
          if (rl && "clips" in rl) l.clips = rl.clips;
          else delete l.clips;
        }
      }
    }
    if (draft && "bed" in draft) beforeScenes("bed", sanitizeBed(dir, draft.bed, total));
    if (draft && "cuts" in draft) {
      const c = normalizeCuts(draft.cuts, total, video.format.fps);
      beforeScenes("cuts", c.length ? c : null);
    }
    if (draft && "speed" in draft) beforeScenes("speed", sanitizeSpeed(draft.speed));
    const tmp = `${file}.${process.pid}.tmp`;
    writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
    renameSync(tmp, file);
  } catch (e: any) {
    return { ok: false, error: e.message };
  }
  return {
    ok: true,
    output: `som salvo no scenes.json (${changed} lugar(es)${draft && "bed" in draft ? " e a cama" : ""}${draft?.cuts?.length ? `, ${draft.cuts.length} corte(s)` : ""}${draft && "speed" in draft ? `, velocidade ${Math.round(sanitizeSpeed(draft.speed) * 100)}%` : ""})`,
  };
}

/* adds an Epidemic effect to the video's list: sound.mjs download itself (only the URL
   captured in the player gets in), which writes the MP3 to sfx/ and the origin to sfx/sources.json */
export async function downloadEffect(dir: string, body: any): Promise<Result> {
  const url = String(body?.url ?? "").trim();
  const name = String(body?.name ?? "").trim();
  if (!url) return { ok: false, error: "cole a URL da Epidemic (audiocdn.epidemicsound.com/lqmp3/<id>.mp3)" };
  const p = Bun.spawn([NODE, join(TOOLS_DIR, "sound.mjs"), "download", dir, url, ...(name ? [name] : [])], {
    cwd: ROOT,
    stdout: "pipe",
    stderr: "pipe",
    env: { ...process.env, OMNIVIDEO_ORIGIN: "studio" },
  });
  const [o, e, exit] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
  if (exit !== 0) return { ok: false, error: (e || o).trim().replace(/^erro:\s*/, "") || `sound.mjs saiu com ${exit}` };
  return { ok: true, output: o.trim() };
}

/* A track the user sends from the editor (the upload): the raw body goes to a temp file 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. */
const AUDIO_FILE = /\.(mp3|wav|m4a|aac|flac|ogg|oga|opus|aif|aiff|wma|mp4)$/i;
const MAX_UPLOAD = 200 * 1024 * 1024;
export async function uploadTrack(
  dir: string,
  rawName: string,
  body: ReadableStream | null,
  size: number,
): Promise<Result> {
  let original = rawName;
  try {
    original = decodeURIComponent(rawName);
  } catch {
    /* keeps the raw name */
  }
  const file = basename(original);
  if (!AUDIO_FILE.test(file))
    return { ok: false, error: "o arquivo precisa ser um áudio (mp3, wav, m4a, aac, flac, ogg, aiff)" };
  if (!body || size === 0) return { ok: false, error: "arquivo vazio" };
  if (size > MAX_UPLOAD) return { ok: false, error: "o arquivo passa de 200 MB" };
  const tmp = join(tmpdir(), `omni-upload-${Date.now()}${file.slice(file.lastIndexOf("."))}`);
  try {
    await Bun.write(tmp, new Response(body));
    /* the file's own name (not the temp file's) is the track's name and title */
    const title = file.replace(/\.[^.]+$/, "");
    const p = Bun.spawn([NODE, join(TOOLS_DIR, "sound.mjs"), "import", dir, tmp, title, "--title", title], {
      cwd: ROOT,
      stdout: "pipe",
      stderr: "pipe",
      env: { ...process.env, OMNIVIDEO_ORIGIN: "studio" },
    });
    const [o, e, exit] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
    if (exit !== 0)
      return { ok: false, error: (e || o).trim().replace(/^erro:\s*/, "") || `sound.mjs saiu com ${exit}` };
    return { ok: true, output: o.trim() };
  } catch (err: any) {
    return { ok: false, error: `não deu para guardar o upload: ${err?.message ?? err}` };
  } finally {
    rmSync(tmp, { force: true });
  }
}

/* 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: any): ApiResult {
  let page: URL;
  try {
    page = new URL(String(body?.url ?? "").trim());
  } catch {
    return { ok: false, error: "cole o link de uma página da Epidemic (https://www.epidemicsound.com/music/…)" };
  }
  if (page.protocol !== "https:" || !/^(www\.)?epidemicsound\.com$/.test(page.hostname))
    return { ok: false, error: "o link precisa ser de epidemicsound.com" };
  const name = String(body?.name ?? "").trim();
  const search = page.pathname.split("/").filter(Boolean).pop() ?? "";
  const message = [
    `Adicione ao vídeo uma faixa desta página da Epidemic: ${page.href}`,
    "Só isto: não mexa na timeline, no scenes.json nem na montagem, e não baixe de outra fonte.",
    "1. Carregue as ferramentas do Claude in Chrome (ToolSearch) e abra a página numa aba nova; tire um screenshot, porque a lista só monta com a aba pintada.",
    "2. Rode no javascript_tool o código de `node tools/sound.mjs capture 8`. Ele dá play nas faixas e devolve [{ title, duration, url }], com a URL https://audiocdn.epidemicsound.com/lqmp3/<id>.mp3 lida do `src` do player (a música usa a mesma URL dos efeitos; o blob: da página é outro recurso, ignore). Lista vazia: espere e tente de novo uma vez.",
    `3. Escolha a primeira faixa cuja URL ainda não esteja em videos/${slug}/sfx/sources.json e baixe: \`node tools/sound.mjs download videos/${slug} <url> ${name || "<nome-curto-da-faixa>"} --search "${search}"\`. Música tem mais de 30 s; se a faixa for um efeito curto, diga isso.`,
    "4. Feche a aba que você abriu e responda em uma linha: arquivo, título e duração.",
    "Chrome fora do ar ou Epidemic sem responder: pare e diga o que abrir.",
  ].join("\n");
  return chatWith("edit", slug, message);
}

/* 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 = Bun.spawn([NODE, join(TOOLS_DIR, "assemble.mjs"), dir], {
    cwd: ROOT,
    stdout: "pipe",
    stderr: "pipe",
    env: { ...process.env, OMNIVIDEO_ORIGIN: "studio" },
  });
  const output = Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
  const early = await Promise.race([p.exited, Bun.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)" };
}
