import assert from "node:assert/strict";
import test from "node:test";
import { ensureSegmentAudio } from "../../lib/client/tts/audio-client.ts";

test("reuses synchronized audio without synthesizing", async () => {
  let synthesized = 0;
  const result = await ensureSegmentAudio({
    segmentId: "s1", voice: "voice", rate: 1,
    describe: async () => ({ segment: { id: "s1", text: "Hi", textVersion: 2 }, voice: "voice", audio: { url: "/cached.mp3" } }),
    synthesize: async () => { synthesized += 1; return new Blob(); },
    upload: async () => ({ url: "/new.mp3" }),
  });
  assert.equal(result.url, "/cached.mp3");
  assert.equal(synthesized, 0);
});

test("synthesizes and uploads only the server-described stored segment", async () => {
  const calls = [];
  const mp3 = new Blob([new Uint8Array([0x49, 0x44, 0x33])], { type: "audio/mpeg" });
  const result = await ensureSegmentAudio({
    segmentId: "s1", voice: "voice", rate: 1.1,
    describe: async () => ({ segment: { id: "s1", text: "Stored text.", textVersion: 3 }, voice: "voice", audio: null }),
    synthesize: async (input) => { calls.push(input); return mp3; },
    upload: async (input) => { calls.push(input); return { url: "/api/audio.mp3" }; },
  });
  assert.equal(result.url, "/api/audio.mp3");
  assert.equal(calls[0].text, "Stored text.");
  assert.equal(calls[1].textVersion, 3);
  assert.equal(calls[1].audio, mp3);
});
