import { getBackendBaseURL } from "@/core/config"; export type EmbedSessionStatus = { session_id: string; registered: boolean; thread_id: string | null; finished: boolean; thread_status: string; has_active_run: boolean; latest_run_status: string | null; }; export type EmbedSessionResult = EmbedSessionStatus & { messages: Record[]; generated_text: string; generated_files: string[]; }; async function parseEmbedError(response: Response): Promise { const body = await response.json().catch(() => ({})); if (typeof body.detail === "string") { return body.detail; } return `HTTP ${response.status}`; } /** Register session_id → thread_id (iframe calls this; parent never needs thread_id). */ export async function registerEmbedSession( sessionId: string, threadId: string, ): Promise<{ session_id: string; thread_id: string }> { const base = getBackendBaseURL(); const response = await fetch(`${base}/api/public/embed/sessions`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "omit", body: JSON.stringify({ session_id: sessionId, thread_id: threadId }), }); if (!response.ok) { throw new Error(await parseEmbedError(response)); } return response.json() as Promise<{ session_id: string; thread_id: string }>; } /** Poll whether embed Q&A has finished — parent uses sessionId only. */ export async function getEmbedSessionStatus( sessionId: string, ): Promise { const base = getBackendBaseURL(); const response = await fetch( `${base}/api/public/embed/sessions/${encodeURIComponent(sessionId)}/status`, { credentials: "omit" }, ); if (!response.ok) { throw new Error(await parseEmbedError(response)); } return response.json() as Promise; } /** Fetch full messages, generated text, and artifact paths — parent uses sessionId only. */ export async function getEmbedSessionResult( sessionId: string, ): Promise { const base = getBackendBaseURL(); const response = await fetch( `${base}/api/public/embed/sessions/${encodeURIComponent(sessionId)}/result`, { credentials: "omit" }, ); if (!response.ok) { throw new Error(await parseEmbedError(response)); } return response.json() as Promise; }