File size: 42,132 Bytes
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a9c61f
 
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a9c61f
 
 
 
 
 
 
 
8529108
5a9c61f
 
 
 
 
 
 
 
 
 
 
 
 
 
8529108
 
 
 
 
 
b3e3ac7
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
5a9c61f
 
8529108
5a9c61f
 
 
 
 
8529108
 
 
5a9c61f
 
 
 
 
 
 
 
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8998571
 
 
 
 
 
 
 
 
 
8529108
 
 
 
 
 
 
8998571
 
 
 
 
8529108
 
8998571
8529108
8998571
8529108
 
8998571
8529108
 
 
 
8998571
8529108
 
 
 
8998571
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62d6ea5
 
 
 
 
 
 
 
 
 
8529108
 
62d6ea5
8529108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * ArchNemix Shorts Generator API - Node.js v5.1.0
 * ════════════════════════════════════════════════════════════════════════════
 * Exact mirror of Python FFmpeg backend (ffmpeg_main.py v5.1.0)
 * Uses native FFmpeg CLI tool via child_process.spawn
 * Endpoints, request/response formats, and video cleanup match Python version
 */

const express = require('express');
const cors = require('cors');
const crypto = require('crypto');
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const { v4: uuidv4 } = require('uuid');

// =============================================================================
// CONFIG
// =============================================================================
const HF_DATASET = process.env.HF_DATASET || 'YTShortMakerArchx/BG_VIDS_ARCHX_YT';
const HF_TOKEN = process.env.HF_TOKEN;
const APP_KEY = process.env.APP_KEY;
const UI_ORIGIN = process.env.UI_ORIGIN || 'https://shortgenx.pages.dev';
const PORT = process.env.PORT || 7860;

const BASE_DIR = '/tmp';
const AUDIO_DIR = path.join(BASE_DIR, 'audio');
const OUTPUT_DIR = path.join(BASE_DIR, 'out');
const JOBS_DIR = path.join(BASE_DIR, 'jobs');
const CLIENT_DIR = path.join(BASE_DIR, 'clients');
const HF_CACHE_DIR = '/tmp/hf_cache';

// Create directories
for (const dir of [AUDIO_DIR, OUTPUT_DIR, JOBS_DIR, CLIENT_DIR, HF_CACHE_DIR]) {
    if (!fsSync.existsSync(dir)) {
        fsSync.mkdirSync(dir, { recursive: true });
    }
}

// Rate limiting
const RATE_LIMITS = new Map();
const GENERATE_LIMIT = 3;    // per hour per client
const STATUS_LIMIT = 1000;   // per hour per job

// Job timeout
const JOBS = new Map();
const JOB_TIMEOUT = 900;     // 15 min hard cap

// Video listing cache
const VIDEO_CACHE = new Map();
const CACHE_TIMEOUT = 300;   // 5 minutes

// =============================================================================
// QUEUE SYSTEM
// =============================================================================
const MAX_CONCURRENT = 1;
const AVG_JOB_DURATION_S = 360;   // 6 minutes per job

const JOB_QUEUE = [];
const RUNNING_JOBS = new Set();

// =============================================================================
// CLIENT ID SYSTEM
// =============================================================================
const CLIENT_TOKENS = new Map();

function clientFile(token) {
    return path.join(CLIENT_DIR, `${token.slice(0, 8)}.json`);
}

function loadClient(token) {
    if (CLIENT_TOKENS.has(token)) {
        return CLIENT_TOKENS.get(token);
    }
    const filePath = clientFile(token);
    if (fsSync.existsSync(filePath)) {
        try {
            const data = JSON.parse(fsSync.readFileSync(filePath, 'utf8'));
            data.created_at = new Date(data.created_at);
            data.last_seen = new Date(data.last_seen);
            CLIENT_TOKENS.set(token, data);
            return data;
        } catch (e) {
            // ignore
        }
    }
    return null;
}

function saveClient(rec) {
    const token = rec.token;
    CLIENT_TOKENS.set(token, rec);
    try {
        const recCopy = {
            ...rec,
            created_at: rec.created_at.toISOString(),
            last_seen: rec.last_seen.toISOString(),
        };
        fsSync.writeFileSync(clientFile(token), JSON.stringify(recCopy));
    } catch (e) {
        console.warn(`Failed to persist client ${token.slice(0, 8)}: ${e.message}`);
    }
}

function createClient(fingerprint) {
    const rec = {
        token: crypto.randomBytes(24).toString('hex'),
        fingerprint,
        created_at: new Date(),
        last_seen: new Date(),
        job_count: 0,
        jobs: [],
    };
    saveClient(rec);
    console.log(`New client ${rec.token.slice(0, 8)}...`);
    return rec;
}

function fingerprint(req) {
    const data = `${req.ip}:${req.get('user-agent') || ''}:${req.get('accept') || ''}`;
    return crypto.createHash('sha256').update(data).digest('hex');
}

function resolveClient(req) {
    let token = (req.get('X-Client-ID') || '').trim();

    if (token) {
        let rec = loadClient(token);
        if (rec) {
            rec.last_seen = new Date();
            saveClient(rec);
            return rec;
        }
        const fp = fingerprint(req);
        rec = {
            token,
            fingerprint: fp,
            created_at: new Date(),
            last_seen: new Date(),
            job_count: 0,
            jobs: [],
        };
        saveClient(rec);
        console.log(`Restored client ${token.slice(0, 8)}... from header`);
        return rec;
    }

    const fp = fingerprint(req);
    for (const rec of CLIENT_TOKENS.values()) {
        if (rec.fingerprint === fp) {
            rec.last_seen = new Date();
            saveClient(rec);
            return rec;
        }
    }

    return createClient(fp);
}

// =============================================================================
// EXPRESS APP
// =============================================================================
const app = express();

// Allowed origins - strict list
const ALLOWED_ORIGINS = [
    'https://shortgenx.pages.dev',                                           // Your frontend
    'https://ytshortmakerarchx-archnemix-controller.hf.space',              // Your controller space
    'http://localhost:3000',                                                 // Local development ONLY port 3000
    'http://127.0.0.1:3000',                                                // Local development ONLY port 3000
];

app.use(cors({
    origin: (origin, callback) => {
        // Allow requests with no origin (like server-to-server)
        if (!origin) {
            return callback(null, true);
        }
        
        // Check if origin is allowed
        if (ALLOWED_ORIGINS.indexOf(origin) !== -1) {
            return callback(null, true);
        }
        
        console.warn(`[CORS] Rejected origin: ${origin}`);
        callback(new Error(`Origin ${origin} not allowed by CORS`));
    },
    credentials: true,
    methods: ['GET', 'POST', 'DELETE', 'OPTIONS', 'HEAD'],
    allowedHeaders: ['*'],
    exposedHeaders: ['X-Client-ID'],
    maxAge: 600,
}));
app.use(express.json({ limit: '50mb' }));

// =============================================================================
// SECURITY
// =============================================================================
function validateAppKey(req) {
    if (!APP_KEY || APP_KEY === 'archnemix-secret-key-change-in-production') {
        return true;
    }
    const key = req.get('X-APP-KEY') || req.get('Authorization')?.replace('Bearer ', '') || '';
    return key === APP_KEY;
}

function validateOrigin(req) {
    const origin = req.get('origin') || req.get('referer') || '';
    
    // Allow requests with no origin (server-to-server)
    if (!origin) return true;
    
    // Strict allowed origins (exact match only)
    const ALLOWED_ORIGINS_EXACT = [
        'https://shortgenx.pages.dev',
        'https://ytshortmakerarchx-archnemix-controller.hf.space',
        'http://localhost:3000',
        'http://127.0.0.1:3000',
    ];
    
    // Exact match check
    if (ALLOWED_ORIGINS_EXACT.includes(origin)) {
        return true;
    }
    
    console.warn(`[SECURITY] Rejected request from origin: ${origin}`);
    return false;
}

function rateLimit(key, limit, window = 3600) {
    const now = Date.now() / 1000;
    if (!RATE_LIMITS.has(key)) {
        RATE_LIMITS.set(key, []);
    }
    const timestamps = RATE_LIMITS.get(key).filter(t => now - t < window);
    RATE_LIMITS.set(key, timestamps);
    
    if (timestamps.length >= limit) {
        return false;
    }
    timestamps.push(now);
    return true;
}

// =============================================================================
// HUGGINGFACE HELPERS
// =============================================================================
async function listVideosFromDataset(category = 'minecraft') {
    // Map category aliases to dataset folder names
    const categoryMap = {
        'minecraft': 'minecraft',
        'subwaysurfers': 'subwaysurfers',
        'ss': 'subwaysurfers'
    };
    
    const datasetCategory = categoryMap[category] || category;
    
    const cacheKey = `videos_${datasetCategory}`;
    if (VIDEO_CACHE.has(cacheKey)) {
        const { ts, data } = VIDEO_CACHE.get(cacheKey);
        if (Date.now() / 1000 - ts < CACHE_TIMEOUT) {
            return data;
        }
    }

    // Default fallback based on category
    const defaults = datasetCategory === 'subwaysurfers' 
        ? ['ss1', 'ss2', 'ss3', 'ss4', 'ss5']  // 5 videos
        : Array.from({ length: 6 }, (_, i) => `mc${i + 1}`);

    try {
        const fetch = (await import('node-fetch')).default;
        const url = `https://huggingface.co/api/datasets/${HF_DATASET}/tree/main/${datasetCategory}`;
        const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {};

        const response = await fetch(url, { headers });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);

        const files = await response.json();
        const result = files
            .filter(f => f.type === 'file' && f.path.endsWith('.mp4'))
            .map(f => path.basename(f.path, '.mp4'));

        VIDEO_CACHE.set(cacheKey, { ts: Date.now() / 1000, data: result });
        return result;
    } catch (e) {
        console.error(`list_videos failed: ${e.message}`);
        return defaults;
    }
}

async function downloadVideoFromDataset(videoName, category = 'minecraft') {
    videoName = videoName.replace('.mp4', '');
    const paths = [`${category}/${videoName}.mp4`, `${videoName}.mp4`];

    for (const filePath of paths) {
        try {
            const url = `https://huggingface.co/datasets/${HF_DATASET}/resolve/main/${filePath}`;
            const localPath = path.join(HF_CACHE_DIR, `${videoName}.mp4`);
            
            // Check if already cached
            if (fsSync.existsSync(localPath)) {
                return localPath;
            }

            const fetch = (await import('node-fetch')).default;
            const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {};
            const response = await fetch(url, { headers });
            
            if (response.ok) {
                const buffer = await response.buffer();
                await fs.writeFile(localPath, buffer);
                return localPath;
            }
        } catch (e) {
            continue;
        }
    }

    const available = await listVideosFromDataset(category);
    throw new Error(`Video '${videoName}' not found. Available: ${available.join(', ')}`);
}

// =============================================================================
// FILE HELPERS
// =============================================================================
async function saveBase64Audio(data, filePath) {
    if (data.startsWith('data:audio/')) {
        data = data.split(',')[1];
    }
    const audioBuffer = Buffer.from(data, 'base64');
    if (audioBuffer.length > 15 * 1024 * 1024) {
        throw new Error('Audio too large (max 15 MB)');
    }
    await fs.writeFile(filePath, audioBuffer);
    return audioBuffer.length;
}

async function saveSubtitles(ass, filePath) {
    if (!ass.includes('[Script Info]') || !ass.includes('[Events]')) {
        throw new Error('Invalid ASS subtitle format');
    }
    if (Buffer.byteLength(ass) > 500 * 1024) {
        throw new Error('Subtitles too large (max 500 KB)');
    }
    await fs.writeFile(filePath, ass, 'utf8');
}

function getMediaDuration(filePath) {
    return new Promise((resolve) => {
        const proc = spawn('ffprobe', [
            '-v', 'error',
            '-show_entries', 'format=duration',
            '-of', 'default=noprint_wrappers=1:nokey=1',
            filePath,
        ]);

        let output = '';
        proc.stdout.on('data', data => output += data.toString());
        
        proc.on('close', (code) => {
            if (code === 0 && output.trim()) {
                resolve(parseFloat(output.trim()));
            } else {
                // Fallback estimate
                try {
                    const size = fsSync.statSync(filePath).size;
                    resolve(Math.max(1.0, Math.min(180.0, size / 16000)));
                } catch {
                    resolve(30.0);
                }
            }
        });

        setTimeout(() => {
            proc.kill();
            resolve(30.0);
        }, 10000);
    });
}

// =============================================================================
// JOB MANAGEMENT
// =============================================================================
function makeJob(jobId, clientToken) {
    return {
        id: jobId,
        client_token: clientToken,
        status: 'queued',
        queue_position: null,
        progress: 0,
        message: 'Waiting in queue...',
        created_at: new Date(),
        updated_at: new Date(),
        error: null,
        output_path: null,
        audio_path: null,
        subs_path: null,
        ffmpeg_frame: 0,
        ffmpeg_fps: 0.0,
        ffmpeg_out_time: 0.0,
        ffmpeg_speed: 0.0,
        total_duration: 0.0,
    };
}

function createJob(jobId, clientToken) {
    const job = makeJob(jobId, clientToken);
    JOBS.set(jobId, job);
    persistJob(jobId);
    return job;
}

function updateJob(jobId, updates) {
    if (!JOBS.has(jobId)) return;
    const job = JOBS.get(jobId);
    Object.assign(job, updates);
    job.updated_at = new Date();
    persistJob(jobId);
}

function persistJob(jobId) {
    if (!JOBS.has(jobId)) return;
    try {
        const job = JOBS.get(jobId);
        const data = {
            ...job,
            created_at: job.created_at.toISOString(),
            updated_at: job.updated_at.toISOString(),
        };
        fsSync.writeFileSync(path.join(JOBS_DIR, `${jobId}.json`), JSON.stringify(data));
    } catch (e) {
        console.error(`persist_job failed: ${e.message}`);
    }
}

function cleanupOldJobs() {
    const now = new Date();
    for (const [jobId, job] of JOBS.entries()) {
        const age = (now - job.updated_at) / 1000;
        if (age > 3600) {
            JOBS.delete(jobId);
            RUNNING_JOBS.delete(jobId);
            const idx = JOB_QUEUE.indexOf(jobId);
            if (idx !== -1) JOB_QUEUE.splice(idx, 1);
            
            // Cleanup files
            for (const file of [
                path.join(JOBS_DIR, `${jobId}.json`),
                path.join(AUDIO_DIR, `${jobId}.mp3`),
                path.join(AUDIO_DIR, `${jobId}.ass`),
                path.join(OUTPUT_DIR, `${jobId}.mp4`),
            ]) {
                try {
                    fsSync.unlinkSync(file);
                } catch (e) {
                    // ignore
                }
            }
        }
    }
}

// =============================================================================
// QUEUE HELPERS
// =============================================================================
function queuePosition(jobId) {
    const idx = JOB_QUEUE.indexOf(jobId);
    return idx !== -1 ? idx + 1 : null;
}

function queueEta(position, jobDuration = null) {
    let runningRemaining = AVG_JOB_DURATION_S;
    
    for (const jid of RUNNING_JOBS) {
        const j = JOBS.get(jid);
        if (!j) continue;
        const total = j.total_duration || AVG_JOB_DURATION_S;
        const out = j.ffmpeg_out_time || 0;
        const remaining = Math.max(0, total - out);
        runningRemaining = Math.min(runningRemaining, remaining);
    }

    const queuedAhead = Math.max(0, position - 1);
    const totalWaitS = runningRemaining + queuedAhead * AVG_JOB_DURATION_S;
    const ownDuration = jobDuration || AVG_JOB_DURATION_S;
    const totalS = totalWaitS + ownDuration;

    const lowS = Math.floor(totalWaitS * 0.75);
    const highS = Math.floor(totalWaitS * 1.2);

    const fmt = (s) => {
        if (s < 60) return `${s}s`;
        const m = Math.floor(s / 60);
        const sec = s % 60;
        return sec ? `${m}m ${sec.toString().padStart(2, '0')}s` : `${m}m`;
    };

    return {
        queue_position: position,
        jobs_ahead: position,
        wait_low_s: lowS,
        wait_high_s: highS,
        wait_low_human: fmt(lowS),
        wait_high_human: fmt(highS),
        total_with_own_s: Math.floor(totalS),
        message: `Position ${position} in queue — roughly ${fmt(lowS)}–${fmt(highS)} wait, likely less`,
    };
}

function refreshQueuePositions() {
    JOB_QUEUE.forEach((jid, i) => {
        if (JOBS.has(jid)) {
            const pos = i + 1;
            updateJob(jid, {
                queue_position: pos,
                message: queueEta(pos).message,
            });
        }
    });
}

// =============================================================================
// FFMPEG PROCESS MANAGEMENT
// =============================================================================
const FFMPEG_PROCS = new Map();

function killFfmpegForJob(jobId) {
    const proc = FFMPEG_PROCS.get(jobId);
    if (proc && !proc.killed) {
        try {
            proc.kill('SIGKILL');
            console.log(`Killed FFmpeg for job ${jobId}`);
        } catch (e) {
            // ignore
        }
    }
    FFMPEG_PROCS.delete(jobId);
}

function parseFfmpegKv(line) {
    const parts = line.trim().split('=');
    if (parts.length !== 2) return {};
    return { [parts[0].trim()]: parts[1].trim() };
}

async function streamFfmpegProgress(proc, jobId, totalDuration, progressStart = 50, progressEnd = 95) {
    let frame = 0, fps = 0, speed = 0;
    let outTimeS = 0.0;
    let lastUpdateTime = Date.now();

    return new Promise((resolve, reject) => {
        proc.stderr.on('data', (data) => {
            const lines = data.toString().split('\n');
            
            for (const line of lines) {
                if (!line.trim()) continue;
                
                const kv = parseFfmpegKv(line);
                if (Object.keys(kv).length === 0) continue;
                
                const [key, val] = Object.entries(kv)[0];
                
                if (key === 'frame') {
                    frame = parseInt(val) || frame;
                } else if (key === 'fps') {
                    fps = parseFloat(val) || fps;
                } else if (key === 'out_time_ms') {
                    outTimeS = parseInt(val) / 1_000_000 || outTimeS;
                } else if (key === 'out_time') {
                    const parts = val.split(':');
                    if (parts.length === 3) {
                        const [h, m, s] = parts;
                        outTimeS = parseInt(h) * 3600 + parseInt(m) * 60 + parseFloat(s);
                    }
                } else if (key === 'speed') {
                    speed = parseFloat(val.replace('x', '')) || speed;
                } else if (key === 'progress') {
                    const now = Date.now();
                    if (val === 'end' || now - lastUpdateTime >= 500) {
                        lastUpdateTime = now;
                        const ratio = totalDuration > 0 ? Math.min(1.0, outTimeS / totalDuration) : 0;
                        const mapped = Math.floor(progressStart + ratio * (progressEnd - progressStart));
                        
                        updateJob(jobId, {
                            progress: mapped,
                            ffmpeg_frame: frame,
                            ffmpeg_fps: fps,
                            ffmpeg_out_time: Math.round(outTimeS * 100) / 100,
                            ffmpeg_speed: speed,
                            total_duration: totalDuration,
                            message: totalDuration > 0 && speed > 0
                                ? `Encoding ${outTimeS.toFixed(1)}s / ${totalDuration.toFixed(1)}s (${speed.toFixed(1)}x speed)`
                                : 'Encoding...',
                        });
                    }
                    
                    if (val === 'end') {
                        resolve();
                        return;
                    }
                    
                    if (JOBS.get(jobId)?.status === 'failed') {
                        proc.kill();
                        reject(new Error('Job marked as failed'));
                        return;
                    }
                }
            }
        });

        proc.on('close', (code) => {
            if (code === 0) {
                resolve();
            } else {
                reject(new Error(`FFmpeg exited with code ${code}`));
            }
        });

        proc.on('error', reject);
    });
}

// =============================================================================
// CORE VIDEO PROCESSING
// =============================================================================
async function processVideoTask(jobId, audioPath, subsPath, background, duration) {
    try {
        console.log(`Job ${jobId}: starting encode`);
        updateJob(jobId, {
            status: 'processing',
            progress: 10,
            message: 'Downloading background video...',
            queue_position: null,
        });

        // Auto-detect category from video name
        // ss1, ss2, ss3, ss4, ss5 → subwaysurfers
        // mc1, mc2, etc. → minecraft
        let category = 'minecraft'; // default fallback
        if (background.startsWith('ss')) {
            category = 'subwaysurfers';
        } else if (background.startsWith('mc')) {
            category = 'minecraft';
        }

        let bgPath;
        try {
            bgPath = await downloadVideoFromDataset(background, category);
        } catch (e) {
            updateJob(jobId, { status: 'failed', error: e.message });
            return;
        }

        updateJob(jobId, { progress: 20, message: 'Analysing media...' });

        const audioDur = duration || await getMediaDuration(audioPath);
        const videoDur = await getMediaDuration(bgPath);

        if (audioDur < 1 || audioDur > 180) {
            updateJob(jobId, { status: 'failed', error: 'Audio duration out of range (1-180 s)' });
            return;
        }

        console.log(`Job ${jobId}: audio=${audioDur.toFixed(2)}s  bg=${videoDur.toFixed(2)}s`);

        let bgInputArgs;
        if (videoDur > audioDur) {
            const maxStart = videoDur - audioDur;
            const start = Math.random() * maxStart;
            bgInputArgs = [
                '-ss', start.toFixed(3),
                '-t', audioDur.toFixed(3),
                '-i', bgPath,
            ];
            console.log(`Job ${jobId}: trim start=${start.toFixed(2)}s`);
        } else {
            const loopN = Math.floor(audioDur / videoDur) + 2;
            bgInputArgs = [
                '-stream_loop', loopN.toString(),
                '-i', bgPath,
            ];
            console.log(`Job ${jobId}: loop x${loopN}`);
        }

        const subsStr = subsPath.replace(/\\/g, '/').replace(/:/g, '\\:');
        const vf = `[0:v]ass='${subsStr}',scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,setsar=1[v]`;

        const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`);

        const finalCmd = [
            '-y',
            '-hide_banner',
            '-loglevel', 'error',
            ...bgInputArgs,
            '-i', audioPath,
            '-filter_complex', vf,
            '-map', '[v]',
            '-map', '1:a',
            '-c:v', 'libx264',
            '-preset', 'medium',
            '-crf', '16',
            '-minrate', '8M',
            '-maxrate', '16M',
            '-bufsize', '16M',
            '-profile:v', 'high',
            '-level:v', '4.2',
            '-pix_fmt', 'yuv420p',
            '-c:a', 'aac',
            '-b:a', '192k',
            '-shortest',
            '-movflags', '+faststart',
            '-threads', '0',
            '-progress', 'pipe:2',
            '-t', audioDur.toFixed(3),
            outputPath,
        ];

        updateJob(jobId, { progress: 40, message: 'Encoding... (single-pass)', total_duration: audioDur });

        const timeout = Math.max(480, Math.floor(audioDur * 5) + 120) * 1000;

        const encodeProc = spawn('ffmpeg', finalCmd);
        FFMPEG_PROCS.set(jobId, encodeProc);

        const progressPromise = streamFfmpegProgress(encodeProc, jobId, audioDur, 40, 95);
        const timeoutPromise = new Promise((_, reject) => 
            setTimeout(() => reject(new Error('timeout')), timeout)
        );

        try {
            await Promise.race([progressPromise, timeoutPromise]);
        } catch (e) {
            killFfmpegForJob(jobId);
            if (e.message === 'timeout') {
                updateJob(jobId, { status: 'failed', error: 'Encoding timed out — try a shorter script' });
                return;
            }
            if (JOBS.get(jobId)?.status === 'failed') {
                return;
            }
            updateJob(jobId, { status: 'failed', error: `Encoding failed: ${e.message.slice(0, 200)}` });
            return;
        }

        FFMPEG_PROCS.delete(jobId);

        if (!fsSync.existsSync(outputPath) || fsSync.statSync(outputPath).size === 0) {
            updateJob(jobId, { status: 'failed', error: 'Output file missing after encode' });
            return;
        }

        const sizeMb = fsSync.statSync(outputPath).size / 1024 / 1024;
        console.log(`Job ${jobId}: done ${sizeMb.toFixed(2)} MB`);

        // Cleanup input files
        for (const p of [audioPath, subsPath]) {
            try {
                await fs.unlink(p);
            } catch (e) {
                // ignore
            }
        }

        updateJob(jobId, {
            status: 'completed',
            progress: 100,
            message: `Done! ${sizeMb.toFixed(1)} MB`,
            output_path: outputPath,
        });

    } catch (e) {
        console.error(`process_video_task unhandled for ${jobId}:`, e);
        updateJob(jobId, { status: 'failed', error: 'Unexpected server error' });
    }
}

// =============================================================================
// VIDEO CLEANUP (1-hour TTL)
// =============================================================================
async function cleanupOldVideos() {
    setInterval(async () => {
        try {
            const cutoffTime = Date.now() / 1000 - 3600; // 1 hour ago
            let cleanedCount = 0;
            let cleanedSizeMb = 0;

            const files = await fs.readdir(OUTPUT_DIR);
            for (const file of files) {
                if (!file.endsWith('.mp4')) continue;
                
                const filePath = path.join(OUTPUT_DIR, file);
                try {
                    const stats = await fs.stat(filePath);
                    if (stats.mtimeMs / 1000 < cutoffTime) {
                        const sizeMb = stats.size / 1024 / 1024;
                        await fs.unlink(filePath);
                        cleanedCount++;
                        cleanedSizeMb += sizeMb;
                        console.log(`Cleaned up ${file} (${sizeMb.toFixed(1)}MB)`);
                    }
                } catch (e) {
                    console.warn(`Cleanup failed ${file}: ${e.message}`);
                }
            }

            if (cleanedCount > 0) {
                console.log(`Cleaned ${cleanedCount} videos, freed ${cleanedSizeMb.toFixed(1)}MB`);
            }
        } catch (e) {
            console.error(`Cleanup error: ${e.message}`);
        }
    }, 600_000); // 10 minutes
}

// =============================================================================
// QUEUE WORKER
// =============================================================================
async function queueWorker() {
    setInterval(async () => {
        if (RUNNING_JOBS.size >= MAX_CONCURRENT) return;
        if (JOB_QUEUE.length === 0) return;

        const jobId = JOB_QUEUE[0];
        const job = JOBS.get(jobId);
        
        if (!job || job.status === 'failed' || job.status === 'completed') {
            JOB_QUEUE.shift();
            return;
        }

        JOB_QUEUE.shift();
        RUNNING_JOBS.add(jobId);
        refreshQueuePositions();

        const audioPath = job.audio_path;
        const subsPath = job.subs_path;
        const background = job.background || 'mc1';
        const duration = job.requested_duration;

        processVideoTask(jobId, audioPath, subsPath, background, duration)
            .finally(() => {
                RUNNING_JOBS.delete(jobId);
                refreshQueuePositions();
            });

    }, 2000);
}

// =============================================================================
// FILE CLEANUP HELPER
// =============================================================================
function deleteOutputFile(jobId, outputPath) {
    setTimeout(async () => {
        try {
            await fs.unlink(outputPath);
            if (JOBS.has(jobId)) {
                updateJob(jobId, {
                    output_path: null,
                    message: 'Downloaded and cleaned up',
                });
            }
            console.log(`Cleaned up ${jobId} after download`);
        } catch (e) {
            console.warn(`Cleanup failed for ${jobId}: ${e.message}`);
        }
    }, 5000); // 5 second delay
}

// =============================================================================
// API ENDPOINTS
// =============================================================================

app.get('/', (req, res) => {
    res.json({
        name: 'ArchNemix Shorts Generator API',
        version: '5.1.0',
        queue: {
            max_concurrent: MAX_CONCURRENT,
            avg_job_duration_s: AVG_JOB_DURATION_S,
        },
        endpoints: {
            register: 'GET  /register',
            generate: 'POST /generate',
            cancel: 'DELETE /job/{id}',
            job_status: 'GET  /job/{id}',
            queue: 'GET  /queue',
            stream: 'GET  /stream/{id}   — inline video playback',
            download: 'GET  /download/{id} — file download (deletes after)',
            delete: 'DELETE /video/{id}',
            videos: 'GET  /videos/{category}',
            health: 'GET  /health',
        },
    });
});

app.get('/register', (req, res) => {
    const client = resolveClient(req);
    res.set('X-Client-ID', client.token);
    res.json({
        client_token: client.token,
        is_new: client.job_count === 0,
        job_count: client.job_count,
        instructions: "Store client_token in localStorage as 'archx_client_id'. Send it as the X-Client-ID header on every request.",
    });
});

app.get('/health', async (req, res) => {
    try {
        const videos = await listVideosFromDataset('minecraft');
        res.json({
            status: 'healthy',
            timestamp: new Date().toISOString(),
            videos: videos.length,
            running: RUNNING_JOBS.size,
            queued: JOB_QUEUE.length,
            active_jobs: Array.from(JOBS.values()).filter(j => j.status === 'processing').length,
        });
    } catch (e) {
        res.status(503).json({ status: 'degraded', error: e.message });
    }
});

app.get('/queue', (req, res) => {
    const running = RUNNING_JOBS.size;
    const waiting = JOB_QUEUE.length;
    res.json({
        running,
        waiting,
        total_active: running + waiting,
        avg_job_s: AVG_JOB_DURATION_S,
        estimated_wait_s: running === 0 ? waiting * AVG_JOB_DURATION_S : (waiting + 1) * AVG_JOB_DURATION_S,
        message: (running + waiting) === 0 ? 'No jobs running — submit yours now!' : `${running} running, ${waiting} in queue`,
    });
});

app.get('/videos/:category', async (req, res) => {
    const category = req.params.category || 'minecraft';
    try {
        const videos = await listVideosFromDataset(category) || Array.from({ length: 6 }, (_, i) => `mc${i + 1}`);
        res.json({ category, videos, count: videos.length });
    } catch (e) {
        res.json({
            category,
            videos: Array.from({ length: 6 }, (_, i) => `mc${i + 1}`),
            count: 6,
            error: e.message,
        });
    }
});

app.post('/generate', async (req, res) => {
    if (!validateAppKey(req)) {
        return res.status(403).json({ error: 'Invalid API key' });
    }
    if (!validateOrigin(req)) {
        return res.status(403).json({ error: 'Invalid origin' });
    }

    const client = resolveClient(req);
    const token = client.token;

    if (!rateLimit(`generate:${token}`, GENERATE_LIMIT)) {
        return res.status(429).json({ error: `Rate limit: max ${GENERATE_LIMIT} requests/hour` });
    }

    cleanupOldJobs();

    const activeForClient = Array.from(JOBS.values()).filter(
        j => j.client_token === token && (j.status === 'queued' || j.status === 'processing')
    );
    
    if (activeForClient.length > 0) {
        const existingId = activeForClient[0].id;
        return res.status(409).json({
            error: `You already have an active job (${existingId}). Wait for it to finish or cancel it first.`,
        });
    }

    const { audio_base64, subtitles_ass, background, duration } = req.body;

    if (!audio_base64 || audio_base64.length < 10) {
        return res.status(400).json({ error: 'audio_base64 is required and must be at least 10 characters' });
    }
    if (!subtitles_ass || subtitles_ass.length < 10) {
        return res.status(400).json({ error: 'subtitles_ass is required and must be at least 10 characters' });
    }
    if (!background) {
        return res.status(400).json({ error: 'background is required' });
    }

    const jobId = uuidv4();
    const audioPath = path.join(AUDIO_DIR, `${jobId}.mp3`);
    const subsPath = path.join(AUDIO_DIR, `${jobId}.ass`);

    createJob(jobId, token);

    try {
        await saveBase64Audio(audio_base64, audioPath);
        await saveSubtitles(subtitles_ass, subsPath);
    } catch (e) {
        updateJob(jobId, { status: 'failed', error: e.message });
        return res.status(400).json({ error: e.message });
    }

    updateJob(jobId, {
        audio_path: audioPath,
        subs_path: subsPath,
        background,
        requested_duration: duration,
    });

    client.job_count++;
    client.jobs.push(jobId);
    if (client.jobs.length > 50) {
        client.jobs = client.jobs.slice(-50);
    }
    saveClient(client);

    const position = RUNNING_JOBS.size === 0 ? 0 : JOB_QUEUE.length + 1;
    JOB_QUEUE.push(jobId);
    refreshQueuePositions();

    const eta = position === 0
        ? { message: 'Starting very soon...', wait_low_s: 0, wait_high_s: 30 }
        : queueEta(position, duration);

    res.set('X-Client-ID', token);
    res.json({
        job_id: jobId,
        client_token: token,
        status: 'queued',
        queue_position: position > 0 ? position : 1,
        queue: eta,
        check_status: `/job/${jobId}`,
    });
});

app.get('/job/:job_id', (req, res) => {
    const jobId = req.params.job_id;

    if (!rateLimit(`status:${jobId}`, STATUS_LIMIT)) {
        return res.json({ job_id: jobId, status: 'rate_limited' });
    }

    if (!JOBS.has(jobId)) {
        const jobFile = path.join(JOBS_DIR, `${jobId}.json`);
        if (fsSync.existsSync(jobFile)) {
            try {
                const data = JSON.parse(fsSync.readFileSync(jobFile, 'utf8'));
                return res.json(data);
            } catch (e) {
                // ignore
            }
        }
        return res.status(404).json({ error: 'Job not found' });
    }

    const job = JOBS.get(jobId);

    const now = new Date();
    if ((now - job.updated_at) / 1000 > JOB_TIMEOUT) {
        if (job.status !== 'completed' && job.status !== 'failed') {
            updateJob(jobId, { status: 'failed', error: 'Job timed out' });
        }
    }

    const pos = queuePosition(jobId);

    const resp = {
        job_id: job.id,
        status: job.status,
        progress: job.progress,
        message: job.message,
        queue_position: pos,
        queue: pos ? queueEta(pos) : null,
        created_at: job.created_at.toISOString(),
        updated_at: job.updated_at.toISOString(),
        encode_stats: {
            frame: job.ffmpeg_frame || 0,
            fps: job.ffmpeg_fps || 0.0,
            out_time_s: job.ffmpeg_out_time || 0.0,
            total_s: job.total_duration || 0.0,
            speed: job.ffmpeg_speed || 0.0,
        },
    };

    // Return both URLs when completed — controller stores these directly
    if (job.status === 'completed' && job.output_path) {
        resp.download_url = `/download/${jobId}`;
        resp.stream_url = `/stream/${jobId}`;
    }

    if (job.error) {
        resp.error = job.error;
    }

    res.json(resp);
});

app.get('/stream/:job_id', (req, res) => {
    const jobId = req.params.job_id;
    const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`);
    
    if (!fsSync.existsSync(outputPath)) {
        return res.status(404).json({ error: 'Video not found or not ready' });
    }
    
    if (JOBS.has(jobId) && JOBS.get(jobId).status !== 'completed') {
        return res.status(400).json({ error: 'Video not ready yet' });
    }

    res.set({
        'Cache-Control': 'no-cache',
        'Accept-Ranges': 'bytes',
    });
    res.sendFile(outputPath);
});

app.get('/download/:job_id', (req, res) => {
    const jobId = req.params.job_id;
    const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`);
    
    if (!fsSync.existsSync(outputPath)) {
        return res.status(404).json({ error: 'Video not found or not ready' });
    }
    
    if (JOBS.has(jobId) && JOBS.get(jobId).status !== 'completed') {
        return res.status(400).json({ error: 'Video not ready yet' });
    }

    // Delete file from /tmp after response is sent
    res.on('finish', () => deleteOutputFile(jobId, outputPath));

    res.set({
        'Content-Disposition': `attachment; filename="archnemix-short-${jobId.slice(0, 8)}.mp4"`,
        'Cache-Control': 'no-cache',
    });
    res.sendFile(outputPath);
});

app.delete('/video/:job_id', async (req, res) => {
    if (!validateAppKey(req)) {
        return res.status(403).json({ error: 'Invalid API key' });
    }

    const jobId = req.params.job_id;
    const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`);
    let removed = false;

    if (fsSync.existsSync(outputPath)) {
        try {
            await fs.unlink(outputPath);
            removed = true;
            console.log(`Deleted ${jobId}`);
        } catch (e) {
            return res.status(500).json({ error: `Delete failed: ${e.message}` });
        }
    }

    if (JOBS.has(jobId)) {
        updateJob(jobId, {
            output_path: null,
            message: 'Video deleted by user',
        });
    }

    res.json({ job_id: jobId, deleted: removed });
});

app.delete('/job/:job_id', (req, res) => {
    if (!validateAppKey(req)) {
        return res.status(403).json({ error: 'Invalid API key' });
    }

    const jobId = req.params.job_id;

    if (!JOBS.has(jobId)) {
        return res.json({ job_id: jobId, cancelled: false, reason: 'not found' });
    }

    const job = JOBS.get(jobId);
    if (job.status === 'completed' || job.status === 'failed') {
        return res.json({ job_id: jobId, cancelled: false, reason: job.status });
    }

    killFfmpegForJob(jobId);
    RUNNING_JOBS.delete(jobId);
    
    const idx = JOB_QUEUE.indexOf(jobId);
    if (idx !== -1) {
        JOB_QUEUE.splice(idx, 1);
    }

    // Clean up output file if it exists
    const outputPath = path.join(OUTPUT_DIR, `${jobId}.mp4`);
    try {
        fsSync.unlinkSync(outputPath);
    } catch (e) {
        // ignore
    }

    updateJob(jobId, {
        status: 'failed',
        error: 'Cancelled by controller — client disconnected',
    });
    refreshQueuePositions();

    console.log(`Job ${jobId} cancelled via controller request`);
    res.json({ job_id: jobId, cancelled: true });
});

app.get('/debug/dataset', async (req, res) => {
    try {
        const fetch = (await import('node-fetch')).default;
        const url = `https://huggingface.co/api/datasets/${HF_DATASET}/tree/main`;
        const headers = HF_TOKEN ? { 'Authorization': `Bearer ${HF_TOKEN}` } : {};
        
        const response = await fetch(url, { headers });
        const files = await response.json();
        const mc = files.filter(f => f.path.toLowerCase().includes('minecraft') && f.path.endsWith('.mp4'));
        
        res.json({
            dataset: HF_DATASET,
            total_files: files.length,
            minecraft: mc.map(f => f.path),
        });
    } catch (e) {
        res.status(500).json({ status: 'error', error: e.message });
    }
});

// =============================================================================
// STARTUP
// =============================================================================
app.listen(PORT, async () => {
    console.log('='.repeat(60));
    console.log('ArchNemix Shorts Generator API v5.1.0 (Node.js)');
    console.log(`Dataset    : ${HF_DATASET}`);
    console.log(`Concurrent : ${MAX_CONCURRENT}`);
    console.log(`Avg job    : ${AVG_JOB_DURATION_S}s (${Math.floor(AVG_JOB_DURATION_S / 60)}m)`);
    console.log('Quality    : CRF 16 · medium · 8-16 Mbps · AAC 192k');
    console.log('Video path : stream from /tmp, delete on download');
    console.log('='.repeat(60));

    queueWorker();
    cleanupOldVideos();

    try {
        const vids = await listVideosFromDataset('minecraft');
        console.log(`${vids.length} videos cached`);
    } catch (e) {
        console.warn(`Video cache warm-up: ${e.message}`);
    }

    cleanupOldJobs();
    console.log(`Ready on port ${PORT}`);
});

// Graceful shutdown
process.on('SIGTERM', () => {
    console.log('Shutdown — cleaning jobs');
    cleanupOldJobs();
    process.exit(0);
});