File size: 54,050 Bytes
5ef6e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
import { Router, type Response as ExpressResponse, type Request } from "express";
import { db, videosTable, usersTable, configTable, creditTransactionsTable } from "@workspace/db";
import { desc, eq, and, or, sql } from "drizzle-orm";
import { randomUUID } from "crypto";
import {
  getValidBearerToken,
  refreshAccessToken,
  getPoolToken,
  tryRefreshPoolAccount,
} from "./config";
import { getTurnstileToken, invalidateTurnstileToken } from "../captcha";
import { generateGuardId } from "../guardId";
import { optionalJwtAuth } from "./auth";
import { downloadAndStoreVideo, streamStoredVideo, isStorageReady } from "../lib/videoStorage";

const router = Router();

const GEMINIGEN_BASE    = "https://api.geminigen.ai";
const GROK_ENDPOINT     = `${GEMINIGEN_BASE}/api/video-gen/grok-stream`;
const VEO_ENDPOINT      = `${GEMINIGEN_BASE}/api/video-gen/veo`;
const USER_AGENT =
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36";

// โ”€โ”€ In-memory task store โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Tasks live here between POST /generate (which creates them) and the
// SSE /progress/:taskId endpoint which a client subscribes to.

type TaskStatus = "pending" | "complete" | "failed";

interface ProgressEvent {
  type: "start" | "progress" | "complete" | "error";
  message?: string;
  status?: number;
  uuid?: string;
  video?: unknown;
  errorCode?: string;
}

interface Task {
  status: TaskStatus;
  createdAt: number;
  buffered: ProgressEvent[];                  // events buffered before client connects
  clients: Set<(e: ProgressEvent) => void>;  // active SSE listeners
}

const tasks = new Map<string, Task>();

// Clean up tasks older than 30 min
setInterval(() => {
  const cutoff = Date.now() - 30 * 60 * 1000;
  for (const [id, t] of tasks) {
    if (t.createdAt < cutoff) tasks.delete(id);
  }
}, 5 * 60 * 1000);

function createTask(): string {
  const id = randomUUID();
  tasks.set(id, { status: "pending", createdAt: Date.now(), buffered: [], clients: new Set() });
  return id;
}

function broadcast(task: Task, event: ProgressEvent): void {
  if (task.status === "pending") task.buffered.push(event);
  for (const client of task.clients) {
    try { client(event); } catch { /* ignore broken pipe */ }
  }
}

function finishTask(task: Task, status: TaskStatus, final: ProgressEvent): void {
  task.status = status;
  task.buffered.push(final);
  for (const client of task.clients) {
    try { client(final); } catch {}
  }
  task.clients.clear();
}

// โ”€โ”€ Video generation options โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
export type VideoModel = "grok-3" | "veo-3-fast";

export interface VideoGenOptions {
  model: VideoModel;
  prompt: string;
  negativePrompt?: string;
  aspectRatio: "16:9" | "9:16" | "1:1" | "3:4" | "4:3";
  resolution: "480p" | "720p" | "1080p";
  duration: 5 | 6 | 8 | 10;
  enhancePrompt: boolean;
  refImageBase64?: string;
  refImageMime?: string;
}

// โ”€โ”€ Model constraints โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Grok-3 limits (API confirmed)
const GROK3_MAX_DURATION   = 6;
const GROK3_MAX_RESOLUTION = "720p";

// Veo 3.1 Fast limits (API confirmed)
// duration: 8s only, aspect ratios: 16:9 / 9:16 only
const VEO_VALID_ASPECT_RATIOS = new Set(["16:9", "9:16"]);
const VEO_DURATION = 8 as const;

// Grok-3 aspect ratio mapping: raw user ratio โ†’ API keyword
const GROK_ASPECT_RATIO_MAP: Record<string, string> = {
  "16:9": "landscape",
  "4:3":  "landscape",
  "3:2":  "3:2",
  "9:16": "portrait",
  "3:4":  "portrait",
  "2:3":  "2:3",
  "1:1":  "square",
};

const VALID_ASPECT_RATIOS = new Set(["16:9", "9:16", "1:1", "3:4", "4:3"]);
const VALID_RESOLUTIONS   = new Set(["480p", "720p", "1080p"]);
const VALID_DURATIONS     = new Set([5, 6, 8, 10]);
const RESOLUTION_RANK: Record<string, number> = { "480p": 0, "720p": 1, "1080p": 2 };

export function parseVideoOptions(body: Record<string, unknown>, prompt: string): VideoGenOptions {
  const model: VideoModel = body.model === "veo-3-fast" ? "veo-3-fast" : "grok-3";

  let aspectRatio = VALID_ASPECT_RATIOS.has(body.aspectRatio as string)
    ? (body.aspectRatio as VideoGenOptions["aspectRatio"]) : "16:9";

  let resolution = VALID_RESOLUTIONS.has(body.resolution as string)
    ? (body.resolution as VideoGenOptions["resolution"]) : "480p";

  let duration = VALID_DURATIONS.has(Number(body.duration))
    ? (Number(body.duration) as VideoGenOptions["duration"]) : 6;

  if (model === "grok-3") {
    // Clamp resolution to max 720p
    if (RESOLUTION_RANK[resolution] > RESOLUTION_RANK[GROK3_MAX_RESOLUTION]) {
      resolution = GROK3_MAX_RESOLUTION;
    }
    // Clamp duration to max 6s
    if (duration > GROK3_MAX_DURATION) {
      duration = GROK3_MAX_DURATION as VideoGenOptions["duration"];
    }
  } else if (model === "veo-3-fast") {
    // Force duration to 8s
    duration = VEO_DURATION;
    // Restrict to 16:9 / 9:16
    if (!VEO_VALID_ASPECT_RATIOS.has(aspectRatio)) {
      aspectRatio = "16:9";
    }
  }

  const negativePrompt = typeof body.negativePrompt === "string" && body.negativePrompt.trim()
    ? body.negativePrompt.trim() : undefined;
  const enhancePrompt = body.enhancePrompt !== false;

  return { model, prompt, negativePrompt, aspectRatio, resolution, duration, enhancePrompt };
}

// โ”€โ”€ Helper: build FormData โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function base64ToBlob(base64: string, mime: string): Blob {
  const binary = Buffer.from(base64, "base64");
  return new Blob([binary], { type: mime });
}

// โ”€โ”€ Grok-3 form builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function buildGrokForm(turnstileToken: string, opts: VideoGenOptions): FormData {
  const form = new FormData();
  form.append("prompt", opts.prompt);
  form.append("model", "grok-3");
  form.append("model_name", "grok-3");
  // Aspect ratio: API expects 'landscape'|'portrait'|'square'|'3:2'|'2:3'
  const apiAspectRatio = GROK_ASPECT_RATIO_MAP[opts.aspectRatio] ?? "landscape";
  form.append("aspect_ratio", apiAspectRatio);
  form.append("resolution", opts.resolution);
  form.append("duration", opts.duration.toString());
  form.append("num_result", "1");
  form.append("enhance_prompt", opts.enhancePrompt ? "true" : "false");
  form.append("turnstile_token", turnstileToken);
  if (opts.negativePrompt) form.append("negative_prompt", opts.negativePrompt);
  if (opts.refImageBase64 && opts.refImageMime) {
    // Presence of 'files' tells the API this is image-to-video.
    // Do NOT set mode='image_to_video' โ€” the 'mode' field is a creativity level
    // (normal | custom | extremely-crazy | extremely-spicy-or-crazy).
    form.append("files", base64ToBlob(opts.refImageBase64, opts.refImageMime), "reference.jpg");
    form.append("mode", "custom");
  }
  return form;
}

// โ”€โ”€ Veo form builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function buildVeoForm(turnstileToken: string, opts: VideoGenOptions): FormData {
  const form = new FormData();
  form.append("prompt", opts.prompt);
  form.append("model", "veo-3-fast");
  // Veo uses raw ratio strings directly ('16:9' or '9:16')
  form.append("aspect_ratio", opts.aspectRatio);
  form.append("duration", opts.duration.toString());
  form.append("enhance_prompt", opts.enhancePrompt ? "true" : "false");
  form.append("turnstile_token", turnstileToken);
  if (opts.negativePrompt) form.append("negative_prompt", opts.negativePrompt);
  if (opts.refImageBase64 && opts.refImageMime) {
    form.append("ref_images", base64ToBlob(opts.refImageBase64, opts.refImageMime), "reference.jpg");
    form.append("mode_image", "image_to_video");
  }
  return form;
}

// โ”€โ”€ Grok-3 SSE endpoint โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async function callGrokEndpoint(
  bearerToken: string,
  turnstileToken: string,
  opts: VideoGenOptions,
): Promise<Response> {
  const guardId = generateGuardId("/api/video-gen/grok-stream", "post");
  return fetch(GROK_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${bearerToken}`,
      "x-guard-id": guardId,
      "User-Agent": USER_AGENT,
      Accept: "text/event-stream, application/json",
    },
    body: buildGrokForm(turnstileToken, opts),
  });
}

// โ”€โ”€ Veo POST endpoint (returns {uuid}, then poll) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async function callVeoEndpoint(
  bearerToken: string,
  turnstileToken: string,
  opts: VideoGenOptions,
): Promise<{ uuid: string }> {
  const guardId = generateGuardId("/api/video-gen/veo", "post");
  const resp = await fetch(VEO_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${bearerToken}`,
      "x-guard-id": guardId,
      "User-Agent": USER_AGENT,
      Accept: "application/json",
    },
    body: buildVeoForm(turnstileToken, opts),
  });
  if (!resp.ok) {
    const raw = await resp.text().catch(() => "");
    const { code, msg } = parseErrBody(raw);
    throw Object.assign(new Error(msg || `HTTP ${resp.status}`), { code, status: resp.status, raw });
  }
  const data = await resp.json() as { uuid?: string; history_uuid?: string; task_id?: string; id?: string };
  console.log("[veo-submit] response:", JSON.stringify(data).slice(0, 300));
  const uuid = data.uuid || data.history_uuid || data.task_id || data.id;
  if (!uuid) throw new Error(`Veo API did not return a UUID. Response: ${JSON.stringify(data).slice(0, 200)}`);
  return { uuid };
}

// โ”€โ”€ One-shot history fetch: get the R2 pre-signed URL after generation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// geminigen.ai stores completed videos to Cloudflare R2 and returns a 7-day
// pre-signed URL in generated_video[0].video_url.  This works without any
// additional auth, unlike the intermediate assets.grok.com CDN URL.
async function fetchHistoryVideoUrl(
  uuid: string,
  bearerToken: string,
): Promise<{ videoUrl: string; thumbnailUrl: string | null } | null> {
  try {
    const guardId = generateGuardId("/api/history/" + uuid, "get");
    const resp = await fetch(`${GEMINIGEN_BASE}/api/history/${uuid}`, {
      headers: {
        Authorization: `Bearer ${bearerToken}`,
        "x-guard-id": guardId,
        "User-Agent": USER_AGENT,
        Accept: "application/json",
      },
    });
    if (!resp.ok) {
      console.warn("[history-fetch] HTTP", resp.status, "for uuid", uuid);
      return null;
    }
    const data = await resp.json() as {
      status?: number;
      generated_video?: Array<{ video_url?: string; thumbnail_url?: string }>;
    };
    const vid = data.generated_video?.[0];
    const videoUrl = vid?.video_url ?? null;
    const thumbnailUrl = vid?.thumbnail_url ?? null;
    if (videoUrl) {
      console.log("[history-fetch] got R2 URL:", videoUrl.slice(0, 120));
      return { videoUrl, thumbnailUrl };
    }
    return null;
  } catch (err) {
    console.warn("[history-fetch] error:", err instanceof Error ? err.message : err);
    return null;
  }
}

// โ”€โ”€ Veo polling: GET /api/history/{uuid} until status 2/3 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Veo generation typically takes 2โ€“8 minutes on geminigen.ai; we poll up to
// 12 minutes with a 20s interval (first check after 15s to catch fast results).
async function pollVeoHistory(
  uuid: string,
  bearerToken: string,
  onProgress: (msg: string) => void,
  maxWaitMs = 720_000, // 12 minutes
): Promise<{ videoUrl: string; thumbnailUrl: string | null } | null> {
  const start = Date.now();
  let attempt = 0;
  let waitMs = 15_000; // first check sooner; subsequent checks every 20s

  while (Date.now() - start < maxWaitMs) {
    await new Promise((r) => setTimeout(r, waitMs));
    waitMs = 20_000; // steady-state interval
    attempt++;
    const elapsed = Math.round((Date.now() - start) / 1000);
    onProgress(`Veo ็”Ÿๆˆไธญ๏ผŒ็ฌฌ ${attempt} ๆฌก็ขบ่ช... (ๅทฒ็ญ‰ๅพ… ${elapsed}s)`);

    const guardId = generateGuardId("/api/history/" + uuid, "get");
    let resp: Response;
    try {
      resp = await fetch(`${GEMINIGEN_BASE}/api/history/${uuid}`, {
        headers: {
          Authorization: `Bearer ${bearerToken}`,
          "x-guard-id": guardId,
          "User-Agent": USER_AGENT,
          Accept: "application/json",
        },
        signal: AbortSignal.timeout(15_000),
      });
    } catch (fetchErr) {
      console.warn("[veo-poll] fetch error on attempt", attempt, ":", fetchErr instanceof Error ? fetchErr.message : fetchErr);
      continue;
    }

    if (!resp.ok) {
      console.warn("[veo-poll] history HTTP", resp.status, "for uuid", uuid, "attempt", attempt);
      continue;
    }

    let data: {
      status?: number;
      generated_video?: Array<{ video_url?: string; thumbnail_url?: string; media_url?: string }>;
      video_url?: string;
    };
    try {
      data = await resp.json();
    } catch {
      console.warn("[veo-poll] JSON parse failed on attempt", attempt);
      continue;
    }

    console.log("[veo-poll] attempt", attempt, "status=", data.status,
      "has_video=", !!(data.generated_video?.[0]?.video_url || data.video_url));

    if (data.status === 2) {
      const vid = data.generated_video?.[0];
      // Try multiple possible URL fields
      const videoUrl = vid?.video_url || vid?.media_url || data.video_url || null;
      const thumbnailUrl = vid?.thumbnail_url ?? null;
      if (videoUrl) {
        console.log("[veo-poll] completed with video URL:", videoUrl.slice(0, 120));
        return { videoUrl, thumbnailUrl };
      }
      // Status 2 but no URL โ€” wait a bit and try once more
      console.warn("[veo-poll] status=2 but no video URL, retrying in 10s...");
      await new Promise((r) => setTimeout(r, 10_000));
      const guardId2 = generateGuardId("/api/history/" + uuid, "get");
      const resp2 = await fetch(`${GEMINIGEN_BASE}/api/history/${uuid}`, {
        headers: { Authorization: `Bearer ${bearerToken}`, "x-guard-id": guardId2,
          "User-Agent": USER_AGENT, Accept: "application/json" },
      }).catch(() => null);
      if (resp2?.ok) {
        const data2 = await resp2.json().catch(() => ({})) as typeof data;
        const vid2 = data2.generated_video?.[0];
        const videoUrl2 = vid2?.video_url || vid2?.media_url || data2.video_url || null;
        if (videoUrl2) return { videoUrl: videoUrl2, thumbnailUrl: vid2?.thumbnail_url ?? null };
      }
      return null; // complete but no URL
    }

    if (data.status === 3) {
      console.warn("[veo-poll] status=3 (failed) for uuid", uuid);
      return null; // failed
    }

    // status 1 = still generating; any other status: continue polling
  }

  console.warn("[veo-poll] timed out after", maxWaitMs / 1000, "s for uuid", uuid);
  return null; // timeout
}

// โ”€โ”€ Helper: parse error body โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function parseErrBody(text: string): { code: string; msg: string } {
  try {
    const d = JSON.parse(text) as { detail?: { error_code?: string; error_message?: string } };
    return {
      code: d?.detail?.error_code || "",
      msg: (d?.detail?.error_message || "").toLowerCase(),
    };
  } catch {
    return { code: "", msg: text.toLowerCase() };
  }
}

// โ”€โ”€ SSE stream reader โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
interface StreamResult {
  videoUrl: string | null;
  thumbnailUrl: string | null;
  uuid: string | null;
  lastEvent: unknown;
  errorCode: string | null;
  errorMsg: string | null;
}

/**
 * Resolve a potentially-relative video URL to an absolute URL.
 *
 * geminigen.ai's SSE stream returns a field like:
 *   "videoUrl": "users/{userId}/generated/{videoId}/gen_xxx.mp4?signed=..."
 * which needs to be prefixed with the R2 CDN base, or it may already be a
 * full https:// signed URL (if the JSON was not truncated in our logs).
 *
 * NOTE: confirmed from production logs โ€” video files are served from
 *   https://assets.grok.com/  NOT from https://api.geminigen.ai/
 */
const VIDEO_CDN_BASE = "https://assets.grok.com/";

function resolveVideoUrl(rawUrl: string): string {
  if (!rawUrl) return rawUrl;
  if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) return rawUrl;
  // Relative path โ†’ prepend CDN base
  return VIDEO_CDN_BASE + rawUrl;
}

/**
 * Extract the geminigen.ai streaming video generation response from a parsed
 * SSE event.  The structure (confirmed from production logs) is:
 *
 *   parsed.data.result.response.streamingVideoGenerationResponse
 *     .progress   : 0โ€“100
 *     .videoUrl   : relative or absolute URL (only when progress === 100)
 */
function extractSVGR(parsed: Record<string, unknown>): Record<string, unknown> | null {
  try {
    const data = parsed.data as Record<string, unknown> | undefined;
    const result = data?.result as Record<string, unknown> | undefined;
    const response = result?.response as Record<string, unknown> | undefined;
    const svgr = response?.streamingVideoGenerationResponse as Record<string, unknown> | undefined;
    return svgr ?? null;
  } catch {
    return null;
  }
}

async function readVideoStream(
  resp: Response,
  onEvent: (parsed: Record<string, unknown>) => void,
  maxWaitMs = 300_000,
): Promise<StreamResult> {
  const decoder = new TextDecoder();
  const reader = resp.body?.getReader();
  const empty: StreamResult = {
    videoUrl: null, thumbnailUrl: null, uuid: null, lastEvent: null, errorCode: null, errorMsg: null,
  };
  if (!reader) return empty;

  let videoUrl: string | null = null;
  let thumbnailUrl: string | null = null;
  let uuid: string | null = null;
  let lastEvent: unknown = null;
  let errorCode: string | null = null;
  let errorMsg: string | null = null;
  let buffer = "";
  let historyUuid: string | null = null;
  const deadline = Date.now() + maxWaitMs;

  try {
    while (Date.now() < deadline) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() ?? "";

      for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed || trimmed === "data: [DONE]") continue;

        const jsonStr = trimmed.startsWith("data:") ? trimmed.slice(5).trim() : trimmed;

        let parsed: Record<string, unknown>;
        try {
          parsed = JSON.parse(jsonStr);
        } catch {
          continue;
        }

        lastEvent = parsed;
        // Log full event (no truncation โ€” we need the complete video URL)
        console.log("[video-stream]", JSON.stringify(parsed));

        // โ”€โ”€ Error detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // Pattern A: {"detail":{"error_code":"..."}}
        const detail = parsed.detail as Record<string, string> | undefined;
        if (detail?.error_code) {
          errorCode = detail.error_code;
          errorMsg = detail.error_message || detail.error_code;
          console.error(`[video-stream] error: ${errorCode} โ€” ${errorMsg}`);
          return { videoUrl: null, thumbnailUrl: null, uuid, lastEvent, errorCode, errorMsg };
        }
        // Pattern B: top-level error_code
        if (typeof parsed.error_code === "string" && parsed.error_code) {
          errorCode = parsed.error_code;
          errorMsg = (parsed.error_message as string) || parsed.error_code;
          return { videoUrl: null, thumbnailUrl: null, uuid, lastEvent, errorCode, errorMsg };
        }
        // Pattern C: top-level error string (no status field)
        if (typeof parsed.error === "string" && parsed.error && typeof parsed.status === "undefined") {
          errorCode = "STREAM_ERROR";
          errorMsg = parsed.error;
          return { videoUrl: null, thumbnailUrl: null, uuid, lastEvent, errorCode, errorMsg };
        }

        // โ”€โ”€ Initial event: {"success":true,"message":"Video generation started",
        //                    "history_id":...,"history_uuid":"...","status":1} โ”€โ”€
        if (parsed.success === true && typeof parsed.history_uuid === "string") {
          historyUuid = parsed.history_uuid;
          uuid = historyUuid;
          if (parsed.message === "Video generation started") {
            onEvent({ type: "started", historyUuid });
            continue;
          }
        }

        // โ”€โ”€ Completion signal: {"success":true,"message":"Video generation complete..."} โ”€โ”€
        if (parsed.success === true && typeof parsed.message === "string"
            && parsed.message.includes("Video generation complete")) {
          console.log("[video-stream] generation complete signal received");
          return { videoUrl, thumbnailUrl, uuid, lastEvent, errorCode: null, errorMsg: null };
        }

        // โ”€โ”€ HD URL event: {"success":true,"data":{"video_id":"...","hdMediaUrl":"https://assets.grok.com/..."}} โ”€โ”€
        // Prefer this over the relative videoUrl from SVGR since it's already absolute and higher quality.
        {
          const d = parsed.data as Record<string, unknown> | undefined;
          if (d && typeof d.hdMediaUrl === "string" && d.hdMediaUrl.startsWith("https://")) {
            console.log("[video-url] using hdMediaUrl:", d.hdMediaUrl.slice(0, 120));
            videoUrl = d.hdMediaUrl;
          }
        }

        // โ”€โ”€ Progress events: data.result.response.streamingVideoGenerationResponse โ”€โ”€
        const svgr = extractSVGR(parsed);
        if (svgr) {
          const progress = typeof svgr.progress === "number" ? svgr.progress : null;
          const rawUrl = typeof svgr.videoUrl === "string" ? svgr.videoUrl : null;
          const videoId = typeof svgr.videoId === "string" ? svgr.videoId : undefined;

          if (rawUrl) {
            videoUrl = resolveVideoUrl(rawUrl);
            try {
              const u = new URL(videoUrl);
              console.log("[video-url] origin:", u.origin);
              console.log("[video-url] path:", u.pathname);
              const qs = u.search;
              for (let i = 0; i < qs.length; i += 200) {
                console.log("[video-url] qs[" + Math.floor(i / 200) + "]:", qs.slice(i, i + 200));
              }
              console.log("[video-url] total_length:", videoUrl.length, "| raw_length:", rawUrl.length);
            } catch {
              console.log("[video-url] raw (non-URL):", rawUrl.slice(0, 200));
            }
          }

          // Extract thumbnail URL (only present at progress=100)
          const rawThumb = typeof svgr.thumbnailImageUrl === "string" ? svgr.thumbnailImageUrl : null;
          if (rawThumb) thumbnailUrl = resolveVideoUrl(rawThumb);

          onEvent({ type: "progress", progress, videoId, videoUrl });

          if (progress === 100 && videoUrl) {
            console.log("[video-stream] progress=100, video ready");
            // Don't return yet โ€” wait for the "Video generation complete" signal
            // which ensures the backend has finished processing.
            // But if no more events come, videoUrl is set so we'll return at stream end.
          }
          continue;
        }

        // โ”€โ”€ Legacy format fallback โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        // In case geminigen.ai changes format back, still check old fields
        if (!uuid && typeof parsed.uuid === "string") uuid = parsed.uuid;
        const legacyCandidate =
          (parsed.video_url as string | undefined) ||
          (parsed.generated_video as Array<{ video_url?: string }> | undefined)?.[0]?.video_url ||
          null;
        if (legacyCandidate) videoUrl = resolveVideoUrl(legacyCandidate);

        if (typeof parsed.status === "number" && (parsed.status === 2 || parsed.status === 3)) {
          return { videoUrl, thumbnailUrl, uuid, lastEvent, errorCode: null, errorMsg: null };
        }
        if (typeof parsed.status === "number" && parsed.status > 3) {
          errorCode = "GEN_FAILED";
          errorMsg = (parsed.message as string) || `status=${parsed.status}`;
          return { videoUrl: null, thumbnailUrl: null, uuid, lastEvent, errorCode, errorMsg };
        }
      }
    }
  } finally {
    reader.cancel().catch(() => {});
  }

  // Stream ended naturally โ€” if we have a videoUrl it's a success
  return { videoUrl, thumbnailUrl, uuid, lastEvent, errorCode, errorMsg };
}

// โ”€โ”€ Shared token helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function makeTokenHelpers() {
  const failedPoolIds: number[] = [];
  let currentAccountId: number | null = null;

  async function pickToken(): Promise<string | null> {
    const poolEntry = await getPoolToken(failedPoolIds);
    if (poolEntry) { currentAccountId = poolEntry.accountId; return poolEntry.token; }
    currentAccountId = null;
    return getValidBearerToken();
  }

  async function handleTokenExpiry(): Promise<string | null> {
    if (currentAccountId !== null) {
      const refreshed = await tryRefreshPoolAccount(currentAccountId);
      if (refreshed) return refreshed;
      failedPoolIds.push(currentAccountId);
      const next = await getPoolToken(failedPoolIds);
      if (next) { currentAccountId = next.accountId; return next.token; }
    }
    return refreshAccessToken();
  }

  return { pickToken, handleTokenExpiry };
}

// โ”€โ”€ Grok-3 background task runner (SSE streaming) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async function runGrokTask(
  taskId: string,
  opts: VideoGenOptions,
  isPrivate: boolean,
  userId: number | null,
): Promise<void> {
  const task = tasks.get(taskId);
  if (!task) return;

  const { pickToken, handleTokenExpiry } = makeTokenHelpers();

  try {
    broadcast(task, { type: "start", message: "ๆญฃๅœจๅ–ๅพ— Turnstile ้ฉ—่ญ‰็ขผ..." });
    let turnstileToken = await getTurnstileToken();

    broadcast(task, { type: "start", message: "ๆญฃๅœจๅ–ๅพ— Bearer Token..." });
    let token = await pickToken();

    if (!token) {
      finishTask(task, "failed", { type: "error", errorCode: "NO_TOKEN", message: "ๆœช่จญๅฎš API Token๏ผŒ่ซ‹ๅˆฐ็ฎก็†ๅพŒๅฐ่จญๅฎš" });
      return;
    }

    broadcast(task, { type: "start", message: "ๆญฃๅœจ้€ฃๆŽฅ geminigen.ai (Grok-3)..." });

    let resp = await callGrokEndpoint(token, turnstileToken, opts);

    // โ”€โ”€ Handle HTTP-level errors โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (!resp.ok) {
      const rawText = await resp.text().catch(() => "");
      const { code, msg } = parseErrBody(rawText);

      const isCaptcha = msg.includes("captcha") || msg.includes("turnstile")
        || code === "CAPTCHA_ERROR" || code === "INVALID_CAPTCHA";

      if (isCaptcha) {
        broadcast(task, { type: "start", message: "Turnstile ๆ‹’็ต•๏ผŒๆญฃๅœจ้‡ๆ–ฐๅ–ๅพ—..." });
        invalidateTurnstileToken();
        turnstileToken = await getTurnstileToken();
        resp = await callGrokEndpoint(token, turnstileToken, opts);
      } else {
        const isExpired = resp.status === 401 || resp.status === 403
          || code === "TOKEN_EXPIRED" || code === "INVALID_CREDENTIALS"
          || msg.includes("token") || msg.includes("expired") || msg.includes("credential");
        if (isExpired) {
          broadcast(task, { type: "start", message: "Token ้ŽๆœŸ๏ผŒๆญฃๅœจๅˆทๆ–ฐ..." });
          const newToken = await handleTokenExpiry();
          if (!newToken) {
            finishTask(task, "failed", {
              type: "error", errorCode: "TOKEN_EXPIRED",
              message: "Token ๅทฒ้ŽๆœŸไธ”็„กๆณ•่‡ชๅ‹•ๅˆทๆ–ฐ๏ผŒ่ซ‹ๅˆฐ็ฎก็†ๅพŒๅฐๆ›ดๆ–ฐ Token",
            });
            return;
          }
          token = newToken;
          resp = await callGrokEndpoint(token, turnstileToken, opts);
        }
      }

      if (!resp.ok) {
        const raw2 = await resp.text().catch(() => "");
        const { code: c2, msg: m2 } = parseErrBody(raw2);
        finishTask(task, "failed", {
          type: "error",
          errorCode: c2 || "API_ERROR",
          message: m2 || `HTTP ${resp.status}`,
        });
        return;
      }
    }

    broadcast(task, { type: "start", message: "AI ๆญฃๅœจ็”Ÿๆˆๅฝฑ็‰‡๏ผŒ้€™ๅฏ่ƒฝ้œ€่ฆ 1โ€“5 ๅˆ†้˜..." });

    // โ”€โ”€ Read SSE stream โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    const makeProgressHandler = (label: string) => (parsed: Record<string, unknown>) => {
      // New format: { type: "progress", progress: 0-100 }
      if (parsed.type === "progress") {
        const pct = typeof parsed.progress === "number" ? parsed.progress : null;
        const pctStr = pct !== null ? ` (${pct}%)` : "";
        broadcast(task, { type: "progress", progress: pct, message: `${label}${pctStr}` });
      } else if (parsed.type === "started") {
        broadcast(task, { type: "progress", message: "AI ้–‹ๅง‹็”Ÿๆˆ..." });
      } else {
        // Legacy / fallback
        const u = typeof parsed.uuid === "string" ? parsed.uuid : undefined;
        broadcast(task, { type: "progress", uuid: u, message: label });
      }
    };

    let streamResult = await readVideoStream(resp, makeProgressHandler("AI ็”Ÿๆˆไธญ"));

    // โ”€โ”€ Retry logic for stream-level errors โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (!streamResult.videoUrl && streamResult.errorCode) {
      const ec = streamResult.errorCode;
      const em = (streamResult.errorMsg || "").toLowerCase();

      const isStreamCaptcha = ec === "CAPTCHA_ERROR" || ec === "INVALID_CAPTCHA"
        || em.includes("captcha") || em.includes("turnstile");

      const isStreamToken = ec === "TOKEN_EXPIRED" || ec === "INVALID_CREDENTIALS"
        || ec === "UNAUTHORIZED" || em.includes("token") || em.includes("expired")
        || em.includes("credentials") || em.includes("invalid credential");

      if (isStreamCaptcha) {
        broadcast(task, { type: "start", message: "Turnstile ๅœจไธฒๆตไธญๆ‹’็ต•๏ผŒ้‡ๆ–ฐๅ–ๅพ—ไธฆ้‡่ฉฆ..." });
        invalidateTurnstileToken();
        turnstileToken = await getTurnstileToken();
        const retryResp = await callGrokEndpoint(token, turnstileToken, opts);
        if (retryResp.ok) {
          streamResult = await readVideoStream(retryResp, makeProgressHandler("AI ็”Ÿๆˆไธญ๏ผˆ้‡่ฉฆ๏ผ‰"));
        }
      } else if (isStreamToken) {
        broadcast(task, { type: "start", message: `Token ้Œฏ่ชค (${ec})๏ผŒ้‡ๆ–ฐๅˆทๆ–ฐไธฆ้‡่ฉฆ...` });
        const newToken = await handleTokenExpiry();
        if (!newToken) {
          finishTask(task, "failed", {
            type: "error", errorCode: "TOKEN_EXPIRED",
            message: "Token ๅทฒ้ŽๆœŸไธ”็„กๆณ•่‡ชๅ‹•ๅˆทๆ–ฐ๏ผŒ่ซ‹ๅˆฐ็ฎก็†ๅพŒๅฐๆ›ดๆ–ฐ Token",
          });
          return;
        }
        token = newToken;
        const retryResp = await callGrokEndpoint(token, turnstileToken, opts);
        if (retryResp.ok) {
          streamResult = await readVideoStream(retryResp, makeProgressHandler("AI ็”Ÿๆˆไธญ๏ผˆ้‡่ฉฆ๏ผ‰"));
        }
      }
    }

    let { videoUrl, thumbnailUrl, uuid, errorCode: finalCode, errorMsg: finalMsg } = streamResult;

    if (!videoUrl && !uuid) {
      const msg = finalMsg ? `็”Ÿๆˆๅคฑๆ•—๏ผš${finalMsg}` : "ๆœชๅ–ๅพ—ๅฝฑ็‰‡ URL๏ผŒ็”Ÿๆˆๅฏ่ƒฝๅทฒๅคฑๆ•—ๆˆ–่ถ…ๆ™‚";
      finishTask(task, "failed", { type: "error", errorCode: finalCode || "NO_VIDEO", message: msg });
      return;
    }

    // โ”€โ”€ Step 2: Fetch R2 pre-signed URL from history API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    // The SSE stream gives us an assets.grok.com URL (requires auth + Cloudflare cookies).
    // The history API returns a Cloudflare R2 pre-signed URL (7-day, publicly accessible).
    // Always try to get the R2 URL regardless of whether SSE already gave us a URL.
    if (uuid) {
      broadcast(task, { type: "progress", progress: 100, message: "ๆญฃๅœจๅ–ๅพ—ๅฝฑ็‰‡ไธ‹่ผ‰้€ฃ็ต..." });
      const historyResult = await fetchHistoryVideoUrl(uuid, token);
      if (historyResult?.videoUrl) {
        videoUrl = historyResult.videoUrl;
        if (historyResult.thumbnailUrl) thumbnailUrl = historyResult.thumbnailUrl;
        console.log("[grok-task] using R2 URL from history API");
      }
    }

    if (!videoUrl) {
      const msg = finalMsg ? `็”Ÿๆˆๅคฑๆ•—๏ผš${finalMsg}` : "ๆœชๅ–ๅพ—ๅฝฑ็‰‡ URL๏ผŒ็”Ÿๆˆๅฏ่ƒฝๅทฒๅคฑๆ•—ๆˆ–่ถ…ๆ™‚";
      finishTask(task, "failed", { type: "error", errorCode: finalCode || "NO_VIDEO", message: msg });
      return;
    }

    // Store the URL (R2 pre-signed if available, falls back to assets.grok.com).
    const [saved] = await db
      .insert(videosTable)
      .values({
        videoUrl,
        thumbnailUrl: thumbnailUrl ?? null,
        prompt: opts.prompt,
        negativePrompt: opts.negativePrompt ?? null,
        model: opts.model,
        aspectRatio: opts.aspectRatio,
        resolution: opts.resolution,
        duration: opts.duration,
        hasRefImage: !!(opts.refImageBase64 && opts.refImageMime),
        isPrivate,
        userId,
      })
      .returning();

    finishTask(task, "complete", { type: "complete", video: saved, uuid: uuid ?? undefined });

    // โ”€โ”€ Background: download video to S3 for permanent storage โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    // R2 pre-signed URLs expire in 7 days; S3 copy is permanent.
    if (isStorageReady()) {
      (async () => {
        try {
          const storedPath = await downloadAndStoreVideo(videoUrl!, token);
          if (storedPath) {
            await db.update(videosTable).set({ videoUrl: storedPath }).where(eq(videosTable.id, saved.id));
            console.log(`[grok-task] video cached in storage: ${storedPath}`);
          }
        } catch (e) {
          console.warn("[grok-task] background storage failed:", e instanceof Error ? e.message : e);
        }
      })();
    }
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[grok-task] unexpected error:", msg);
    finishTask(task, "failed", { type: "error", errorCode: "INTERNAL_ERROR", message: msg });
  }
}

// โ”€โ”€ Veo 3.1 Fast background task runner (POST + polling) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async function runVeoTask(
  taskId: string,
  opts: VideoGenOptions,
  isPrivate: boolean,
  userId: number | null,
): Promise<void> {
  const task = tasks.get(taskId);
  if (!task) return;

  const { pickToken, handleTokenExpiry } = makeTokenHelpers();

  try {
    broadcast(task, { type: "start", message: "ๆญฃๅœจๅ–ๅพ— Turnstile ้ฉ—่ญ‰็ขผ..." });
    let turnstileToken = await getTurnstileToken();

    broadcast(task, { type: "start", message: "ๆญฃๅœจๅ–ๅพ— Bearer Token..." });
    let token = await pickToken();

    if (!token) {
      finishTask(task, "failed", { type: "error", errorCode: "NO_TOKEN", message: "ๆœช่จญๅฎš API Token๏ผŒ่ซ‹ๅˆฐ็ฎก็†ๅพŒๅฐ่จญๅฎš" });
      return;
    }

    broadcast(task, { type: "start", message: "ๆญฃๅœจๆไบค Veo 3.1 Fast ไปปๅ‹™..." });

    // Submit to Veo endpoint (returns UUID immediately)
    let veoResult: { uuid: string };
    try {
      veoResult = await callVeoEndpoint(token, turnstileToken, opts);
    } catch (err: unknown) {
      const e = err as Error & { code?: string; status?: number };
      const code = e.code ?? "";
      const msg = (e.message ?? "").toLowerCase();

      const isCaptcha = msg.includes("captcha") || msg.includes("turnstile")
        || code === "CAPTCHA_ERROR" || code === "INVALID_CAPTCHA";
      const isExpired = e.status === 401 || e.status === 403
        || code === "TOKEN_EXPIRED" || msg.includes("token") || msg.includes("expired");

      if (isCaptcha) {
        broadcast(task, { type: "start", message: "Turnstile ๆ‹’็ต•๏ผŒ้‡ๆ–ฐๅ–ๅพ—ไธฆ้‡่ฉฆ..." });
        invalidateTurnstileToken();
        turnstileToken = await getTurnstileToken();
        veoResult = await callVeoEndpoint(token, turnstileToken, opts);
      } else if (isExpired) {
        broadcast(task, { type: "start", message: "Token ้ŽๆœŸ๏ผŒๆญฃๅœจๅˆทๆ–ฐ..." });
        const newToken = await handleTokenExpiry();
        if (!newToken) {
          finishTask(task, "failed", { type: "error", errorCode: "TOKEN_EXPIRED", message: "Token ้ŽๆœŸไธ”็„กๆณ•่‡ชๅ‹•ๅˆทๆ–ฐ๏ผŒ่ซ‹ๅˆฐ็ฎก็†ๅพŒๅฐๆ›ดๆ–ฐ Token" });
          return;
        }
        token = newToken;
        veoResult = await callVeoEndpoint(token, turnstileToken, opts);
      } else {
        throw err;
      }
    }

    const { uuid } = veoResult;
    broadcast(task, {
      type: "progress",
      progress: 5,
      message: `Veo ไปปๅ‹™ๅทฒๆไบค (UUID: ${uuid.slice(0, 8)}...)๏ผŒ็ญ‰ๅพ…็”Ÿๆˆ๏ผˆๆฏ 30 ็ง’็ขบ่ชไธ€ๆฌก๏ผ‰...`,
    });

    // Poll until done (max 5 minutes, every 30s)
    const pollResult = await pollVeoHistory(
      uuid,
      token,
      (msg) => broadcast(task, { type: "progress", progress: null, message: msg }),
    );

    if (!pollResult || !pollResult.videoUrl) {
      finishTask(task, "failed", { type: "error", errorCode: "NO_VIDEO", message: "Veo ๆœช่ฟ”ๅ›žๅฝฑ็‰‡ URL๏ผŒๅฏ่ƒฝ็”Ÿๆˆๅคฑๆ•—ๆˆ–่ถ…ๆ™‚" });
      return;
    }

    const { videoUrl, thumbnailUrl } = pollResult;

    const absVideoUrl = resolveVideoUrl(videoUrl);
    const absThumbUrl = thumbnailUrl ? resolveVideoUrl(thumbnailUrl) : null;

    // Store raw CDN URL immediately; background GCS download follows.
    const [saved] = await db
      .insert(videosTable)
      .values({
        videoUrl: absVideoUrl,
        thumbnailUrl: absThumbUrl ?? null,
        prompt: opts.prompt,
        negativePrompt: opts.negativePrompt ?? null,
        model: opts.model,
        aspectRatio: opts.aspectRatio,
        resolution: opts.resolution,
        duration: opts.duration,
        hasRefImage: !!(opts.refImageBase64 && opts.refImageMime),
        isPrivate,
        userId,
      })
      .returning();

    finishTask(task, "complete", { type: "complete", video: saved, uuid });

    // โ”€โ”€ Background: download video to GCS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (isStorageReady()) {
      (async () => {
        try {
          const storedPath = await downloadAndStoreVideo(absVideoUrl, token);
          if (storedPath) {
            await db.update(videosTable).set({ videoUrl: storedPath }).where(eq(videosTable.id, saved.id));
            console.log(`[veo-task] video cached in storage: ${storedPath}`);
          }
        } catch (e) {
          console.warn("[veo-task] background storage failed:", e instanceof Error ? e.message : e);
        }
      })();
    }
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[veo-task] unexpected error:", msg);
    finishTask(task, "failed", { type: "error", errorCode: "INTERNAL_ERROR", message: msg });
  }
}

// โ”€โ”€ Credit helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async function getVideoConfigVal(key: string): Promise<string | null> {
  const rows = await db.select({ value: configTable.value }).from(configTable).where(eq(configTable.key, key)).limit(1);
  return rows[0]?.value ?? null;
}

async function checkAndDeductVideoCredits(userId: number, cost: number, description: string): Promise<{ ok: boolean; balance?: number }> {
  const enabled = await getVideoConfigVal("enable_credits");
  if (enabled !== "true") return { ok: true };

  const [user] = await db.select({ credits: usersTable.credits }).from(usersTable).where(eq(usersTable.id, userId)).limit(1);
  if (!user) return { ok: false };
  if (user.credits < cost) return { ok: false, balance: user.credits };

  const [updated] = await db
    .update(usersTable)
    .set({ credits: sql`${usersTable.credits} - ${cost}` })
    .where(eq(usersTable.id, userId))
    .returning({ credits: usersTable.credits });

  await db.insert(creditTransactionsTable).values({ userId, amount: -cost, type: "spend", description });
  return { ok: true, balance: updated.credits };
}

// โ”€โ”€ POST /api/videos/generate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Returns taskId immediately; generation runs in background.
router.post("/generate", optionalJwtAuth, async (req, res) => {
  const body = req.body as Record<string, unknown>;

  const prompt = typeof body.prompt === "string" ? body.prompt.trim() : "";
  if (!prompt || prompt.length < 1 || prompt.length > 2000) {
    return res.status(400).json({ error: "INVALID_BODY", message: "prompt is required (1-2000 chars)" });
  }
  const isPrivate = body.isPrivate === true;

  // Parse video options (aspectRatio, resolution, duration, negativePrompt, enhancePrompt)
  const opts = parseVideoOptions(body, prompt);

  // Attach reference image if provided
  const refImageBase64 = typeof body.referenceImageBase64 === "string" ? body.referenceImageBase64 : undefined;
  const refImageMime = typeof body.referenceImageMime === "string" ? body.referenceImageMime : undefined;
  if (refImageBase64 && refImageMime) {
    opts.refImageBase64 = refImageBase64;
    opts.refImageMime = refImageMime;
  }

  const userId: number | null = (req as any).jwtUserId ?? null;

  // โ”€โ”€ Credits check โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  if (userId !== null) {
    const costStr = await getVideoConfigVal("video_gen_cost");
    const cost = Number(costStr) || 0;
    if (cost > 0) {
      const creditResult = await checkAndDeductVideoCredits(userId, cost, `ๅฝฑ็‰‡็”Ÿๆˆ๏ผˆ${opts.model}๏ผ‰`);
      if (!creditResult.ok) {
        return res.status(402).json({
          error: "INSUFFICIENT_CREDITS",
          message: `้ปžๆ•ธไธ่ถณ๏ผŒๆญคๆ“ไฝœ้œ€่ฆ ${cost} ้ปž`,
          balance: creditResult.balance ?? 0,
        });
      }
    }
  }

  const taskId = createTask();
  res.json({ taskId });

  // Dispatch to the correct runner based on model
  const runner = opts.model === "veo-3-fast" ? runVeoTask : runGrokTask;
  runner(taskId, opts, isPrivate, userId).catch((err) => {
    console.error("[video-task] uncaught:", err);
    const t = tasks.get(taskId);
    if (t && t.status === "pending") {
      finishTask(t, "failed", { type: "error", errorCode: "INTERNAL_ERROR", message: String(err) });
    }
  });
});

// โ”€โ”€ GET /api/videos/progress/:taskId  (SSE) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
router.get("/progress/:taskId", (req, res: ExpressResponse) => {
  const task = tasks.get(req.params.taskId);
  if (!task) return res.status(404).json({ error: "TASK_NOT_FOUND" });

  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
    "X-Accel-Buffering": "no",
  });
  res.flushHeaders();

  const send = (event: ProgressEvent) => {
    res.write(`data: ${JSON.stringify(event)}\n\n`);
  };

  // Replay buffered events
  for (const ev of task.buffered) {
    send(ev);
  }

  // If already done, close immediately
  if (task.status !== "pending") {
    res.write("data: {\"type\":\"done\"}\n\n");
    res.end();
    return;
  }

  // Subscribe to future events
  task.clients.add(send);

  // Heartbeat every 20s to prevent proxy / CDN from closing idle SSE connections
  const heartbeat = setInterval(() => {
    try { res.write(": heartbeat\n\n"); } catch { clearInterval(heartbeat); }
  }, 20_000);

  const onClose = () => {
    clearInterval(heartbeat);
    task.clients.delete(send);
  };
  req.on("close", onClose);
  req.on("end", onClose);
});

// Helper: rewrite raw geminigen URLs to proxy URL for backward compatibility.
// assets.grok.com URLs are returned as-is (browser plays directly).
// /api/videos/stored/ URLs are returned as-is (GCS).
function toProxyUrl(url: string | null): string | null {
  if (!url) return null;
  if (url.startsWith("/api/videos/proxy")) return url;
  if (url.startsWith("/api/videos/stored")) return url;
  try {
    const u = new URL(url);
    // Cloudflare R2 pre-signed URLs (*.r2.cloudflarestorage.com) are publicly
    // accessible โ€” no proxy needed.  Browser plays them directly.
    if (u.hostname.endsWith(".r2.cloudflarestorage.com")) return url;
    // assets.grok.com requires auth/cookies โ€” route through our proxy.
    if (u.hostname === "api.geminigen.ai" || u.hostname === "assets.grok.com") {
      return `/api/videos/proxy?url=${encodeURIComponent(url)}`;
    }
  } catch { /* relative path or non-URL */ }
  return url;
}

// โ”€โ”€ GET /api/videos/stored/<id>.mp4 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Serve videos that were downloaded from CDN and stored in GCS.
router.get(/^\/stored\/(.+)$/, async (req, res) => {
  const objectPath = (req.params as Record<string, string>)[0];
  if (!objectPath) return res.status(400).json({ error: "Missing objectPath" });
  await streamStoredVideo(objectPath, res, req.headers.range);
});

// โ”€โ”€ GET /api/videos/history โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
router.get("/history", optionalJwtAuth, async (req, res) => {
  const userId: number | null = (req as any).jwtUserId ?? null;
  const limit = Math.min(Number(req.query.limit) || 20, 50);
  const offset = Number(req.query.offset) || 0;

  const visibilityFilter = userId
    ? or(eq(videosTable.isPrivate, false), and(eq(videosTable.isPrivate, true), eq(videosTable.userId, userId)))
    : eq(videosTable.isPrivate, false);

  const rows = await db
    .select()
    .from(videosTable)
    .where(visibilityFilter)
    .orderBy(desc(videosTable.createdAt))
    .limit(limit)
    .offset(offset);

  // Rewrite any legacy direct geminigen URLs to proxy URLs
  const videos = rows.map((v) => ({
    ...v,
    videoUrl: toProxyUrl(v.videoUrl) ?? v.videoUrl,
    thumbnailUrl: toProxyUrl(v.thumbnailUrl),
  }));

  return res.json({ videos, limit, offset });
});

// โ”€โ”€ GET /api/videos/proxy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Proxy geminigen.ai video/thumbnail files with Bearer token auth.
// Supports HTTP Range requests so the browser's <video> player can seek.
router.get("/proxy", async (req, res) => {
  const raw = typeof req.query.url === "string" ? req.query.url : "";
  if (!raw) return res.status(400).json({ error: "Missing url param" });

  // Only proxy geminigen.ai and Grok CDN assets
  let targetUrl: URL;
  try {
    targetUrl = new URL(raw);
  } catch {
    return res.status(400).json({ error: "Invalid url" });
  }
  const ALLOWED_PROXY_HOSTS = ["api.geminigen.ai", "assets.grok.com"];
  if (!ALLOWED_PROXY_HOSTS.includes(targetUrl.hostname)) {
    return res.status(403).json({ error: "URL not allowed" });
  }

  // Forward Range header if present (needed for video seeking)
  const rangeHeader = req.headers.range;

  /**
   * assets.grok.com is the Grok CDN.  It appears to be a public CDN that does
   * NOT accept the geminigen.ai JWT as auth (returns 403 if you send it).
   * Strategy: try first WITHOUT Authorization, fall back to with-token if needed.
   *
   * api.geminigen.ai requires Bearer auth as before.
   */
  const isGrokCdn = targetUrl.hostname === "assets.grok.com";

  // For assets.grok.com, use Referer=https://grok.com/ (same origin as the CDN).
  // For geminigen.ai, use Referer=https://geminigen.ai/.
  const referer = isGrokCdn ? "https://grok.com/" : "https://geminigen.ai/";

  const buildHeaders = (token?: string | null): Record<string, string> => {
    const h: Record<string, string> = {
      "User-Agent": USER_AGENT,
      Accept: "video/mp4,video/*,*/*",
      Referer: referer,
      Origin: isGrokCdn ? "https://grok.com" : "https://geminigen.ai",
    };
    if (rangeHeader) h["Range"] = rangeHeader;
    if (token) h["Authorization"] = `Bearer ${token}`;
    return h;
  };

  try {
    // Always fetch the Bearer token (needed for both geminigen.ai and assets.grok.com)
    const poolResult = await getPoolToken();
    const bearerToken = poolResult?.token ?? await getValidBearerToken();

    // 1. First attempt: with Bearer token for both endpoints
    let upstream = await fetch(targetUrl.toString(), {
      headers: buildHeaders(bearerToken),
    });

    // 2. If first attempt fails, try without auth (in case token is wrong for CDN)
    if (!upstream.ok && upstream.status !== 206) {
      console.warn(`[video-proxy] first attempt ${upstream.status} for ${targetUrl.hostname}${targetUrl.pathname}`);

      if (isGrokCdn) {
        // Try without auth as fallback
        upstream = await fetch(targetUrl.toString(), { headers: buildHeaders(null) });

        if (!upstream.ok && upstream.status !== 206) {
          // Refresh token and try again
          const newToken = await refreshAccessToken();
          if (newToken) {
            upstream = await fetch(targetUrl.toString(), { headers: buildHeaders(newToken) });
          }
        }
      } else {
        // geminigen.ai rejected token โ€” refresh and retry
        if (!bearerToken) {
          console.error("[video-proxy] no token available");
          return res.status(502).json({ error: "No bearer token available for proxy" });
        }
        if ((upstream.status === 401 || upstream.status === 403)) {
          console.warn(`[video-proxy] refreshing token after ${upstream.status}...`);
          const newToken = await refreshAccessToken();
          if (newToken) {
            upstream = await fetch(targetUrl.toString(), { headers: buildHeaders(newToken) });
          }
        }
      }
    }

    console.log(`[video-proxy] final status ${upstream.status} for ${targetUrl.hostname}${targetUrl.pathname}`);

    if (!upstream.ok && upstream.status !== 206) {
      console.error(`[video-proxy] upstream ${upstream.status} for ${targetUrl.pathname}`);
      return res.status(upstream.status).json({ error: "Upstream error", status: upstream.status });
    }

    // Forward response headers
    const ct = upstream.headers.get("content-type");
    const cl = upstream.headers.get("content-length");
    const cr = upstream.headers.get("content-range");
    const ac = upstream.headers.get("accept-ranges");

    if (ct) res.setHeader("Content-Type", ct);
    if (cl) res.setHeader("Content-Length", cl);
    if (cr) res.setHeader("Content-Range", cr);
    if (ac) res.setHeader("Accept-Ranges", ac);
    else res.setHeader("Accept-Ranges", "bytes");

    // Cache for 1 hour (videos don't change)
    res.setHeader("Cache-Control", "public, max-age=3600");

    res.status(upstream.status);

    if (!upstream.body) {
      return res.end();
    }

    // Stream the body
    const reader = upstream.body.getReader();
    const pump = async () => {
      const { done, value } = await reader.read();
      if (done) { res.end(); return; }
      if (!res.write(value)) {
        // Backpressure: wait for drain
        await new Promise<void>((r) => res.once("drain", r));
      }
      await pump();
    };

    req.on("close", () => reader.cancel().catch(() => {}));
    await pump();
  } catch (err) {
    console.error("[video-proxy] fetch error:", err);
    if (!res.headersSent) res.status(502).json({ error: "Proxy fetch failed" });
  }
});

// โ”€โ”€ DELETE /api/videos/:id โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
router.delete("/:id", optionalJwtAuth, async (req, res) => {
  const id = Number(req.params.id);
  if (isNaN(id)) return res.status(400).json({ error: "INVALID_ID" });

  const userId: number | null = (req as any).jwtUserId ?? null;
  const rows = await db.select().from(videosTable).where(eq(videosTable.id, id)).limit(1);
  if (!rows.length) return res.status(404).json({ error: "NOT_FOUND" });

  const video = rows[0];
  if (video.userId !== null && video.userId !== userId) {
    return res.status(403).json({ error: "FORBIDDEN" });
  }

  await db.delete(videosTable).where(eq(videosTable.id, id));
  return res.json({ success: true });
});

export default router;