File size: 39,686 Bytes
94ea30c
 
5b84d75
dc1d9a1
9efecfd
 
 
 
5b84d75
94ea30c
5b84d75
f16c1f5
 
 
 
 
 
 
 
94ea30c
 
6e5f553
f16c1f5
9efecfd
f16c1f5
 
9efecfd
 
 
6e5f553
dc1d9a1
 
 
 
 
 
 
 
 
 
 
 
 
6e5f553
dc1d9a1
 
6e5f553
 
 
 
b192674
f16c1f5
dc1d9a1
 
f16c1f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9efecfd
 
f16c1f5
9efecfd
 
 
f16c1f5
9efecfd
f16c1f5
9efecfd
 
 
 
f16c1f5
 
 
 
9efecfd
 
 
 
f16c1f5
 
 
9efecfd
f16c1f5
 
 
 
 
 
 
 
 
 
9efecfd
 
 
f16c1f5
 
 
 
 
 
9efecfd
f16c1f5
 
9efecfd
b192674
 
f16c1f5
b192674
6e5f553
f16c1f5
dc1d9a1
6e5f553
 
f16c1f5
6e5f553
f16c1f5
 
6e5f553
4275023
f16c1f5
 
 
 
4275023
 
f16c1f5
 
 
 
4275023
6e5f553
f16c1f5
 
6e5f553
f16c1f5
6e5f553
f16c1f5
6e5f553
 
 
 
4275023
6e5f553
4275023
6e5f553
4275023
f16c1f5
 
4275023
b192674
 
 
f16c1f5
b192674
6e5f553
 
f16c1f5
 
 
9efecfd
6e5f553
98fa784
26546d4
 
 
f16c1f5
26546d4
 
 
 
f16c1f5
a9c8a82
f16c1f5
 
 
 
 
9efecfd
 
a9c8a82
26546d4
a9c8a82
 
 
c101d28
f16c1f5
9efecfd
f16c1f5
c101d28
 
f16c1f5
9efecfd
f16c1f5
9efecfd
f16c1f5
c101d28
9efecfd
f16c1f5
9efecfd
76c92ce
 
 
 
9efecfd
 
f16c1f5
c101d28
9efecfd
f16c1f5
9efecfd
 
 
 
f16c1f5
 
98fa784
6e5f553
 
 
 
 
 
 
 
 
 
f16c1f5
 
6e5f553
 
 
 
 
f16c1f5
6e5f553
98fa784
f16c1f5
6e5f553
 
98fa784
9efecfd
6e5f553
98fa784
6e5f553
b192674
a9c8a82
 
 
9efecfd
f16c1f5
 
 
9efecfd
f16c1f5
a9c8a82
 
6e5f553
 
 
 
 
 
 
9efecfd
f16c1f5
9efecfd
 
 
6e5f553
 
 
 
b192674
6e5f553
b192674
6e5f553
 
 
 
 
76c92ce
 
 
 
 
6e5f553
 
dc1d9a1
b192674
 
 
76c92ce
 
 
 
 
dc1d9a1
 
7c03b9c
 
 
f16c1f5
 
 
7c03b9c
 
 
f16c1f5
 
 
7c03b9c
 
 
f16c1f5
 
 
7c03b9c
 
 
f16c1f5
 
 
7c03b9c
 
 
f16c1f5
 
 
76c92ce
 
 
 
 
 
 
 
 
 
 
 
7c03b9c
 
 
6e5f553
 
 
f16c1f5
 
 
 
6e5f553
 
 
7c03b9c
 
 
f16c1f5
 
 
 
 
 
 
 
 
7c03b9c
 
b192674
f16c1f5
 
 
7c03b9c
 
 
 
 
f16c1f5
9efecfd
 
 
 
 
 
f16c1f5
9efecfd
 
f16c1f5
 
 
9efecfd
 
6e5f553
 
 
 
 
 
 
f16c1f5
6e5f553
 
 
f16c1f5
6e5f553
 
f16c1f5
6e5f553
f16c1f5
 
6e5f553
9efecfd
6e5f553
f16c1f5
6e5f553
 
 
 
 
 
 
f16c1f5
 
 
6e5f553
 
 
b192674
 
 
f16c1f5
9efecfd
94ea30c
b192674
 
 
6e5f553
4275023
9efecfd
f16c1f5
 
 
9efecfd
f16c1f5
9efecfd
f16c1f5
b192674
 
 
f16c1f5
9efecfd
f16c1f5
 
9efecfd
f16c1f5
 
9efecfd
 
 
 
f16c1f5
9efecfd
 
 
f16c1f5
9efecfd
 
f16c1f5
 
 
 
 
 
 
9efecfd
 
b192674
f16c1f5
 
 
 
 
 
9efecfd
 
98fa784
9efecfd
 
f16c1f5
 
 
 
9efecfd
f16c1f5
9efecfd
 
 
 
 
 
f16c1f5
9efecfd
 
f16c1f5
 
 
 
9efecfd
 
 
f16c1f5
9efecfd
 
 
b192674
f16c1f5
 
94ea30c
6e5f553
 
94ea30c
 
9efecfd
 
94ea30c
6e5f553
 
94ea30c
9efecfd
94ea30c
 
6e5f553
94ea30c
6e5f553
94ea30c
6e5f553
f79db97
94ea30c
 
 
 
6e5f553
94ea30c
f16c1f5
 
94ea30c
 
f16c1f5
 
 
 
94ea30c
6e5f553
f79db97
f16c1f5
 
 
9efecfd
94ea30c
 
f16c1f5
9efecfd
 
 
b192674
f16c1f5
 
c1e5804
6e5f553
 
c1e5804
 
9efecfd
 
c1e5804
6e5f553
 
c1e5804
9efecfd
c1e5804
 
6e5f553
f79db97
6e5f553
c1e5804
 
 
 
 
 
6e5f553
c1e5804
f16c1f5
6e5f553
f16c1f5
c1e5804
 
 
6e5f553
f16c1f5
c1e5804
6e5f553
 
c1e5804
f16c1f5
c1e5804
6e5f553
f16c1f5
6e5f553
f16c1f5
 
6e5f553
f16c1f5
c1e5804
 
 
 
 
f16c1f5
 
c1e5804
6e5f553
f79db97
f16c1f5
 
 
9efecfd
c1e5804
 
f16c1f5
9efecfd
 
 
b192674
f16c1f5
 
1218518
6e5f553
 
cb561b4
 
9efecfd
 
cb561b4
6e5f553
 
cb561b4
9efecfd
cb561b4
c1e5804
6e5f553
cb561b4
6e5f553
cb561b4
 
 
 
 
6e5f553
cb561b4
 
 
 
6e5f553
cb561b4
 
 
 
 
 
 
f16c1f5
cb561b4
 
6e5f553
f16c1f5
cb561b4
 
9efecfd
 
cb561b4
f16c1f5
 
cb561b4
9efecfd
cb561b4
 
6e5f553
f16c1f5
cb561b4
6e5f553
f16c1f5
cb561b4
 
 
 
6e5f553
cb561b4
f16c1f5
 
 
9efecfd
dc1d9a1
 
b192674
98fa784
6e5f553
dc1d9a1
 
cb561b4
dc1d9a1
f16c1f5
6e5f553
 
 
f16c1f5
a9c8a82
f16c1f5
 
 
 
 
 
 
 
6e5f553
 
 
f16c1f5
6e5f553
 
 
a9c8a82
f16c1f5
 
 
 
 
 
 
 
b192674
 
f16c1f5
 
 
 
 
a9c8a82
 
f16c1f5
9efecfd
f16c1f5
9efecfd
 
f16c1f5
9efecfd
 
f16c1f5
9efecfd
f16c1f5
 
9efecfd
 
 
f16c1f5
26546d4
 
 
9efecfd
 
f16c1f5
 
9efecfd
 
f16c1f5
 
 
 
 
 
 
 
 
 
 
1b8c5c0
f16c1f5
9efecfd
1b8c5c0
f16c1f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e5f553
f16c1f5
 
 
6e5f553
 
f16c1f5
9efecfd
f16c1f5
 
 
 
9efecfd
 
 
b192674
f16c1f5
9efecfd
f16c1f5
 
 
9efecfd
f16c1f5
9efecfd
 
 
 
 
f16c1f5
9efecfd
 
 
f16c1f5
9efecfd
 
 
 
 
 
 
 
 
 
f16c1f5
9efecfd
 
 
f16c1f5
 
 
 
 
9efecfd
 
 
a9c8a82
9efecfd
6e5f553
f16c1f5
9efecfd
 
 
 
 
f16c1f5
6e5f553
9efecfd
26546d4
 
f16c1f5
 
 
 
 
26546d4
 
9efecfd
f16c1f5
 
 
 
6e5f553
 
cb561b4
 
6e5f553
 
 
cb561b4
6e5f553
f16c1f5
 
 
 
 
 
 
 
 
 
 
 
6e5f553
f16c1f5
6e5f553
 
f16c1f5
6e5f553
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
const express = require('express');
const { createCanvas, loadImage } = require('canvas');
const cors = require('cors');
const Tesseract = require('tesseract.js');
const compression = require('compression');
const crypto = require('crypto');
const http = require('http');
const https = require('https');

const app = express();
app.use(cors());
app.use(compression({
    filter: (req, res) => {
        // PNG zaten sıkıştırılmış, tekrar gzip yapmak boşa CPU yakıyor
        if (res.getHeader('Content-Type') === 'image/png') return false;
        return compression.filter(req, res);
    },
    level: 1 // En hızlı gzip seviyesi
}));
app.use(express.json());

// ─────────────────────────────────────────────
// KEEP-ALIVE AGENTS FOR EXTREMELY FAST FETCHES
// ─────────────────────────────────────────────
const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 256, keepAliveMsecs: 30000, scheduling: 'fifo' });
const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 256, keepAliveMsecs: 30000, scheduling: 'fifo' });

// ─────────────────────────────────────────────
// TASK QUEUES
// ─────────────────────────────────────────────
class TaskQueue {
    constructor(concurrency = 1) {
        this.concurrency = concurrency;
        this.running = 0;
        this.queue = [];
    }
    add(task) {
        return new Promise((resolve, reject) => {
            this.queue.push({ task, resolve, reject });
            this.next();
        });
    }
    next() {
        if (this.running >= this.concurrency || this.queue.length === 0) return;
        this.running++;
        const { task, resolve, reject } = this.queue.shift();
        task().then(resolve).catch(reject).finally(() => {
            this.running--;
            this.next();
        });
    }
    isBusy() { return this.running >= this.concurrency; }
}

// vCPU Limit of 2: Canvas native C++ threads + daha düşük PNG compression = daha fazla paralel iş
const canvasQueue = new TaskQueue(5);

// ─────────────────────────────────────────────
// CANVAS POOL - Reuse canvas objects to avoid GC pressure
// ─────────────────────────────────────────────
class CanvasPool {
    constructor() {
        this.pools = new Map(); // 'WxH' -> [canvas]
    }
    acquire(width, height) {
        const key = `${width}x${height}`;
        const pool = this.pools.get(key);
        if (pool && pool.length > 0) return pool.pop();
        return createCanvas(width, height);
    }
    release(canvas) {
        const key = `${canvas.width}x${canvas.height}`;
        if (!this.pools.has(key)) this.pools.set(key, []);
        const pool = this.pools.get(key);
        if (pool.length < 8) {
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            pool.push(canvas);
        }
    }
}
const canvasPool = new CanvasPool();

// Pre-warm font rendering to eliminate cold-start penalty
function prewarmFonts() {
    const c = createCanvas(1, 1);
    const ctx = c.getContext('2d');
    const fonts = [
        '14px sans-serif', '16px sans-serif', '18px sans-serif',
        '20px sans-serif', '24px sans-serif', '36px sans-serif', '42px sans-serif',
        'bold 14px sans-serif', 'bold 16px sans-serif', 'bold 18px sans-serif',
        'bold 20px sans-serif', 'bold 24px sans-serif', 'bold 36px sans-serif',
        'bold 42px sans-serif', 'italic 18px sans-serif'
    ];
    for (const f of fonts) {
        ctx.font = f;
        ctx.fillText('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 0, 0);
    }
    console.log('[Canvas] Fonts pre-warmed ✓');
}

// ─────────────────────────────────────────────
// HIGH-CAPACITY LRU CACHE (18GB RAM available)
// ─────────────────────────────────────────────
class CacheStore {
    constructor(maxSize = 10000, defaultTtlMs = 600000) {
        this.maxSize = maxSize;
        this.defaultTtlMs = defaultTtlMs;
        this.store = new Map();
    }
    get(key) {
        const item = this.store.get(key);
        if (!item) return null;
        if (Date.now() > item.expiry) {
            this.store.delete(key);
            return null;
        }
        return item.value;
    }
    set(key, value, ttlMs = this.defaultTtlMs) {
        if (this.store.size >= this.maxSize) {
            // Evict oldest (Map preserves insertion order)
            const oldestKey = this.store.keys().next().value;
            this.store.delete(oldestKey);
        }
        this.store.set(key, {
            value,
            expiry: Date.now() + ttlMs
        });
    }
    clear() {
        this.store.clear();
    }
    get size() {
        return this.store.size;
    }
}

// ─── ULTRA-AGGRESSIVE CACHE SIZES (18GB RAM) ───
const ocrUrlCache = new CacheStore(100000, 1800000);      // URL → OCR sonucu (30 dakika)
const ocrHashCache = new CacheStore(200000, 7200000);     // MD5 → OCR sonucu (2 saat)
const pHashCache = new CacheStore(200000, 21600000);      // pHash → scam bilgisi (6 saat)
const remoteImageCache = new CacheStore(20000, 3600000);  // Avatar/icon image nesneleri (1 saat)
const canvasRenderCache = new CacheStore(50000, 300000);  // Rendered PNG buffer (5 dakika)

// In-flight request deduplication map to combine concurrent identical requests
const inflightOCR = new Map();
const inflightCanvas = new Map();

// ─────────────────────────────────────────────
// WARM TESSERACT SCHEDULER
// ─────────────────────────────────────────────
let ocrScheduler = null;
let ocrReady = false;

async function initOCR() {
    try {
        console.log('[OCR] Workers starting (Offline mode, Local tessdata)...');
        ocrScheduler = Tesseract.createScheduler();
        
        // 2 parallel workers optimized for 2 vCPU
        const workers = await Promise.all([
            Tesseract.createWorker('eng', 1, {
                langPath: '/app/tessdata',
                cachePath: '/app/tessdata',
                cacheMethod: 'readOnly',
                gzip: true
            }),
            Tesseract.createWorker('eng', 1, {
                langPath: '/app/tessdata',
                cachePath: '/app/tessdata',
                cacheMethod: 'readOnly',
                gzip: true
            })
        ]);
        
        workers.forEach(w => ocrScheduler.addWorker(w));
        ocrReady = true;
        console.log('[OCR] 2 workers ready with local tessdata ✓');
    } catch (err) {
        console.error('[OCR] Worker initialization error:', err.message);
        ocrReady = false;
    }
}

async function runOCR(imageBufferOrUrl) {
    if (ocrReady && ocrScheduler) {
        return ocrScheduler.addJob('recognize', imageBufferOrUrl);
    }
    return Tesseract.recognize(imageBufferOrUrl, 'eng', {
        langPath: '/app/tessdata',
        gzip: true
    });
}

// ─────────────────────────────────────────────
// IMAGE PROCESSING & UTILS
// ─────────────────────────────────────────────
function simpleHash(str) {
    let h = 0;
    for (let i = 0; i < str.length; i++) {
        h = Math.imul(31, h) + str.charCodeAt(i) | 0;
    }
    return (h >>> 0).toString(16);
}

class DownloadError extends Error {
    constructor(message) {
        super(message);
        this.name = "DownloadError";
        this.isDownloadError = true;
    }
}

// Fetch image buffer with short timeout & custom keep-alive agent
async function fetchImageBuffer(imageUrl) {
    const isHttps = imageUrl.startsWith('https');
    const agent = isHttps ? httpsAgent : httpAgent;
    
    const res = await fetch(imageUrl, { 
        signal: AbortSignal.timeout(3000), // 3s strict timeout for 1000ms total budget
        headers: { 'User-Agent': 'Mozilla/5.0 SeireiGuardMediaScan/1.0' },
        agent
    });
    if (!res.ok) throw new DownloadError(`HTTP ${res.status}`);
    return Buffer.from(await res.arrayBuffer());
}

// Pre-process: sadece grayscale, boyut küçültme YOK (metin okunabilirliği için)
async function preprocessImageForOCR(buffer) {
    try {
        const img = await loadImage(buffer);
        const width = img.width;
        const height = img.height;
        
        const canvas = createCanvas(width, height);
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);
        
        // Sadece grayscale dönüşümü
        const imgData = ctx.getImageData(0, 0, width, height);
        const data = imgData.data;
        for (let i = 0; i < data.length; i += 4) {
            const gray = Math.round(0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]);
            data[i] = gray;
            data[i + 1] = gray;
            data[i + 2] = gray;
        }
        ctx.putImageData(imgData, 0, 0);
        
        return canvas.toBuffer('image/jpeg', { quality: 0.75 });
    } catch (err) {
        console.warn('[Preprocessing] Failed, using raw buffer instead:', err.message);
        return buffer;
    }
}

// Compute pHash for fuzzy matching
async function computePHashFromBuffer(buf) {
    try {
        let pixelData;
        try {
            const sharp = require('sharp');
            const { data } = await sharp(buf)
                .resize(8, 8, { fit: 'fill' })
                .grayscale()
                .raw()
                .toBuffer({ resolveWithObject: true });
            pixelData = data;
        } catch {
            const img = await loadImage(buf);
            const c = createCanvas(8, 8);
            const ctx = c.getContext('2d');
            ctx.drawImage(img, 0, 0, 8, 8);
            const d = ctx.getImageData(0, 0, 8, 8).data;
            pixelData = [];
            for (let i = 0; i < d.length; i += 4) {
                pixelData.push(Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2]));
            }
        }

        const avg = pixelData.reduce((s, v) => s + v, 0) / pixelData.length;
        return pixelData.map(p => p >= avg ? '1' : '0').join('');
    } catch (err) {
        console.warn('[pHash] Failed:', err.message);
        return null;
    }
}

function backgroundAddPHash(imageUrl, isScam, reason, keywords) {
    fetchImageBuffer(imageUrl)
        .then(buf => computePHashFromBuffer(buf))
        .then(hash => {
            if (hash) {
                pHashCache.set(hash, { isScam, reason: reason || null, keywords: keywords || [] });
            }
        })
        .catch(err => console.warn('[Background pHash] Error:', err.message));
}

function hammingDistance(h1, h2) {
    if (!h1 || !h2 || h1.length !== h2.length) return 999;
    let d = 0;
    for (let i = 0; i < h1.length; i++) if (h1[i] !== h2[i]) d++;
    return d;
}

function findSimilarInCache(hash, threshold = 10) {
    // Map entries are fast to iterate
    for (const [cachedHash, entry] of pHashCache.store.entries()) {
        const dist = hammingDistance(hash, cachedHash);
        if (dist <= threshold) return { ...entry, distance: dist };
    }
    return null;
}

// ─────────────────────────────────────────────
// KEYWORD / SCAM DETECTION
// ─────────────────────────────────────────────
const FAST_KEYWORDS = [
    "promo code", "withdraw", "claim your reward", "crypto", "nft",
    "mrbeast", "fuzewin", "xcom/", "free nitro", "airdrop", "mint now",
    "usdt", "giveaway", "free money", "claim now", "twogamb.at",
    "bonus", "free usdt", "congratulations", "reward received",
    "activate code", "successfully received", "receive usdt",
    "hasobet", "withdrawal success", "cryptocurrency casino",
    "tether", "your withdrawal", "promo code:", "claim reward",
    "connect wallet", "binance", "coinbase", "trading bot",
    "investment", "double your", "guaranteed profit", "passive income"
];

const SCAM_KEYWORDS = [
    "usdt", "giveaway", "withdrawal", "successfully received", "receive usdt",
    "promo code", "congratulations", "reward received", "activate code",
    "mrbeast", "free money", "claim your reward", "claim now", "twogamb.at",
    "bonus", "gift", "airdrop", "crypto", "free usdt", "withdraw",
    "hasobet", "withdrawal success", "cryptocurrency casino", "tether",
    "your withdrawal", "was successful", "claim reward", "connect wallet",
    "trading bot", "investment", "double your", "guaranteed profit",
    "passive income", "rakeback", "deposit", "casino"
];

const scamRules = [
    {
        pattern: /nitro/i,
        keywords: ["free", "gift", "claim", "promo", "steam", "giveaway", "distribution", "discorx", "dlscord", "get", "link", "claim nitro"],
        minKeywords: 1,
        reason: "Şüpheli Nitro Hediyesi/Kampanyası"
    },
    {
        pattern: /qr|verify|scan|dogrulama|doğrulama/i,
        keywords: ["discord settings", "mobile", "camera", "developer", "options", "safety", "scan", "qr code", "barkod"],
        minKeywords: 2,
        reason: "Şüpheli QR Kod/Doğrulama Yönlendirmesi"
    },
    {
        pattern: /game|test|play|download|indir/i,
        keywords: ["developer", "unity", "unreal", "test my", "my new", "feedback", "executable", ".exe", ".zip", "run", "beta"],
        minKeywords: 2,
        reason: "Şüpheli Oyun/Yazılım İndirme Talebi"
    },
    {
        pattern: /airdrop|crypto|nft|solana|ethereum|eth|btc/i,
        keywords: ["free", "claim", "wallet", "connect", "drop", "giveaway", "whitelist", "mint"],
        minKeywords: 1,
        reason: "Şüpheli Kripto/NFT Dağıtımı"
    },
    {
        pattern: /verification|verify|captcha|restorecord|wick/i,
        keywords: ["click", "link", "server", "join", "verify to", "gain access", "doğrula", "dogrula", "tıkla", "tıklayın"],
        minKeywords: 1,
        reason: "Şüpheli Doğrulama/Captcha Kimlik Avı"
    },
    {
        pattern: /casino|gambling|bet|hasobet|stake|slots|roulette|poker/i,
        keywords: ["bonus", "promo", "deposit", "withdraw", "rakeback", "vip", "reward", "code", "launch", "activate", "claim"],
        minKeywords: 1,
        reason: "Şüpheli Kripto Casino/Bahis Dolandırıcılığı"
    },
    {
        pattern: /withdrawal|transaction|received|success|transfer/i,
        keywords: ["usdt", "tether", "$2", "$5", "$1", "wallet", "trx", "ton", "completed", "continue", "funds"],
        minKeywords: 1,
        reason: "Sahte Para Çekme/İşlem Ekran Görüntüsü"
    }
];

function fastKeywordCheck(text) {
    if (!text) return null;
    const lower = text.toLowerCase();
    const found = [];
    for (const kw of FAST_KEYWORDS) {
        if (lower.includes(kw)) found.push(kw);
    }
    return found.length > 0 ? { isScam: true, reason: "Hızlı Keyword Eşleşmesi", keywords: found } : null;
}

function checkTextForScam(text) {
    if (!text) return null;
    const lower = text.toLowerCase();

    const foundKeywords = [];
    for (const kw of SCAM_KEYWORDS) {
        if (lower.includes(kw)) foundKeywords.push(kw);
    }
    if (foundKeywords.length > 0) {
        return { isScam: true, reason: "Zararlı/Scam Kelime Eşleşmesi", keywords: foundKeywords };
    }

    for (const rule of scamRules) {
        if (rule.pattern.test(lower)) {
            const ruleMatches = rule.keywords.filter(kw => lower.includes(kw));
            if (ruleMatches.length >= rule.minKeywords) {
                return { isScam: true, reason: rule.reason, keywords: ruleMatches };
            }
        }
    }
    return null;
}

// Loaded Image Cacher to prevent downloading avatars and icons multiple times
async function fetchAndCacheImage(url) {
    if (!url) return null;
    const cached = remoteImageCache.get(url);
    if (cached) return cached;
    try {
        const buffer = await fetchImageBuffer(url);
        const img = await loadImage(buffer);
        remoteImageCache.set(url, img);
        return img;
    } catch {
        return null;
    }
}

// ─────────────────────────────────────────────
// FORWARD
// ─────────────────────────────────────────────
async function attemptForward(req, res, path) {
    const otherSpaceUrl = process.env.OTHER_SPACE_URL;
    if (!otherSpaceUrl) return false;
    if (req.headers['x-no-redirect'] === 'true' || req.query.no_redirect === 'true') return false;

    try {
        let targetHost = otherSpaceUrl.endsWith('/') ? otherSpaceUrl.slice(0, -1) : otherSpaceUrl;
        console.log(`[Forward] → ${targetHost}${path}`);

        const headers = { 'Content-Type': 'application/json', 'x-no-redirect': 'true' };
        if (req.headers['authorization']) headers['authorization'] = req.headers['authorization'];

        const response = await fetch(`${targetHost}${path}`, {
            method: 'POST',
            headers,
            body: JSON.stringify(req.body),
            signal: AbortSignal.timeout(6000)
        });

        if (response.ok) {
            const data = await response.json();
            data.forwarded = true;
            data.forwarded_to = targetHost;
            res.json(data);
            return true;
        }
    } catch (err) {
        console.error(`[Forward Error] ${err.message}`);
    }
    return false;
}

// ─────────────────────────────────────────────
// ROUTES
// ─────────────────────────────────────────────

app.get('/', (req, res) => res.send("Seirei Partner Stat API is running at maximum efficiency."));

app.get('/health', (req, res) => {
    res.json({
        status: 'ok',
        ocr_ready: ocrReady,
        ocr_workers: ocrReady ? 2 : 0,
        caches: {
            ocr_url_cache: ocrUrlCache.size,
            ocr_hash_cache: ocrHashCache.size,
            phash_cache: pHashCache.size,
            remote_image_cache: remoteImageCache.size,
            canvas_render_cache: canvasRenderCache.size
        },
        canvas_queue: { running: canvasQueue.running, pending: canvasQueue.queue.length }
    });
});

// Helper to handle canvas requests with high speed rendering cache
function handleCanvasRequest(req, res, routeKey, renderFn) {
    const startTime = Date.now();
    const reqHash = simpleHash(JSON.stringify(req.body));
    const cacheKey = `${routeKey}:${reqHash}`;
    
    // Check render cache (5 dakika TTL)
    const cachedBuffer = canvasRenderCache.get(cacheKey);
    if (cachedBuffer) {
        res.set('Content-Type', 'image/png');
        res.set('X-Cache', 'HIT');
        res.set('X-Response-Time', `${Date.now() - startTime}ms`);
        return res.send(cachedBuffer);
    }

    // Deduplicate in-flight requests
    if (inflightCanvas.has(cacheKey)) {
        return inflightCanvas.get(cacheKey)
            .then(buf => {
                res.set('Content-Type', 'image/png');
                res.set('X-Cache', 'DEDUP');
                res.set('X-Response-Time', `${Date.now() - startTime}ms`);
                res.send(buf);
            })
            .catch(e => res.status(500).json({ error: e.toString() }));
    }

    if (canvasQueue.isBusy()) {
        attemptForward(req, res, req.path).then(forwarded => {
            if (!forwarded) {
                // If forward fails, queue it locally
                queueRender();
            }
        });
    } else {
        queueRender();
    }

    function queueRender() {
        const renderPromise = canvasQueue.add(async () => {
            return renderFn(req.body);
        });

        inflightCanvas.set(cacheKey, renderPromise);

        renderPromise
            .then(buf => {
                inflightCanvas.delete(cacheKey);
                canvasRenderCache.set(cacheKey, buf);
                res.set('Content-Type', 'image/png');
                res.set('X-Cache', 'MISS');
                res.set('X-Response-Time', `${Date.now() - startTime}ms`);
                res.send(buf);
            })
            .catch(e => {
                inflightCanvas.delete(cacheKey);
                res.status(500).json({ error: e.toString() });
            });
    }
}

// ── Partner Stat Canvas ──────────────────────
app.post('/api/partnerstat', (req, res) => {
    handleCanvasRequest(req, res, 'partnerstat', async (body) => {
        const { username, avatar, createdOn, joinedOn, stats } = body;
        const width = 800, height = 350;
        const canvas = canvasPool.acquire(width, height);
        const ctx = canvas.getContext('2d');

        ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height);
        ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 100);

        if (avatar) {
            const img = await fetchAndCacheImage(avatar);
            if (img) {
                ctx.save();
                ctx.beginPath(); ctx.arc(60, 50, 40, 0, Math.PI * 2); ctx.closePath(); ctx.clip();
                ctx.drawImage(img, 20, 10, 80, 80);
                ctx.restore();
            }
        }

        ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif';
        ctx.fillText(username || "Bilinmeyen Kullanıcı", 120, 55);
        ctx.fillStyle = '#b5bac1'; ctx.font = '16px sans-serif';
        ctx.fillText(`Kayıt: ${createdOn || '-'}  •  Katılım: ${joinedOn || '-'}`, 120, 85);
        ctx.fillStyle = '#ffffff'; ctx.font = 'bold 24px sans-serif';
        ctx.fillText(body.title || 'Partnerlik İstatistikleri', 30, 150);

        const drawStatBox = (x, y, w, h, label, value, color) => {
            ctx.fillStyle = '#1e1f22';
            ctx.beginPath();
            if (ctx.roundRect) ctx.roundRect(x, y, w, h, 10); else ctx.rect(x, y, w, h);
            ctx.fill();
            ctx.fillStyle = '#b5bac1'; ctx.font = '16px sans-serif'; ctx.fillText(label, x + 20, y + 30);
            ctx.fillStyle = color; ctx.font = 'bold 42px sans-serif'; ctx.fillText(value.toString(), x + 20, y + 80);
        };

        drawStatBox(30, 180, 170, 120, 'Son 24 Saat', stats?.['1d'] || 0, '#57f287');
        drawStatBox(220, 180, 170, 120, 'Son 7 Gün', stats?.['7d'] || 0, '#fee75c');
        drawStatBox(410, 180, 170, 120, 'Son 30 Gün', stats?.['30d'] || 0, '#eb459e');
        drawStatBox(600, 180, 170, 120, 'Toplam', stats?.['total'] || 0, '#5865F2');

        ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif';
        ctx.fillText(body.footer || 'Seirei Partner Takip Sistemi', 30, 335);
        const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE });
        canvasPool.release(canvas);
        return buf;
    });
});

// ── Partner Leaderboard Canvas ───────────────
app.post('/api/partnerlb', (req, res) => {
    handleCanvasRequest(req, res, 'partnerlb', async (body) => {
        const { guildName, guildIcon, weekly, total } = body;
        const width = 900, height = 650;
        const canvas = canvasPool.acquire(width, height);
        const ctx = canvas.getContext('2d');

        ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height);
        ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 120);

        if (guildIcon) {
            const img = await fetchAndCacheImage(guildIcon);
            if (img) {
                ctx.save();
                ctx.beginPath(); ctx.arc(70, 60, 45, 0, Math.PI * 2); ctx.closePath(); ctx.clip();
                ctx.drawImage(img, 25, 15, 90, 90);
                ctx.restore();
            }
        }

        ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif';
        ctx.fillText(body.title || 'Partnerlik Liderlik Sıralaması', 140, 55);
        ctx.fillStyle = '#b5bac1'; ctx.font = '20px sans-serif';
        ctx.fillText(guildName || "Sunucu İstatistikleri", 140, 90);

        const drawColumn = (x, title, data, color) => {
            const colWidth = 410;
            ctx.fillStyle = '#1e1f22';
            ctx.beginPath();
            if (ctx.roundRect) ctx.roundRect(x, 140, colWidth, 470, 15); else ctx.rect(x, 140, colWidth, 470);
            ctx.fill();
            ctx.fillStyle = color; ctx.font = 'bold 24px sans-serif'; ctx.fillText(title, x + 20, 180);
            ctx.strokeStyle = '#3f4147'; ctx.lineWidth = 2;
            ctx.beginPath(); ctx.moveTo(x + 20, 195); ctx.lineTo(x + colWidth - 20, 195); ctx.stroke();

            let y = 230;
            if (!data || data.length === 0) {
                ctx.fillStyle = '#80848e'; ctx.font = 'italic 18px sans-serif';
                ctx.fillText('Veri bulunamadı.', x + 20, y);
            } else {
                data.slice(0, 10).forEach((item, i) => {
                    ctx.fillStyle = i < 3 ? color : '#313338';
                    ctx.beginPath();
                    if (ctx.roundRect) ctx.roundRect(x + 20, y - 22, 35, 35, 8); else ctx.rect(x + 20, y - 22, 35, 35);
                    ctx.fill();
                    ctx.fillStyle = i < 3 ? '#1e1f22' : '#ffffff'; ctx.font = 'bold 18px sans-serif';
                    ctx.textAlign = 'center'; ctx.fillText((i + 1).toString(), x + 37.5, y + 3); ctx.textAlign = 'left';
                    ctx.fillStyle = '#ffffff'; ctx.font = '18px sans-serif';
                    const name = item.username.length > 20 ? item.username.substring(0, 17) + '...' : item.username;
                    ctx.fillText(name, x + 70, y + 2);
                    ctx.fillStyle = color; ctx.font = 'bold 18px sans-serif';
                    ctx.textAlign = 'right'; ctx.fillText(`${item.count} partner`, x + colWidth - 20, y + 2); ctx.textAlign = 'left';
                    y += 42;
                });
            }
        };

        drawColumn(30, '📅 Bu Hafta (7 Gün)', weekly, '#fee75c');
        drawColumn(460, '👑 Tüm Zamanlar', total, '#5865F2');

        ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif';
        ctx.fillText(body.footer || 'Seirei System Guard • Otomatik Raporlama', 30, 635);
        const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE });
        canvasPool.release(canvas);
        return buf;
    });
});

// ── Arena Leaderboard Canvas ─────────────────
app.post('/api/arenalb', (req, res) => {
    handleCanvasRequest(req, res, 'arenalb', async (body) => {
        const { guildName, guildIcon, rankings } = body;
        const width = 900, height = 700;
        const canvas = canvasPool.acquire(width, height);
        const ctx = canvas.getContext('2d');

        ctx.fillStyle = '#2b2d31'; ctx.fillRect(0, 0, width, height);
        ctx.fillStyle = '#1e1f22'; ctx.fillRect(0, 0, width, 120);

        if (guildIcon) {
            const img = await fetchAndCacheImage(guildIcon);
            if (img) {
                ctx.save();
                ctx.beginPath(); ctx.arc(70, 60, 45, 0, Math.PI * 2); ctx.closePath(); ctx.clip();
                ctx.drawImage(img, 25, 15, 90, 90);
                ctx.restore();
            }
        }

        ctx.fillStyle = '#ffffff'; ctx.font = 'bold 36px sans-serif';
        ctx.fillText('Anime Arenası Puan Sıralaması', 140, 55);
        ctx.fillStyle = '#b5bac1'; ctx.font = '20px sans-serif';
        ctx.fillText(guildName || "Sunucu Arenası", 140, 90);

        const colWidth = 840;
        ctx.fillStyle = '#1e1f22';
        ctx.beginPath();
        if (ctx.roundRect) ctx.roundRect(30, 140, colWidth, 520, 15); else ctx.rect(30, 140, colWidth, 520);
        ctx.fill();

        let y = 190;
        if (!rankings || rankings.length === 0) {
            ctx.fillStyle = '#80848e'; ctx.font = 'italic 18px sans-serif';
            ctx.fillText('Henüz veri bulunamadı.', 60, y);
        } else {
            for (let i = 0; i < Math.min(rankings.length, 10); i++) {
                const char = rankings[i];
                if (i % 2 === 0) {
                    ctx.fillStyle = '#232428';
                    ctx.beginPath();
                    if (ctx.roundRect) ctx.roundRect(40, y - 35, colWidth - 20, 45, 8); else ctx.rect(40, y - 35, colWidth - 20, 45);
                    ctx.fill();
                }
                ctx.fillStyle = i === 0 ? '#fee75c' : i === 1 ? '#b5bac1' : i === 2 ? '#e67e22' : '#ffffff';
                ctx.font = 'bold 20px sans-serif'; ctx.fillText(`${i + 1}.`, 60, y);

                if (char.imageUrl) {
                    const img = await fetchAndCacheImage(char.imageUrl);
                    if (img) {
                        ctx.save();
                        ctx.beginPath(); ctx.arc(110, y - 8, 18, 0, Math.PI * 2); ctx.closePath(); ctx.clip();
                        ctx.drawImage(img, 92, y - 26, 36, 36);
                        ctx.restore();
                    }
                }

                ctx.fillStyle = '#ffffff'; ctx.font = '20px sans-serif';
                const displayName = char.name.length > 35 ? char.name.substring(0, 32) + '...' : char.name;
                ctx.fillText(displayName, 145, y);
                ctx.fillStyle = '#5865F2'; ctx.font = 'bold 20px sans-serif';
                ctx.textAlign = 'right'; ctx.fillText(`${char.score} Puan`, width - 60, y); ctx.textAlign = 'left';
                y += 50;
            }
        }

        ctx.fillStyle = '#80848e'; ctx.font = '14px sans-serif';
        ctx.fillText('Seirei Anime Arena • ⚔️ En İyiler', 30, 685);
        const buf = canvas.toBuffer('image/png', { compressionLevel: 1, filters: canvas.PNG_FILTER_NONE });
        canvasPool.release(canvas);
        return buf;
    });
});

// ── OCR / MediaGuard ─────────────────────────
app.post('/check', async (req, res) => {
    const { image_url, message_content } = req.body;
    if (!image_url) {
        return res.status(400).json({ is_scam: false, error: "image_url is required", status: "failed" });
    }

    // ── KATMAN 1: Caption keyword (0ms)
    if (message_content) {
        const captionHit = fastKeywordCheck(message_content);
        if (captionHit) {
            console.log(`[K1-Caption] Hit: ${captionHit.keywords.join(', ')}`);
            backgroundAddPHash(image_url, true, captionHit.reason, captionHit.keywords);
            return res.json({
                is_scam: true,
                detected_text: "",
                found_keywords: captionHit.keywords,
                threat_reason: captionHit.reason,
                source: "caption_keyword",
                status: "success"
            });
        }
    }

    // ── KATMAN 2: URL keyword (0ms)
    const urlHit = fastKeywordCheck(decodeURIComponent(image_url));
    if (urlHit) {
        console.log(`[K2-URL] Hit: ${urlHit.keywords.join(', ')}`);
        backgroundAddPHash(image_url, true, urlHit.reason, urlHit.keywords);
        return res.json({
            is_scam: true,
            detected_text: "",
            found_keywords: urlHit.keywords,
            threat_reason: urlHit.reason,
            source: "url_keyword",
            status: "success"
        });
    }

    // ── KATMAN 2b: URL-Level Cache check (0ms)
    const cachedOcrByUrl = ocrUrlCache.get(image_url);
    if (cachedOcrByUrl) {
        console.log(`[K2b-URLCache] Hit for ${image_url}`);
        return res.json({ ...cachedOcrByUrl, source: "ocr_url_cache" });
    }

    // Deduplicate in-flight requests for the exact same image URL
    if (inflightOCR.has(image_url)) {
        console.log(`[DEDUP] Joining existing OCR scan for URL: ${image_url}`);
        return inflightOCR.get(image_url)
            .then(result => res.json({ ...result, source: "ocr_dedup" }))
            .catch(err => res.status(500).json({ error: err.message }));
    }

    // Create the task promise
    const scanPromise = (async () => {
        // ── GÖRSELİ BİR KEZ İNDİR
        let imageBuffer = null;
        try {
            imageBuffer = await fetchImageBuffer(image_url);
        } catch (err) {
            console.warn('[Fetch] Failed to download:', err.message);
            if (err.isDownloadError || err.name === 'AbortError') {
                throw new DownloadError(err.name === 'AbortError' ? 'İndirme zaman aşımına uğradı.' : err.message);
            }
        }

        if (!imageBuffer) {
            throw new DownloadError("Görsel indirilemedi.");
        }

        // Compute MD5 for exact duplicate file checking (even with different URL)
        const imageMd5 = crypto.createHash('md5').update(imageBuffer).digest('hex');
        
        // ── KATMAN 2c: Hash-Level Cache check (0ms)
        const cachedOcrByHash = ocrHashCache.get(imageMd5);
        if (cachedOcrByHash) {
            console.log(`[K2c-HashCache] Hit for MD5: ${imageMd5}`);
            // Save to URL Cache too
            ocrUrlCache.set(image_url, cachedOcrByHash);
            return cachedOcrByHash;
        }

        // ── KATMAN 3+5 PARALEL: pHash + OCR Preprocess aynı anda (~50ms tasarruf)
        let pHash = null;
        let processedBuffer = null;
        try {
            // pHash ve OCR preprocessing'i paralel başlat
            const [pHashResult, preprocessResult] = await Promise.allSettled([
                computePHashFromBuffer(imageBuffer),
                preprocessImageForOCR(imageBuffer)
            ]);
            
            pHash = pHashResult.status === 'fulfilled' ? pHashResult.value : null;
            processedBuffer = preprocessResult.status === 'fulfilled' ? preprocessResult.value : imageBuffer;
            
            // pHash cache kontrolü
            if (pHash) {
                const similar = findSimilarInCache(pHash, 10);
                if (similar) {
                    console.log(`[K3-pHash] Cache hit, distance: ${similar.distance}, isScam: ${similar.isScam}`);
                    const result = {
                        is_scam: similar.isScam,
                        detected_text: "",
                        found_keywords: similar.keywords || [],
                        threat_reason: similar.isScam
                            ? `Bilinen scam görseline benziyor (${similar.distance} bit fark)`
                            : null,
                        status: "success"
                    };
                    ocrUrlCache.set(image_url, result);
                    ocrHashCache.set(imageMd5, result);
                    return result;
                }
            }
        } catch (err) {
            console.warn('[K3-Parallel] Skipped:', err.message);
            processedBuffer = processedBuffer || imageBuffer;
        }

        // ── KATMAN 4: Forward (if OCR workers not ready)
        if (!ocrReady) {
            const tempRes = {
                json: (data) => data,
                status: () => ({ json: (data) => data })
            };
            const forwarded = await attemptForward({ body: req.body, headers: req.headers, query: req.query }, tempRes, '/check');
            if (forwarded) return forwarded;
        }

        // ── KATMAN 5: Warm OCR (~200-500ms with 300px preprocessing)
        try {
            console.log(`[K5-OCR] Scanning (preprocessed)...`);
            const result = await runOCR(processedBuffer);
            const text = result.data?.text || "";
            const scamCheck = checkTextForScam(text);
            const isScam = !!scamCheck;

            const responseData = {
                is_scam: isScam,
                detected_text: text,
                found_keywords: scamCheck?.keywords || [],
                threat_reason: scamCheck?.reason || null,
                status: "success"
            };

            // Cache in all caches (URL, Hash, pHash)
            ocrUrlCache.set(image_url, responseData);
            ocrHashCache.set(imageMd5, responseData);
            if (pHash) {
                pHashCache.set(pHash, {
                    isScam,
                    reason: scamCheck?.reason || null,
                    keywords: scamCheck?.keywords || []
                });
            }

            console.log(`[K5-OCR] Complete - isScam: ${isScam}, reason: ${scamCheck?.reason || 'none'}`);
            return responseData;
        } catch (err) {
            console.error('[K5-OCR] Error:', err.message);
            // Last fallback to forward
            const tempRes = {
                json: (data) => data,
                status: () => ({ json: (data) => data })
            };
            const forwarded = await attemptForward({ body: req.body, headers: req.headers, query: req.query }, tempRes, '/check');
            if (forwarded) return forwarded;
            throw err;
        }
    })();

    // Store the promise in inflight map to deduplicate
    inflightOCR.set(image_url, scanPromise);

    try {
        const result = await scanPromise;
        inflightOCR.delete(image_url);
        return res.json({ ...result, source: "ocr" });
    } catch (err) {
        inflightOCR.delete(image_url);
        if (err.isDownloadError) {
            return res.status(200).json({
                is_scam: false,
                error: "Görsel indirilemedi.",
                details: err.message,
                status: "failed",
                download_failed: true
            });
        }
        return res.status(500).json({
            is_scam: false,
            error: "Görsel işlenemedi.",
            details: err.toString(),
            status: "failed"
        });
    }
});

// ─────────────────────────────────────────────
// START
// ─────────────────────────────────────────────
const port = process.env.PORT || 7860;

// Pre-warm everything before accepting traffic
prewarmFonts();

// Pre-allocate canvas pools for common sizes
[{ w: 800, h: 350 }, { w: 900, h: 650 }, { w: 900, h: 700 }].forEach(({ w, h }) => {
    for (let i = 0; i < 3; i++) {
        const c = createCanvas(w, h);
        canvasPool.release(c);
    }
});
console.log('[Canvas] Pool pre-allocated for 3 sizes (3 each) ✓');

initOCR().then(() => {
    app.listen(port, () => console.log(`[Server] Listening on port ${port} - TURBO MODE ✓`));
}).catch(err => {
    console.error('[Startup] OCR init failed, starting anyway:', err.message);
    app.listen(port, () => console.log(`[Server] Listening on port ${port} (OCR degraded)`));
});