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 
 
 
 
 
 
 
 
 
66e744c
 
 
 
91d209c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import type { 
  VideoStatusResponse, 
  SegmentsPayload,
  HealthStatus,
  ExtractedFrame,
  LoginRequest,
  LoginResponse,
  AuthUser
} from '@/types';

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';

// Get auth token from localStorage
function getAuthToken(): string | null {
  return localStorage.getItem('auth_token');
}

// Set auth token in localStorage
export function setAuthToken(token: string): void {
  localStorage.setItem('auth_token', token);
}

// Remove auth token from localStorage
export function removeAuthToken(): void {
  localStorage.removeItem('auth_token');
}

// Generic API request handler
async function apiRequest<T>(
  path: string, 
  options: RequestInit = {}
): Promise<T> {
  const url = path.startsWith('http') ? path : `${API_BASE}${path}`;
  const token = getAuthToken();
  
  // Normalize headers to a plain object
  const headers: Record<string, string> = {};
  
  // Convert Headers object or array to plain object
  if (options.headers) {
    if (options.headers instanceof Headers) {
      options.headers.forEach((value, key) => {
        headers[key] = value;
      });
    } else if (Array.isArray(options.headers)) {
      options.headers.forEach(([key, value]) => {
        headers[key] = value;
      });
    } else {
      Object.assign(headers, options.headers);
    }
  }
  
  // Add auth token if available
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  
  const response = await fetch(url, {
    ...options,
    headers,
  });

  if (!response.ok) {
    // If unauthorized, clear token
    if (response.status === 401) {
      removeAuthToken();
    }
    
    let errorMessage = `Request failed with status ${response.status}`;
    
    // Try to extract error message from response
    const contentType = response.headers.get('content-type');
    const isJson = contentType && contentType.includes('application/json');
    
    try {
      if (isJson) {
      const errorData = await response.json();
        // Try multiple common error message fields
        errorMessage = errorData.detail || 
                       errorData.message || 
                       errorData.error || 
                       (typeof errorData === 'string' ? errorData : errorMessage);
      } else {
        const text = await response.text();
        if (text && text.trim()) {
          errorMessage = text;
        } else {
          // Fall back to default message based on status code
          if (response.status === 401) {
            errorMessage = 'Incorrect username or password.';
          } else if (response.status === 403) {
            errorMessage = 'Access forbidden.';
          } else if (response.status === 404) {
            errorMessage = 'Resource not found.';
          } else if (response.status >= 500) {
            errorMessage = 'Server error. Please try again later.';
          }
        }
      }
    } catch (parseError) {
      // If parsing fails, use status-based default
      if (response.status === 401) {
        errorMessage = 'Incorrect username or password.';
      } else if (response.status === 403) {
        errorMessage = 'Access forbidden.';
      } else if (response.status === 404) {
        errorMessage = 'Resource not found.';
      } else if (response.status >= 500) {
        errorMessage = 'Server error. Please try again later.';
      }
    }
    
    const error = new Error(errorMessage);
    console.error('API Error:', {
      status: response.status,
      statusText: response.statusText,
      message: errorMessage,
      url: url,
      contentType: contentType
    });
    throw error;
  }

  return response.json();
}

// Health check
export async function checkHealth(): Promise<HealthStatus> {
  return apiRequest<HealthStatus>('/health');
}

// ==================== AUTHENTICATION ====================

export async function login(credentials: LoginRequest): Promise<LoginResponse> {
  const response = await apiRequest<LoginResponse>('/api/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(credentials),
  });
  
  // Store token
  if (response.access_token) {
    setAuthToken(response.access_token);
  }
  
  return response;
}

export async function verifyAuth(): Promise<AuthUser> {
  try {
    const response = await apiRequest<AuthUser>('/api/auth/verify');
    return response;
  } catch {
    removeAuthToken();
    return { username: '', authenticated: false };
  }
}

export async function getCurrentUser(): Promise<AuthUser> {
  try {
    const response = await apiRequest<AuthUser>('/api/auth/me');
    return response;
  } catch {
    removeAuthToken();
    return { username: '', authenticated: false };
  }
}

export function logout(): void {
  removeAuthToken();
}

// ==================== KLING/KIE API ====================

export interface KlingGenerateParams {
  prompt: string | object;
  imageUrls?: string[];
  model?: string;
  aspectRatio?: string;
  generationType?: string;
  seeds?: number;
  voiceType?: string;
}

export interface KlingGenerateResponse {
  taskId: string;
  status: string;
}

export async function klingGenerate(params: KlingGenerateParams): Promise<KlingGenerateResponse> {
  return apiRequest<KlingGenerateResponse>('/api/veo/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
}

export async function klingExtend(taskId: string, prompt: string | object, seeds?: number, voiceType?: string): Promise<KlingGenerateResponse> {
  return apiRequest<KlingGenerateResponse>('/api/veo/extend', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ taskId, prompt, seeds, voiceType }),
  });
}

export async function klingGetStatus(taskId: string): Promise<VideoStatusResponse> {
  return apiRequest<VideoStatusResponse>(`/api/veo/status/${taskId}`);
}

export async function klingCancel(taskId: string): Promise<{ code: number; msg: string; taskId: string }> {
  return apiRequest<{ code: number; msg: string; taskId: string }>(`/api/veo/cancel/${taskId}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
  });
}

export function createKlingEventSource(taskId: string): EventSource {
  return new EventSource(`${API_BASE}/api/veo/events/${taskId}`);
}

// ==================== REPLICATE API ====================

export interface ReplicateGenerateParams {
  prompt: string;
  imageUrl?: string;
  model?: string;
  duration?: number;
  aspectRatio?: string;
}

export interface ReplicateGenerateResponse {
  id: string;
  status: string;
}

export async function replicateGenerate(params: ReplicateGenerateParams): Promise<ReplicateGenerateResponse> {
  return apiRequest<ReplicateGenerateResponse>('/api/replicate/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
}

export async function replicateGetStatus(predictionId: string): Promise<VideoStatusResponse> {
  return apiRequest<VideoStatusResponse>(`/api/replicate/status/${predictionId}`);
}

// Wait for Replicate video completion by polling
export async function waitForReplicateVideo(
  predictionId: string, 
  timeoutMs: number = 600000, // 10 minutes
  pollIntervalMs: number = 15000 // Poll every 15 seconds (video gen takes 2-5 min)
): Promise<string> {
  const startTime = Date.now();
  
  while (Date.now() - startTime < timeoutMs) {
    const status = await replicateGetStatus(predictionId);
    
    if (status.status === 'succeeded' && status.url) {
      return status.url;
    } else if (status.status === 'failed') {
      throw new Error(status.error || 'Replicate video generation failed');
    }
    
    // Wait before next poll
    await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
  }
  
  throw new Error('Replicate video generation timed out');
}

// ==================== PROMPT GENERATION ====================

export async function generatePrompts(formData: FormData): Promise<SegmentsPayload> {
  const response = await fetch(`${API_BASE}/api/generate-prompts`, {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    let errorMessage = 'Failed to generate prompts';
    try {
      const errorData = await response.json();
      errorMessage = errorData.detail || errorMessage;
    } catch {
      // Ignore
    }
    throw new Error(errorMessage);
  }

  return response.json();
}

export async function refinePromptContinuity(
  segmentPrompt: object, 
  lastFrameBlob: Blob
): Promise<{ refined_prompt: object }> {
  const formData = new FormData();
  formData.append('segmentPrompt', JSON.stringify(segmentPrompt));
  formData.append('lastFrame', lastFrameBlob, 'last-frame.jpg');

  return apiRequest<{ refined_prompt: object }>('/api/refine-prompt-continuity', {
    method: 'POST',
    body: formData,
  });
}

// ==================== IMAGE UPLOAD ====================

export async function uploadImage(file: File): Promise<{ url: string; filename: string }> {
  const formData = new FormData();
  formData.append('file', file);

  return apiRequest<{ url: string; filename: string }>('/api/upload-image', {
    method: 'POST',
    body: formData,
  });
}

// ==================== FRAME EXTRACTION ====================

export interface ExtractFramesParams {
  video_url: string;
  script?: string;
  buffer_time?: number;
  num_frames?: number;
  model_size?: string;
}

export interface ExtractFramesResponse {
  frames: ExtractedFrame[];
}

export async function extractFrames(params: ExtractFramesParams): Promise<ExtractFramesResponse> {
  return apiRequest<ExtractFramesResponse>('/api/extract-frames', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
}

// ==================== WHISPER ANALYSIS ====================

export interface WhisperAnalyzeParams {
  video_url: string;
  dialogue: string;
  buffer_time?: number;
  model_size?: string;
}

export interface WhisperAnalyzeResponse {
  success: boolean;
  last_word_timestamp: number | null;
  trim_point: number | null;
  frame_timestamp: number | null;
  frame_base64: string | null;
  video_duration: number;
  transcribed_text: string | null;  // What Whisper actually heard - for prompt refinement
  error: string | null;
}

/**
 * Analyze video with Whisper to find last spoken word and extract frame.
 * This is the optimized flow that combines Whisper analysis and frame extraction.
 */
export async function whisperAnalyzeAndExtract(params: WhisperAnalyzeParams): Promise<WhisperAnalyzeResponse> {
  return apiRequest<WhisperAnalyzeResponse>('/api/whisper/analyze-and-extract', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
}

/**
 * Refine a segment prompt using the frame AND transcription from the previous segment.
 * This ensures perfect visual and audio continuity.
 */
export async function refinePromptWithContext(
  segmentPrompt: object,
  frameFile: File,
  transcribedDialogue: string,
  expectedDialogue: string
): Promise<{ refined_prompt: object; original_prompt: object }> {
  const formData = new FormData();
  formData.append('segmentPrompt', JSON.stringify(segmentPrompt));
  formData.append('lastFrame', frameFile);
  formData.append('transcribedDialogue', transcribedDialogue);
  formData.append('expectedDialogue', expectedDialogue);
  
  const response = await fetch(`${API_BASE}/api/refine-prompt-continuity`, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    throw new Error(`Failed to refine prompt: ${response.status}`);
  }
  
  return response.json();
}

/**
 * Check if Whisper is available on the backend
 */
export async function checkWhisperStatus(): Promise<{ available: boolean; message: string }> {
  return apiRequest<{ available: boolean; message: string }>('/api/whisper/status');
}

// ==================== VIDEO DOWNLOAD ====================

export async function downloadVideo(url: string): Promise<Blob> {
  const response = await fetch(`${API_BASE}/api/veo/download?url=${encodeURIComponent(url)}`);
  
  if (!response.ok) {
    throw new Error(`Failed to download video: ${response.status}`);
  }

  return response.blob();
}

// ==================== UTILITIES ====================

export async function getVideoDuration(file: File): Promise<number> {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.src = URL.createObjectURL(file);
    video.onloadedmetadata = () => {
      URL.revokeObjectURL(video.src);
      resolve(video.duration);
    };
    video.onerror = () => {
      URL.revokeObjectURL(video.src);
      reject(new Error('Failed to load video metadata'));
    };
  });
}

export async function generateThumbnails(file: File, count: number = 5): Promise<string[]> {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.src = URL.createObjectURL(file);
    video.muted = true;

    video.onloadedmetadata = async () => {
      const duration = video.duration;
      const thumbnails: string[] = [];
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        URL.revokeObjectURL(video.src);
        reject(new Error('Could not get canvas context'));
        return;
      }

      // Use video's actual dimensions for proper aspect ratio
      // Scale down while maintaining aspect ratio (max 400px on longest side)
      const maxSize = 400;
      const videoWidth = video.videoWidth || 1080;
      const videoHeight = video.videoHeight || 1920;
      const scale = Math.min(maxSize / videoWidth, maxSize / videoHeight);
      
      canvas.width = Math.round(videoWidth * scale);
      canvas.height = Math.round(videoHeight * scale);

      for (let i = 0; i < count; i++) {
        const time = (duration / count) * i;
        video.currentTime = time;
        await new Promise<void>((res) => {
          video.onseeked = () => res();
        });
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        thumbnails.push(canvas.toDataURL('image/jpeg', 0.85));
      }

      URL.revokeObjectURL(video.src);
      resolve(thumbnails);
    };

    video.onerror = () => {
      URL.revokeObjectURL(video.src);
      reject(new Error('Failed to load video'));
    };
  });
}

// Wait for video completion using SSE
export function waitForKlingVideo(taskId: string, timeoutMs: number = 300000): Promise<string> {
  return new Promise((resolve, reject) => {
    const eventSource = createKlingEventSource(taskId);
    const startTime = Date.now();

    const timeout = setTimeout(() => {
      eventSource.close();
      reject(new Error('Video generation timed out'));
    }, timeoutMs);

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        
        if (data.status === 'succeeded' && data.url) {
          clearTimeout(timeout);
          eventSource.close();
          resolve(data.url);
        } else if (data.status === 'cancelled') {
          clearTimeout(timeout);
          eventSource.close();
          reject(new Error('Video generation cancelled by user'));
        } else if (data.status === 'failed' || data.code !== undefined && data.code !== 200) {
          clearTimeout(timeout);
          eventSource.close();
          const errorMsg = data.error || data.msg || `Video generation failed (code: ${data.code || 'unknown'})`;
          reject(new Error(errorMsg));
        }
      } catch (err) {
        console.error('Failed to parse SSE data:', err);
        // If we can't parse, don't reject immediately - might be a partial message
      }
    };

    eventSource.onerror = () => {
      // If connection error and we've been waiting a while, reject
      const elapsed = Date.now() - startTime;
      if (elapsed > 5000) { // Wait at least 5 seconds before rejecting on connection error
        clearTimeout(timeout);
        eventSource.close();
        reject(new Error('SSE connection error - video generation may have failed'));
      }
    };
  });
}

// Generate video with automatic retry (retries once on failure)
export async function generateVideoWithRetry(
  generateFn: () => Promise<{ taskId: string }>,
  timeoutMs: number = 300000,
  onRetry?: (attempt: number) => void
): Promise<string> {
  let lastError: Error | null = null;
  
  for (let attempt = 0; attempt < 2; attempt++) {
    try {
      if (attempt > 0) {
        console.log(`🔄 Retrying video generation (attempt ${attempt + 1}/2)...`);
        if (onRetry) {
          onRetry(attempt + 1);
        }
      }
      
      const result = await generateFn();
      const videoUrl = await waitForKlingVideo(result.taskId, timeoutMs);
      return videoUrl;
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error));
      console.error(`❌ Video generation attempt ${attempt + 1} failed:`, lastError.message);
      
      // If this was the first attempt, retry once
      if (attempt === 0) {
        console.log('⏳ Waiting 2 seconds before retry...');
        await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds before retry
        continue;
      }
      
      // If both attempts failed, throw the error
      throw lastError;
    }
  }
  
  // This should never be reached, but TypeScript needs it
  throw lastError || new Error('Video generation failed');
}

// ==================== VIDEO MERGE/EXPORT ====================

export interface ClipMetadata {
  index: number;
  startTime: number;
  endTime: number;
  type: 'video' | 'image';
  duration?: number;
}

// Merge multiple video files into a single video
export async function mergeVideos(
  videoBlobs: Blob[],
  clipMetadata: ClipMetadata[]
): Promise<Blob> {
  const formData = new FormData();
  
  // Add clip metadata as JSON
  formData.append('clips_data', JSON.stringify(clipMetadata));
  
  // Add video files
  videoBlobs.forEach((blob, index) => {
    formData.append('files', blob, `video_${index}.mp4`);
  });
  
  const response = await fetch(`${API_BASE}/api/export/merge`, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    let errorMessage = 'Failed to merge videos';
    try {
      const errorData = await response.json();
      errorMessage = errorData.detail || errorMessage;
    } catch {
      // Ignore JSON parse errors
    }
    throw new Error(errorMessage);
  }
  
  return response.blob();
}