import { j as json } from './index-Djsj11qr.js';
import { z } from 'zod';
import { g as getLatencyRecording, u as updateLatencyRecordingAlignment, i as isWavBytes, s as saveLatencyRecording } from './latency-recordings-CqioXMQl.js';
import 'node:crypto';
import 'node:fs/promises';
import 'node:path';

const AlignmentSchema = z.object({
  alignmentOffsetMs: z.number().finite().min(-36e5).max(36e5)
});
function sourceIdFromUrl(url) {
  const raw = url.searchParams.get("source");
  if (!raw) return null;
  const trimmed = raw.trim();
  return trimmed || null;
}
function uploadFileNameFromUrl(url) {
  const raw = url.searchParams.get("filename");
  const trimmed = String(raw ?? "").trim();
  return trimmed || "recording.wav";
}
function buildAudioUrl(url, conversationId) {
  const next = new URL(
    `/traces/api/latency/${encodeURIComponent(conversationId)}/audio`,
    url.origin
  );
  const sourceId = sourceIdFromUrl(url);
  if (sourceId) next.searchParams.set("source", sourceId);
  return next.pathname + next.search;
}
function serializeRecording(url, recording) {
  if (!recording) {
    return {
      exists: false,
      audioUrl: null,
      fileName: null,
      mimeType: null,
      size: null,
      uploadedAt: null,
      alignmentOffsetMs: 0
    };
  }
  return {
    exists: true,
    audioUrl: buildAudioUrl(url, recording.conversationId),
    fileName: recording.fileName,
    mimeType: recording.mimeType,
    size: recording.size,
    uploadedAt: recording.uploadedAt,
    alignmentOffsetMs: recording.alignmentOffsetMs
  };
}
const GET = async ({ params, url }) => {
  try {
    const conversationId = params.conversationId ?? "";
    if (!conversationId) {
      return json({ error: "Conversation id is required" }, { status: 400 });
    }
    const recording = await getLatencyRecording(conversationId, sourceIdFromUrl(url));
    return json(serializeRecording(url, recording), {
      headers: { "cache-control": "no-store" }
    });
  } catch (error) {
    console.error("Failed to load latency recording metadata:", error);
    return json({ error: "Failed to load latency recording metadata" }, { status: 500 });
  }
};
const POST = async ({ params, request, url }) => {
  try {
    const conversationId = params.conversationId ?? "";
    if (!conversationId) {
      return json({ error: "Conversation id is required" }, { status: 400 });
    }
    const contentType = (request.headers.get("content-type") ?? "").trim();
    let bytes = new Uint8Array(0);
    let fileName = uploadFileNameFromUrl(url);
    let mimeType = contentType.split(";", 1)[0]?.trim() || "audio/wav";
    if (contentType.includes("multipart/form-data")) {
      const form = await request.formData();
      const file = form.get("file");
      if (!(file instanceof File)) {
        return json({ error: "No file uploaded" }, { status: 400 });
      }
      bytes = new Uint8Array(await file.arrayBuffer());
      fileName = file.name || fileName;
      mimeType = file.type || mimeType;
    } else {
      bytes = new Uint8Array(await request.arrayBuffer());
    }
    if (bytes.byteLength === 0) {
      return json({ error: "No file uploaded" }, { status: 400 });
    }
    if (!isWavBytes(bytes)) {
      return json({ error: "Only WAV recordings are supported" }, { status: 400 });
    }
    const recording = await saveLatencyRecording({
      conversationId,
      sourceId: sourceIdFromUrl(url),
      fileName,
      mimeType,
      bytes
    });
    return json(serializeRecording(url, recording), {
      headers: { "cache-control": "no-store" }
    });
  } catch (error) {
    console.error("Failed to save latency recording:", error);
    return json({ error: "Failed to save latency recording" }, { status: 500 });
  }
};
const PATCH = async ({ params, request, url }) => {
  try {
    const conversationId = params.conversationId ?? "";
    if (!conversationId) {
      return json({ error: "Conversation id is required" }, { status: 400 });
    }
    const payload = AlignmentSchema.parse(await request.json());
    const recording = await updateLatencyRecordingAlignment({
      conversationId,
      sourceId: sourceIdFromUrl(url),
      alignmentOffsetMs: payload.alignmentOffsetMs
    });
    if (!recording) {
      return json({ error: "Latency recording not found" }, { status: 404 });
    }
    return json(serializeRecording(url, recording), {
      headers: { "cache-control": "no-store" }
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return json({ error: "Invalid alignment offset" }, { status: 400 });
    }
    console.error("Failed to update latency recording alignment:", error);
    return json({ error: "Failed to update latency recording alignment" }, { status: 500 });
  }
};

export { GET, PATCH, POST };
//# sourceMappingURL=_server.ts-CUTB_pVv.js.map
