import { clearToken, getToken, withRefresh, type RefreshFn } from "../lib/auth"; import type { Feedback, ScriptVariation, FeedbackPayload, AgentRunLog, BankRow, CandidateUpdatePayload, CaptionCue, ChatTurn, Concept, FinalOutput, GenerationAccepted, GenerationRender, GenerationRequest, GenerationStats, GenerationSummary, LoginPayload, Niche, RenderClip, RunStatusResponse, Avatar, ProductExtract, SavedProduct, AvatarFilters, GenerationCost, ServerJob, StudioClip, StudioClipRequest, TextOverlay, TokenResponse, RenderMode, VideoPlan, VisualChatResult, Voice, } from "./types"; const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8000/api/v1"; const LOGIN_PATH = "/auth/login"; export class ApiError extends Error { status: number; constructor(status: number, message: string) { super(message); this.name = "ApiError"; this.status = status; } } function authHeaders(extra?: Record): Record { const token = getToken(); return { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...extra, }; } const REFRESH_PATH = "/auth/refresh"; /** POST /auth/refresh (AUTH_MODE=supabase only). Plain fetch: never itself retried. */ const refreshTokens: RefreshFn = async (refresh_token) => { const res = await fetch(`${BASE_URL}${REFRESH_PATH}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refresh_token }), }); if (!res.ok) throw new ApiError(res.status, res.statusText); return (await res.json()) as TokenResponse; }; /** fetch with the current bearer token; on a 401, refreshes once (if a refresh token * exists) and retries once. The login call itself is never retried. */ function authFetch(url: string, init: RequestInit = {}): Promise { const send = () => { const token = getToken(); const headers = { ...(init.headers as Record | undefined) }; if (token) headers.Authorization = `Bearer ${token}`; return fetch(url, { ...init, headers }); }; return url.endsWith(LOGIN_PATH) ? send() : withRefresh(send, refreshTokens); } /** Shared 401 handling: any expired/invalid session (other than a login attempt * itself) clears the stored token and bounces the user back to the login page. */ async function throwForResponse(path: string, res: Response): Promise { let detail = res.statusText; try { const body = await res.json(); if (typeof body.detail === "string") { detail = body.detail; } else if (Array.isArray(body.detail)) { // FastAPI request-validation errors come as a list of {loc, msg}. detail = body.detail.map((e: { msg?: string }) => e.msg).filter(Boolean).join("; ") || detail; } else if (body.detail) { detail = JSON.stringify(body.detail); } } catch { // response wasn't JSON; fall back to statusText } if (res.status === 401 && path !== LOGIN_PATH) { clearToken(); window.location.assign("/login"); } throw new ApiError(res.status, detail); } async function request(path: string, init?: RequestInit): Promise { const res = await authFetch(`${BASE_URL}${path}`, { ...init, headers: authHeaders({ "Content-Type": "application/json", ...(init?.headers as Record | undefined), }), }); if (!res.ok) await throwForResponse(path, res); if (res.status === 204) return undefined as T; return (await res.json()) as T; } async function requestBlob(path: string, init?: RequestInit): Promise { const res = await authFetch(`${BASE_URL}${path}`, { ...init, headers: authHeaders({ "Content-Type": "application/json", ...(init?.headers as Record | undefined), }), }); if (!res.ok) await throwForResponse(path, res); return res.blob(); } export const api = { login: (payload: LoginPayload) => request(LOGIN_PATH, { method: "POST", body: JSON.stringify(payload) }), listNiches: () => request("/niches"), /** The last brief used for a niche, for prefilling the form. {} when none. */ lastBrief: (niche: string) => request<{ prompt?: string; target_audience?: string; platform?: string; duration_seconds?: number; broll_percent?: number | null; }>(`/generations/last-brief?niche=${encodeURIComponent(niche)}`), /** A researched starting brief for a niche: typical offer + audience. Slow (live search). */ suggestBrief: (niche: string) => request<{ prompt: string; target_audience: string }>( `/generations/suggest-brief?niche=${encodeURIComponent(niche)}`, ), /** Re-run a failed generation, reusing the evidence and trends already logged. */ retryGeneration: (assetId: string) => request<{ task_id: string; status: string }>(`/generations/${assetId}/retry`, { method: "POST", }), /** Write alternative scripts for a candidate whose script already works. */ generateScriptVariations: (assetId: string, candidateNumber: number, count = 3) => request<{ task_id: string; status: string }>( `/generations/${assetId}/candidates/${candidateNumber}/variations?count=${count}`, { method: "POST" }, ), /** Variants written so far, newest first. */ listScriptVariations: (assetId: string, candidateNumber: number) => request( `/generations/${assetId}/candidates/${candidateNumber}/variations`, ), /** Every note left on a generation, newest first. */ listFeedback: (assetId: string) => request(`/generations/${assetId}/feedback`), /** Record a verdict + optional comment on a script, visual direction, or render. */ addFeedback: (assetId: string, payload: FeedbackPayload) => request(`/generations/${assetId}/feedback`, { method: "POST", body: JSON.stringify(payload), }), /** The format playbook, for the concept picker on the request form. */ listConcepts: () => request("/concepts"), createGeneration: (payload: GenerationRequest) => request("/generations", { method: "POST", body: JSON.stringify(payload), }), listGenerations: ( params: { limit?: number; offset?: number; niche?: string; /** Inclusive YYYY-MM-DD bounds on created_at, applied in the query so they * hold across pages rather than filtering the rows already on screen. */ dateFrom?: string; dateTo?: string; } = {}, ) => { const qs = new URLSearchParams(); if (params.limit) qs.set("limit", String(params.limit)); if (params.offset) qs.set("offset", String(params.offset)); if (params.niche) qs.set("niche", params.niche); if (params.dateFrom) qs.set("date_from", params.dateFrom); if (params.dateTo) qs.set("date_to", params.dateTo); const suffix = qs.toString() ? `?${qs.toString()}` : ""; return request(`/generations${suffix}`); }, /** Counted server-side, so the dashboard tiles report the whole table rather * than however many rows happen to be loaded. */ generationStats: () => request("/generations/stats"), getGeneration: (id: string) => request(`/generations/${id}`), getGenerationCost: (id: string) => request(`/generations/${id}/cost`), getGenerationHistory: (id: string) => request(`/generations/${id}/history`), updateCandidate: (assetId: string, candidateNumber: number, payload: CandidateUpdatePayload) => request(`/generations/${assetId}/candidates/${candidateNumber}`, { method: "PATCH", body: JSON.stringify(payload), }), /** Re-derive the shot list from an edited script and re-score it. Background * (three Gemini calls) — poll getRenderStatus, or watch the jobs tray. */ revalidateCandidate: (assetId: string, candidateNumber: number, resyncVisuals = true) => request<{ task_id: string; status: string }>( `/generations/${assetId}/candidates/${candidateNumber}/revalidate?resync_visuals=${resyncVisuals}`, { method: "POST" }, ), /** Revise a failing candidate's QA issues and re-score it. Background (up to * four Gemini calls) — poll getRenderStatus, or watch the jobs tray. */ fixCandidate: (assetId: string, candidateNumber: number) => request<{ task_id: string; status: string }>( `/generations/${assetId}/candidates/${candidateNumber}/fix`, { method: "POST" }, ), /** Saved versions of a candidate, oldest first. Each is the state before one * change; the current state is on the generation itself. */ candidateVersions: (assetId: string, candidateNumber: number) => request(`/generations/${assetId}/candidates/${candidateNumber}/versions`), /** Give the visual director a note on a candidate's shot list, or ask about it. * Synchronous — an instruction is applied server-side and persisted. */ visualChat: (assetId: string, candidateNumber: number, message: string, history: ChatTurn[]) => request( `/generations/${assetId}/candidates/${candidateNumber}/visual-chat`, { method: "POST", body: JSON.stringify({ message, history }) }, ), listVoices: () => request("/tts/voices"), /** The b-roll (914 rows) or hook bank, filtered server-side by a plain * contains-match — enough to find a shot you already have in mind. */ /** Products saved from earlier briefs, most recently used first. */ listProducts: () => request("/products"), deleteProduct: (id: string) => request(`/products/${encodeURIComponent(id)}`, { method: "DELETE" }), /** Read a product page into facts the ad may use. */ extractProduct: (url: string) => request("/products/extract", { method: "POST", body: JSON.stringify({ url }), }), /** Upload one product image (raw body), reporting progress. XHR rather than * fetch because fetch can't report upload progress; an expired session is * retried once through the normal refreshing path. */ uploadProductImage: (file: File, onProgress?: (fraction: number) => void) => new Promise<{ key: string; url: string }>((resolve, reject) => { const path = "/products/images"; const xhr = new XMLHttpRequest(); xhr.open("POST", `${BASE_URL}${path}`); const token = getToken(); if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`); xhr.setRequestHeader("Content-Type", file.type); xhr.upload.onprogress = (e) => e.lengthComputable && onProgress?.(e.loaded / e.total); xhr.onerror = () => reject(new ApiError(0, "Upload failed — check your connection")); xhr.onload = async () => { try { if (xhr.status >= 200 && xhr.status < 300) return resolve(JSON.parse(xhr.responseText)); if (xhr.status !== 401) { let detail = xhr.statusText || "Upload failed"; try { const body = JSON.parse(xhr.responseText); if (typeof body.detail === "string") detail = body.detail; } catch { /* not JSON */ } return reject(new ApiError(xhr.status, detail)); } const res = await authFetch(`${BASE_URL}${path}`, { method: "POST", headers: { ...authHeaders(), "Content-Type": file.type }, body: file, }); if (!res.ok) await throwForResponse(path, res); onProgress?.(1); resolve(await res.json()); } catch (err) { reject(err); } }; xhr.send(file); }), /** The avatar library. Empty filter values are left out of the query. */ listAvatars: (filters: AvatarFilters = {}) => { const params = new URLSearchParams(); for (const [k, v] of Object.entries(filters)) if (v !== undefined && v !== "") params.set(k, String(v)); const qs = params.toString(); return request(`/avatars${qs ? `?${qs}` : ""}`); }, getAvatar: (id: string) => request(`/avatars/${encodeURIComponent(id)}`), listClipBank: (table: "broll" | "hooks_text", q = "", limit = 40) => request( `/clips/banks/${table}?q=${encodeURIComponent(q)}&limit=${limit}`, ), /** Generate a standalone clip (or a batch of variations). Background — poll * getRenderStatus, which returns `clips` for a studio batch. */ generateStudioClip: (payload: StudioClipRequest) => request<{ task_id: string; status: string }>("/clips/generate", { method: "POST", body: JSON.stringify(payload), }), /** The clip library, newest first. */ listStudioClips: (kind?: "broll" | "hook", limit = 60) => request( `/clips?limit=${limit}${kind ? `&kind=${kind}` : ""}`, ), /** Upload a reference video. Cropped to 9:16 and validated server-side, so an * unreadable or horizontal file is rejected here rather than minutes into a * paid generation. Returns the path to pass as `reference_path`. */ uploadReferenceVideo: async (file: File, endpoint = "/clips/reference") => { const res = await authFetch(`${BASE_URL}${endpoint}`, { method: "POST", headers: authHeaders(), body: file, }); if (!res.ok) await throwForResponse(endpoint, res); return (await res.json()) as { path: string; url: string; seconds: number }; }, /** Preview the candidate's voiceover. `voice: null` lets the server cast it from * the presenter description — the same choice the render will make. */ generateCandidateAudio: (assetId: string, candidateNumber: number, voice: string | null) => requestBlob(`/generations/${assetId}/candidates/${candidateNumber}/audio`, { method: "POST", body: JSON.stringify({ voice }), }), getVideoPlan: (assetId: string, candidateNumber: number) => request(`/generations/${assetId}/candidates/${candidateNumber}/video-plan`), getRenderPlan: (assetId: string, candidateNumber: number, mode?: RenderMode) => request( `/generations/${assetId}/candidates/${candidateNumber}/render-plan${mode ? `?mode=${mode}` : ""}`, ), // Rendering runs in the background (minutes per clip). This kicks it off and // returns a task_id; poll getRenderStatus until it's ready. The narration // voice is chosen by the system, not passed in. startRender: (assetId: string, candidateNumber: number, plan: VideoPlan) => request<{ task_id: string; status: string }>( `/generations/${assetId}/candidates/${candidateNumber}/render`, { method: "POST", body: JSON.stringify(plan) }, ), /** Poll a background task. A clip-studio batch additionally returns `clips` * and, for hooks, the `alt_lines` written alongside them — the job row itself * stores no result payload, so this is where they come from. */ getRenderStatus: (taskId: string) => request<{ status: "rendering" | "ready" | "failed"; video_url?: string; render_id?: string; error?: string; clips?: StudioClip[]; alt_lines?: string[]; recovered?: { reason: string; action: string; description?: string }[]; analysis?: { summary?: string; prompt?: string; has_identifiable_person?: boolean; } | null; }>(`/renders/${taskId}`), listGenerationRenders: (assetId: string) => request(`/generations/${assetId}/renders`), listAllRenders: (opts: { niche?: string; limit?: number } = {}) => { const params = new URLSearchParams(); if (opts.niche) params.set("niche", opts.niche); if (opts.limit) params.set("limit", String(opts.limit)); const qs = params.toString(); return request(`/renders${qs ? `?${qs}` : ""}`); }, getRenderClips: (renderId: string) => request(`/renders/${renderId}/clips`), startEdit: ( renderId: string, // `spoken` is the share of the line audible in this piece — set when the // editor has split one source clip, so both halves aren't captioned with the // whole sentence. Omitted means "the whole line", as the manifest has it. edits: { index: number; in: number; out: number; spoken?: string }[], opts: { captions: boolean; music?: string | null; musicVolume?: number; overlays?: TextOverlay[]; captionSource?: "script" | "ai" | "none"; captionCues?: CaptionCue[]; captionColor?: string; captionSize?: number; captionPosition?: string; captionX?: number | null; captionY?: number | null; captionFont?: string | null; captionBgColor?: string; captionBgOpacity?: number; captionAnimation?: string; captionKaraoke?: boolean; captionStyle?: string; }, ) => request<{ task_id: string; status: string }>(`/renders/${renderId}/edit`, { method: "POST", body: JSON.stringify({ edits, captions: opts.captions, music: opts.music ?? null, music_volume: opts.musicVolume ?? 0.25, overlays: opts.overlays ?? [], caption_source: opts.captionSource ?? "script", caption_cues: opts.captionCues ?? [], caption_color: opts.captionColor ?? "#FFFFFF", caption_size: opts.captionSize ?? 52, caption_position: opts.captionPosition ?? "bottom", caption_x: opts.captionX ?? null, caption_y: opts.captionY ?? null, caption_font: opts.captionFont ?? null, caption_bg_color: opts.captionBgColor ?? "#000000", caption_bg_opacity: opts.captionBgOpacity ?? 0.45, caption_animation: opts.captionAnimation ?? "pop", caption_karaoke: opts.captionKaraoke ?? null, caption_style: opts.captionStyle ?? null, }), }), /** Background work in flight, server-side — so a render started on another * device (or before this tab was opened) is still reported. */ listJobs: () => request("/jobs"), listFonts: () => request("/fonts"), regenerateClip: ( renderId: string, index: number, body: { prompt?: string; spoken?: string; voice?: string; use_reference?: boolean }, ) => request<{ task_id: string; status: string }>( `/renders/${renderId}/clips/${index}/regenerate`, { method: "POST", body: JSON.stringify(body) }, ), /** Avatar Swap page: put a library avatar into an uploaded video (a key from * uploadReferenceVideo). Background; the result's video_url comes from getRenderStatus. */ swapVideo: (body: { video_path: string; avatar_id?: string; image_key?: string; prompt?: string; match_lips?: boolean; use_avatar_voice?: boolean; captions?: "keep" | "remove" | "redo"; }) => request<{ task_id: string; status: string }>("/swaps", { method: "POST", body: JSON.stringify(body), }), /** Put a library avatar into one clip's existing footage (MiniMax Recast). * Background task like a regenerate. */ recastClip: (renderId: string, index: number, body: { avatar_id: string; prompt?: string }) => request<{ task_id: string; status: string }>( `/renders/${renderId}/clips/${index}/recast`, { method: "POST", body: JSON.stringify(body) }, ), /** Re-record one clip's voiceover from edited text, keeping its footage. Inline * (one TTS + a mux), so seconds rather than the minutes a regenerate costs. */ revoiceClip: (renderId: string, index: number, spoken: string) => request<{ index: number; duration: number; spoken: string }>( `/renders/${renderId}/clips/${index}/revoice`, { method: "POST", body: JSON.stringify({ spoken }) }, ), uploadClip: async (renderId: string, index: number, file: File) => { const path = `/renders/${renderId}/clips/${index}/upload`; const res = await authFetch(`${BASE_URL}${path}`, { method: "POST", headers: authHeaders(), body: file, }); if (!res.ok) await throwForResponse(path, res); return res.json(); }, uploadMedia: async (file: File): Promise<{ path: string; url: string }> => { const ext = (file.name.split(".").pop() || "mp3").toLowerCase(); const res = await authFetch(`${BASE_URL}/media/upload?ext=${encodeURIComponent(ext)}`, { method: "POST", headers: authHeaders(), body: file, }); if (!res.ok) await throwForResponse("/media/upload", res); return res.json(); }, recordRenderPerformance: ( renderId: string, payload: { verdict: string; ctr?: number; cpc?: number; roas?: number; spend?: number }, ) => request<{ status: string; verdict: string }>(`/renders/${renderId}/performance`, { method: "POST", body: JSON.stringify(payload), }), }; export const TERMINAL_STATUSES = new Set(["completed", "failed"]); export function isTerminal(status: string): boolean { return TERMINAL_STATUSES.has(status); } export type { FinalOutput };