/* استوديو التصميم - the studio's types and calls (app/api/v1/studio.py). Every endpoint answers 404 to anyone but the owner account. */ import { supabase } from "./supabase"; import { API_URL, ApiError } from "./api"; import type { DesignableRun } from "./types"; export interface StudioSize { key: string; platform: string; label: string; width: number; height: number; safe_top: number; safe_bottom: number; note: string; } export interface StudioType { key: string; label: string; words: [number, number]; structure: string; fields: string[]; items: [number, number]; item_words: [number, number]; per_slide: boolean; } export interface StudioPresets { sizes: StudioSize[]; custom: { min: number; max: number }; types: StudioType[]; styles: { key: string; label: string; description: string; dark: boolean }[]; palettes: { key: string; colors: string[] }[]; fonts: { key: string; label: string }[]; logo_spots: string[]; logo_sizes: string[]; max_logo_bytes: number; langs: string[]; } export type Copy = Record; export interface WordCount { total: number; min: number; max: number; per_slide: number[]; problems: string[]; over: boolean; } export interface CopyResult { copy: Copy; words: WordCount; original_words: number; shortened: boolean; notes: string[]; } export interface TraceStep { agent: string; status: "done" | "fixed" | "warn" | "skipped"; detail: string; seconds: number; } export interface StudioResult { images: string[]; copy: Copy; words: WordCount; direction: Record; tokens: Record & { fixes: string[] }; qa: { ok: boolean; issues: { check: string; agent: string; page: number; detail: string }[]; words_ok: boolean }; rounds: number; trace: TraceStep[]; cost: number; shortened: boolean; original_words: number; size: { key: string; width: number; height: number; safe_top: number; safe_bottom: number }; format: "png" | "jpg"; project?: { kind: string; label: string; title: string }; } export interface BrandKitData { colors?: string[]; font?: string; style?: string; logo_spot?: string; logo_size?: string; dark?: boolean | null; } export interface BrandKit { id: string; name: string; data: BrandKitData; logo: string | null; updated_at: string | null; } export interface DesignSpec { type: string; size: string; width?: number; height?: number; style: string; lang: string; mode: "copy" | "idea" | "text"; text?: string; copy?: Copy; colors: string[]; font: string; dark?: boolean | null; logo_spot: string; logo_size: string; kit_id?: string | null; ai_image: boolean; fmt: "png" | "jpg"; use_project_picture?: boolean; } async function headers(json = true): Promise> { const { data } = await supabase.auth.getSession(); const token = data.session?.access_token; return { ...(json ? { "Content-Type": "application/json" } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}), }; } async function call(path: string, init: RequestInit = {}, json = true): Promise { const res = await fetch(`${API_URL}${path}`, { ...init, headers: await headers(json) }); if (!res.ok) { let message = `الطلب فشل (${res.status})`; try { const body = await res.json(); if (typeof body?.detail === "string") message = body.detail; else if (Array.isArray(body?.detail)) { message = body.detail.map((d: { msg: string }) => d.msg).join("، "); } } catch { /* keep the fallback */ } throw new ApiError(res.status, message); } return res.json() as Promise; } function form(spec: DesignSpec, logo: File | null): FormData { const body = new FormData(); body.append("spec", JSON.stringify(spec)); if (logo) body.append("logo", logo); return body; } export const studio = { presets: () => call("/v1/studio/presets"), logoColors: (logo: File) => { const body = new FormData(); body.append("logo", logo); return call<{ colors: string[]; palettes: { key: string; label: string; colors: string[] }[] }>( "/v1/studio/logo", { method: "POST", body }, false); }, copy: (body: { type: string; size: string; width?: number; height?: number; style: string; lang: string; mode: "idea" | "text"; text: string }) => call("/v1/studio/copy", { method: "POST", body: JSON.stringify(body) }), design: (spec: DesignSpec, logo: File | null) => call("/v1/studio/design", { method: "POST", body: form(spec, logo) }, false), projects: (q = "") => call<{ items: DesignableRun[] }>(`/v1/studio/projects?q=${encodeURIComponent(q)}`), promo: (runId: string, spec: DesignSpec, logo: File | null) => call(`/v1/studio/promo/${runId}`, { method: "POST", body: form(spec, logo) }, false), kits: () => call<{ items: BrandKit[] }>("/v1/studio/brand-kits"), saveKit: (name: string, data: BrandKitData, logo: File | null, kitId?: string) => { const body = new FormData(); body.append("name", name); body.append("data", JSON.stringify(data)); if (kitId) body.append("kit_id", kitId); if (logo) body.append("logo", logo); return call("/v1/studio/brand-kits", { method: "POST", body }, false); }, deleteKit: (id: string) => call<{ ok: boolean }>(`/v1/studio/brand-kits/${id}`, { method: "DELETE" }), }; /** Words as the server counts them (agents.count): runs of letters and digits. */ export function countWords(value: unknown): number { const texts: string[] = []; const walk = (v: unknown) => { if (typeof v === "string") texts.push(v); else if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === "object") Object.values(v).forEach(walk); }; walk(value); return texts.reduce((n, t) => n + (t.match(/[\p{L}\p{N}%٪_]+/gu)?.length ?? 0), 0); } /** Save a data URL as a file. */ export function saveDataUrl(url: string, name: string) { const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); }