import type { AIProviderProfile, AIRoleRoutingEntry, AIConnectionTestResult, Project, AssetItem, BrandKit, FrozenRecipe, RenderJob, AspectRatio, } from '@olokaflow/shared'; const AUTH_TOKEN_KEY = 'olokaflow_auth_token'; export function getStoredAuthToken(): string { try { return localStorage.getItem(AUTH_TOKEN_KEY) || ''; } catch { return ''; } } export function setStoredAuthToken(token: string): void { try { if (token) { localStorage.setItem(AUTH_TOKEN_KEY, token); } else { localStorage.removeItem(AUTH_TOKEN_KEY); } } catch {} } async function apiJson(url: string, options?: RequestInit): Promise { const token = getStoredAuthToken(); const resp = await fetch(url, { headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(options?.headers || {}), }, ...options, }); const data = await resp.json().catch(() => ({})); if (!resp.ok) { throw new Error(data.error || data.message || `HTTP Error ${resp.status}`); } return data as T; } export const api = { // 0. Auth Login Gate & Team Governance getAuthMe: () => apiJson<{ authenticated: boolean; requireAuthGate: boolean; user: { id: string; email: string; name: string; role: string; tokenQuota: number; tokensUsed: number; } | null; }>('/api/auth/me'), login: async (email: string, password: string) => { const res = await apiJson<{ token: string; user: { id: string; email: string; name: string; role: string; tokenQuota: number; tokensUsed: number; }; }>('/api/auth/login', { method: 'POST', body: JSON.stringify({ email, password }), }); if (res.token) { setStoredAuthToken(res.token); } return res; }, logout: async () => { await apiJson('/api/auth/logout', { method: 'POST' }).catch(() => {}); setStoredAuthToken(''); }, setAuthGate: (requireAuthGate: boolean) => apiJson<{ success: boolean; requireAuthGate: boolean }>('/api/auth/gate', { method: 'PUT', body: JSON.stringify({ requireAuthGate }), }), // 1. AI Provider Profiles & 4-Tier Live Tester getAIProfiles: () => apiJson<{ profiles: AIProviderProfile[]; routings: AIRoleRoutingEntry[] }>('/api/ai-profiles'), saveAIProfile: (profile: Partial) => apiJson<{ success: boolean; profile: AIProviderProfile; profiles: AIProviderProfile[] }>( '/api/ai-profiles', { method: 'POST', body: JSON.stringify(profile) } ), deleteAIProfile: (id: string) => apiJson<{ success: boolean; profiles: AIProviderProfile[] }>(`/api/ai-profiles/${id}`, { method: 'DELETE', }), duplicateAIProfile: (id: string) => apiJson<{ success: boolean; profile: AIProviderProfile; profiles: AIProviderProfile[] }>( `/api/ai-profiles/${id}/duplicate`, { method: 'POST' } ), fetchModelsFromEndpoint: (payload: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: string; }) => apiJson<{ success: boolean; models: AIProviderProfile['models']; source: string; message: string; profiles: AIProviderProfile[]; }>('/api/ai-profiles/fetch-models', { method: 'POST', body: JSON.stringify(payload), }), testProfileConnection: (payload: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: string; modelId?: string; }) => apiJson<{ result: AIConnectionTestResult; profiles: AIProviderProfile[] }>( '/api/ai-profiles/test-connection', { method: 'POST', body: JSON.stringify(payload) } ), testModelPreflight: (payload: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: string; modelId: string; reasoningEffort?: string; }) => apiJson<{ result: AIConnectionTestResult; profiles: AIProviderProfile[] }>( '/api/ai-profiles/test-model', { method: 'POST', body: JSON.stringify(payload) } ), testModelVision: (payload: { profileId?: string; baseUrl?: string; apiKey?: string; protocol?: string; modelId: string; }) => apiJson<{ result: AIConnectionTestResult; profiles: AIProviderProfile[] }>( '/api/ai-profiles/test-vision', { method: 'POST', body: JSON.stringify(payload) } ), testMediaEndpoint: (payload: { profileId: string; testKind: 'voice' | 'image_gen' | 'modal_render'; modelId?: string; voiceId?: string; }) => apiJson<{ result: AIConnectionTestResult; profiles: AIProviderProfile[] }>( '/api/ai-profiles/test-media', { method: 'POST', body: JSON.stringify(payload) } ), saveRoleRoutings: (routings: AIRoleRoutingEntry[]) => apiJson<{ success: boolean; routings: AIRoleRoutingEntry[] }>('/api/ai-routings', { method: 'PUT', body: JSON.stringify({ routings }), }), // 2. HyperFrames 4-Tier Catalog, Voices & Zero-Shot Voice Cloning getCatalogOverview: () => apiJson('/api/catalog/overview'), getCatalog: () => apiJson('/api/catalog/overview'), getVoices: () => apiJson<{ voices: any[]; customVoices?: any[] }>('/api/voices'), cloneCustomVoice: async (params: { file: File; name: string; gender: string; region: string; description?: string; refText?: string; fallbackVoiceId?: string; }) => { const fd = new FormData(); fd.append('file', params.file); fd.append('name', params.name); fd.append('gender', params.gender); fd.append('region', params.region); if (params.description) fd.append('description', params.description); if (params.refText) fd.append('refText', params.refText); if (params.fallbackVoiceId) fd.append('fallbackVoiceId', params.fallbackVoiceId); const token = getStoredAuthToken(); const resp = await fetch('/api/voices/clone', { method: 'POST', headers: token ? { Authorization: `Bearer ${token}` } : {}, body: fd, }); const data = await resp.json(); if (!resp.ok) throw new Error(data.error || 'Clone giọng đọc thất bại'); return data as { success: boolean; voice: any; voices: any[] }; }, deleteCustomVoice: (id: string) => apiJson<{ success: boolean; voices: any[] }>(`/api/voices/custom/${id}`, { method: 'DELETE', }), searchCatalog: (q: string) => apiJson<{ items: any[] }>(`/api/catalog/search?q=${encodeURIComponent(q)}`), // 3. Asset Scraping, Upload & Multimodal Analysis getAssets: (projectId?: string) => apiJson<{ assets: AssetItem[] }>( projectId ? `/api/assets?projectId=${encodeURIComponent(projectId)}` : '/api/assets' ), uploadAssetFile: async (file: File) => { const fd = new FormData(); fd.append('file', file); const resp = await fetch('/api/assets/upload', { method: 'POST', body: fd }); const data = await resp.json(); if (!resp.ok) throw new Error(data.error || 'Upload thất bại'); return data as { success: boolean; asset: AssetItem; assets: AssetItem[] }; }, scrapeUrlAssets: (payload: { url: string; projectId?: string; brandTag?: string }) => apiJson<{ success: boolean; pageInfo: any; scrapedAssets: AssetItem[]; assets: AssetItem[]; }>('/api/assets/scrape-url', { method: 'POST', body: JSON.stringify(payload), }), searchWebAssets: (payload: { query: string; projectId?: string; limit?: number }) => apiJson<{ success: boolean; foundAssets: AssetItem[]; assets: AssetItem[]; }>('/api/assets/search-web', { method: 'POST', body: JSON.stringify(payload), }), reanalyzeAsset: (id: string) => apiJson<{ success: boolean; asset: AssetItem }>(`/api/assets/${id}/reanalyze`, { method: 'POST', }), deleteAsset: (id: string) => apiJson<{ success: boolean; assets: AssetItem[] }>(`/api/assets/${id}`, { method: 'DELETE', }), // 4. Projects & Studio Actions getProjects: () => apiJson<{ projects: Project[] }>('/api/projects'), createProject: (payload: Record) => apiJson<{ success: boolean; project: Project }>('/api/projects', { method: 'POST', body: JSON.stringify(payload), }), getProject: (id: string) => apiJson<{ project: Project; versions: Array<{ id: string; versionNum: number; label: string; createdAt: string }>; }>(`/api/projects/${id}`), deleteProject: (id: string) => apiJson<{ success: boolean; projects: Project[] }>(`/api/projects/${id}`, { method: 'DELETE', }), abortProject: (id: string) => apiJson<{ success: boolean; project: Project }>(`/api/projects/${id}/abort`, { method: 'POST', }), updateStoryboard: (id: string, payload: Record) => apiJson<{ success: boolean; project: Project }>(`/api/projects/${id}/storyboard`, { method: 'PUT', body: JSON.stringify(payload), }), regenerateSceneImage: (projectId: string, sceneIndex: number, imagePrompt?: string) => apiJson<{ success: boolean; project: Project }>( `/api/projects/${projectId}/scenes/${sceneIndex}/regenerate-image`, { method: 'POST', body: JSON.stringify({ imagePrompt }) } ), resynthesizeSceneVoice: ( projectId: string, sceneIndex: number, narrationText?: string, voiceId?: string, speed?: number ) => apiJson<{ success: boolean; project: Project }>( `/api/projects/${projectId}/scenes/${sceneIndex}/resynthesize-voice`, { method: 'POST', body: JSON.stringify({ narrationText, voiceId, speed }) } ), approveStoryboardAndBuild: (projectId: string) => apiJson<{ success: boolean; project: Project }>( `/api/projects/${projectId}/approve-storyboard`, { method: 'POST' } ), promptEditProject: ( projectId: string, editPrompt: string, targetSceneIndex?: number ) => apiJson<{ success: boolean; project: Project; summary: string; versions: Array<{ id: string; versionNum: number; label: string; createdAt: string }>; }>(`/api/projects/${projectId}/prompt-edit`, { method: 'POST', body: JSON.stringify({ editPrompt, targetSceneIndex }), }), quickEditProject: ( projectId: string, payload: { sceneIndex: number; title?: string; narrationText?: string; referenceImageUrl?: string; blueprintId?: string; } ) => apiJson<{ success: boolean; project: Project; versions: Array<{ id: string; versionNum: number; label: string; createdAt: string }>; }>(`/api/projects/${projectId}/quick-edit`, { method: 'POST', body: JSON.stringify(payload), }), remixAspectRatio: (projectId: string, aspectRatio: AspectRatio) => apiJson<{ success: boolean; project: Project; versions: Array<{ id: string; versionNum: number; label: string; createdAt: string }>; }>(`/api/projects/${projectId}/remix-aspect`, { method: 'POST', body: JSON.stringify({ aspectRatio }), }), restoreVersion: (projectId: string, versionId: string) => apiJson<{ success: boolean; project: Project; versions: Array<{ id: string; versionNum: number; label: string; createdAt: string }>; }>(`/api/projects/${projectId}/versions/${versionId}/restore`, { method: 'POST', }), saveProjectAsRecipe: (projectId: string, name: string, description: string) => apiJson<{ success: boolean; recipe: FrozenRecipe }>( `/api/projects/${projectId}/save-recipe`, { method: 'POST', body: JSON.stringify({ name, description }) } ), // 5. Brand Kits, Frozen Recipes, Renders & Admin getBrandKits: () => apiJson<{ brandKits: BrandKit[] }>('/api/brand-kits'), saveBrandKit: (kit: Partial) => apiJson<{ success: boolean; brandKit: BrandKit }>('/api/brand-kits', { method: 'POST', body: JSON.stringify(kit), }), saveBrand: (kit: Record) => apiJson<{ success: boolean; brandKit: BrandKit }>('/api/brand-kits', { method: 'POST', body: JSON.stringify(kit), }), deleteBrandKit: (id: string) => apiJson<{ success: boolean }>(`/api/brand-kits/${id}`, { method: 'DELETE' }), getRecipes: () => apiJson<{ recipes: FrozenRecipe[] }>('/api/recipes'), getBrandsAndRecipes: async () => { const [bRes, rRes] = await Promise.all([ apiJson<{ brandKits: BrandKit[] }>('/api/brand-kits'), apiJson<{ recipes: FrozenRecipe[] }>('/api/recipes'), ]); return { brands: bRes.brandKits || [], recipes: rRes.recipes || [], }; }, getRenders: (projectId?: string) => apiJson<{ jobs: RenderJob[] }>( projectId ? `/api/renders?projectId=${encodeURIComponent(projectId)}` : '/api/renders' ), getRenderJobs: (projectId?: string) => apiJson<{ jobs: RenderJob[] }>( projectId ? `/api/renders?projectId=${encodeURIComponent(projectId)}` : '/api/renders' ), startRender: (projectId: string, provider: 'modal' | 'local' = 'modal') => apiJson<{ success: boolean; job: RenderJob }>(`/api/projects/${projectId}/render`, { method: 'POST', body: JSON.stringify({ provider }), }), cancelRender: (jobId: string) => apiJson<{ success: boolean; job: RenderJob }>(`/api/renders/${jobId}/cancel`, { method: 'POST', }), getAdminOverview: () => apiJson('/api/admin/overview'), getVaultStatus: async () => { const ov = await apiJson('/api/admin/overview'); return ov.vaultStatus || ov; }, syncVault: () => apiJson<{ success: boolean; message: string }>('/api/admin/vault/sync', { method: 'POST', }), triggerVaultBackup: async () => { await apiJson<{ success: boolean; message: string }>('/api/admin/vault/sync', { method: 'POST', }); const ov = await apiJson('/api/admin/overview'); return ov.vaultStatus || ov; }, getUsers: () => apiJson<{ requireAuthGate?: boolean; users: any[] }>('/api/admin/users'), createUser: (payload: any) => apiJson<{ success: boolean; id: string }>('/api/admin/users', { method: 'POST', body: JSON.stringify(payload), }), deleteUser: (id: string) => apiJson<{ success: boolean }>(`/api/admin/users/${id}`, { method: 'DELETE', }), // 6. Batch Video Factory (Multi-URL / CSV / Bulk Queue) getBatches: () => apiJson<{ batches: any[] }>('/api/batches'), createBatch: (payload: Record) => apiJson<{ success: boolean; batchId: string; batches: any[] }>('/api/batches', { method: 'POST', body: JSON.stringify(payload), }), deleteBatch: (id: string) => apiJson<{ success: boolean; batches: any[] }>(`/api/batches/${id}`, { method: 'DELETE', }), };