File size: 56,646 Bytes
78661be
 
 
 
 
 
 
 
 
f52e861
 
78661be
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52e861
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
4065a20
78661be
 
 
4065a20
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
 
 
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
78661be
 
 
 
 
f52e861
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
24cb476
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52e861
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52e861
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
4065a20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78661be
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
 
78661be
 
 
 
 
 
 
 
 
 
 
4065a20
 
 
78661be
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
 
 
 
 
 
 
4065a20
 
78661be
 
4065a20
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4065a20
78661be
 
4065a20
 
 
 
 
 
 
78661be
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
"""
main.py - ACRA FastAPI Backend
Adaptive Color Re-Encoding System

Endpoints
---------
POST   /process               Upload image β†’ run CVD pipeline β†’ return job
GET    /jobs                  List all active jobs for authenticated user
GET    /jobs/{job_id}         Full job detail with metrics + boxes
GET    /jobs/{job_id}/metrics One job's metrics as CSV or JSON
GET    /metrics/export        Every job and test run, including fails and no-conflict images
DELETE /jobs/{job_id}         Delete job and its images
GET    /health                Server / model health check

POST   /test-runs             Store diagnostic metrics; images expire after 24h
GET    /test-runs             List all test runs for user
GET    /test-runs/analytics   Aggregate stats + per-metric distributions
DELETE /test-runs/{run_id}    Delete one test run
DELETE /test-runs             Clear all test runs for user

Run locally:
    cd code
    uvicorn main:app --reload --port 8000
"""

from __future__ import annotations

import asyncio
import io
import os
import sys
import threading
import time
import uuid

# NumPy (OpenBLAS) and ONNX Runtime each ship an OpenMP runtime. On Windows the
# second native call (the second image) can access-violate (0xC0000005) and
# kill the process. The browser then sits until its timeout. These must be set
# before either library loads.
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional

import httpx
import numpy as np
from PIL import Image, ImageOps

# Teach Pillow to open HEIC/HEIF. Pillow has no built-in decoder for it, so
# without this registration Image.open() raises UnidentifiedImageError on every
# photo straight off an iPhone -- after the upload had already been accepted.
# Kept non-fatal: a missing optional wheel should degrade one format, not stop
# the whole service from booting.
try:
    import pillow_heif

    pillow_heif.register_heif_opener()
    HEIF_OK = True
except Exception as _heif_exc:  # pragma: no cover - depends on the wheel
    HEIF_OK = False
    print(f"[ACRA] HEIC/HEIF support unavailable: {_heif_exc}")
from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / ".env")
load_dotenv(Path(__file__).parent.parent / ".env")

from fastapi import FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware

BASE_DIR = Path(__file__).parent
sys.path.insert(0, str(BASE_DIR))

from pipeline.segmentation import resolve_seg_model, _load_model as _load_seg_model
import local_store

SEG_MODEL_PATH: Optional[str] = resolve_seg_model()

# ── Config ─────────────────────────────────────────────────────────────────────
# Default to OFF. A missing environment variable must never be the thing that
# disables authentication: anyone running this code without setting SKIP_AUTH
# would otherwise get an API that accepts every request. Local development sets
# SKIP_AUTH=true explicitly.
SKIP_AUTH            = os.getenv("SKIP_AUTH", "false").lower() == "true"
SUPABASE_URL         = os.getenv("SUPABASE_URL", "")
SUPABASE_JWT_SECRET  = os.getenv("SUPABASE_JWT_SECRET", "")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY", "")
STORAGE_BUCKET       = os.getenv("STORAGE_BUCKET", "acra-images")
BASE_URL             = os.getenv("BASE_URL", "http://localhost:8000").rstrip("/")
DATA_DIR             = Path(os.getenv("DATA_DIR") or BASE_DIR)
JOB_EXPIRY_HOURS     = 24
PURGE_INTERVAL_S     = min(60, max(1, int(os.getenv("PURGE_INTERVAL_SECONDS", "60"))))
CORS_ORIGINS         = [
    o.strip()
    for o in os.getenv(
        "CORS_ORIGINS",
        "http://localhost:5173,http://localhost:3000",
    ).split(",")
    if o.strip()
]
# Security: a browser forbids allow-credentials with a wildcard origin, so the
# old live config set CORS_ORIGINS="*" which FastAPI turns into "reflect any
# origin" -- strictly worse, because it lets ANY site make authenticated calls
# as a logged-in user. Refuse to run in that shape. If someone really wants an
# open, credential-less API they must set ALLOW_CREDENTIALS=false explicitly.
ALLOW_CREDENTIALS    = os.getenv("ALLOW_CREDENTIALS", "true").lower() == "true"
if "*" in CORS_ORIGINS and ALLOW_CREDENTIALS:
    raise RuntimeError(
        "CORS_ORIGINS='*' with credentials enabled lets any website call this "
        "API as a logged-in user. Set CORS_ORIGINS to your real frontend "
        "origin(s), or set ALLOW_CREDENTIALS=false for a public, cookie-less API."
    )
# Hide interactive API docs in production -- they map the whole attack surface
# for free. On by default only when EXPOSE_DOCS=true.
EXPOSE_DOCS          = os.getenv("EXPOSE_DOCS", "false").lower() == "true"
MAX_IMAGE_BYTES = 10 * 1024 * 1024
ALLOWED_MIMES = {
    "image/jpeg", "image/png", "image/webp", "image/gif",
    "image/bmp", "image/tiff", "image/avif", "image/heic", "image/heif",
}
# The browser fills in a file's MIME type from the OS table, and Windows has no
# entry for .heic -- so an iPhone photo arrives as "" or application/octet-stream
# and a MIME-only check rejects a format that is in the list above. Fall back to
# the filename when the type is missing or generic.
ALLOWED_UPLOAD_EXTS = {
    ".jpg", ".jpeg", ".jfif", ".png", ".webp", ".gif",
    ".bmp", ".dib", ".tif", ".tiff", ".avif", ".heic", ".heif",
}
_VAGUE_MIMES = {"", "application/octet-stream", "binary/octet-stream"}


def _is_allowed_upload(upload) -> bool:
    ctype = (getattr(upload, "content_type", "") or "").split(";")[0].strip().lower()
    if ctype in ALLOWED_MIMES:
        return True
    if ctype and ctype not in _VAGUE_MIMES:
        return False        # a real, specific type that we do not accept
    name = (getattr(upload, "filename", "") or "").lower()
    return Path(name).suffix in ALLOWED_UPLOAD_EXTS

# Local SQLite + static/ when Supabase is not configured (default for local dev).
USE_LOCAL = not (SUPABASE_URL and SUPABASE_SERVICE_KEY)
STATIC_DIR: Path
DB_PATH: Path
if USE_LOCAL:
    STATIC_DIR, DB_PATH = local_store.init_paths(DATA_DIR)
    print(f"[ACRA] Local storage mode - db={DB_PATH} static={STATIC_DIR}")
else:
    STATIC_DIR = DATA_DIR / "static"
    DB_PATH = DATA_DIR / "jobs.db"
    print("[ACRA] Supabase storage mode")

# ── Thread pool ────────────────────────────────────────────────────────────────
_executor = ThreadPoolExecutor(max_workers=2)

# ── YOLO model cache ───────────────────────────────────────────────────────────
_yolo_model   = None
_model_loaded = False
_startup_time = time.time()


def _load_yolo() -> None:
    _ensure_yolo_loaded()


def _ensure_yolo_loaded() -> bool:
    global _yolo_model, _model_loaded, SEG_MODEL_PATH
    if _model_loaded and _yolo_model is not None and SEG_MODEL_PATH:
        return True
    SEG_MODEL_PATH = resolve_seg_model()
    if not SEG_MODEL_PATH:
        print("[ACRA] No YOLO model found - place acra_medium_v7_best.onnx in code/ or set SEG_MODEL_PATH")
        _model_loaded = False
        return False
    try:
        _yolo_model = _load_seg_model(SEG_MODEL_PATH)
        _model_loaded = True
        print(f"[ACRA] Model loaded: {SEG_MODEL_PATH}")
        return True
    except Exception as exc:
        print(f"[ACRA] Warning: could not load model: {exc}")
        _model_loaded = False
        return False


# ── Supabase client ────────────────────────────────────────────────────────────
_sb_client = None


def _get_sb():
    global _sb_client
    if _sb_client is not None:
        return _sb_client
    if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
        raise RuntimeError(
            "SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY must be configured as environment variables"
        )
    from supabase import create_client
    _sb_client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
    return _sb_client


def _ensure_private_storage() -> None:
    if USE_LOCAL:
        return
    storage = _get_sb().storage
    bucket = storage.get_bucket(STORAGE_BUCKET)
    if bucket.public:
        storage.update_bucket(STORAGE_BUCKET, {"public": False})
    if storage.get_bucket(STORAGE_BUCKET).public:
        raise RuntimeError("The image storage bucket must be private.")


# ── Image helpers ──────────────────────────────────────────────────────────────
def _img_to_jpeg_bytes(img_np: np.ndarray, quality: int = 92) -> bytes:
    buf = io.BytesIO()
    Image.fromarray(img_np).save(buf, format="JPEG", quality=quality)
    return buf.getvalue()


# Longest side of the small preview saved beside each result. Storage cards used
# to load the full corrected image to fill a ~300 px tile: measured 289-499 KB
# per card against 38-55 KB for a 480 px thumbnail, so a 12-card page pulled
# 4-6 MB it did not need. 480 still looks sharp on a 2x (retina) screen.
THUMB_MAX_SIDE = 480


def _thumbnail(img_np: np.ndarray) -> np.ndarray:
    im = Image.fromarray(img_np)
    im.thumbnail((THUMB_MAX_SIDE, THUMB_MAX_SIDE))
    return np.asarray(im)


def _thumb_url(corrected_url: Optional[str]) -> Optional[str]:
    """Where the thumbnail lives, derived from the corrected image's URL.

    Derived, not stored, so no database column is needed. Jobs saved before
    thumbnails existed have no file at this address; the frontend falls back to
    the full image when the thumbnail fails to load.
    """
    if not corrected_url or "/corrected.jpg" not in corrected_url:
        return None
    return corrected_url.replace("/corrected.jpg", "/thumb.jpg")


def _sb_retry(fn, *args, **kwargs):
    """Retry a Supabase call once if the connection was already dead.

    _sb_client (_get_sb) is created ONCE and its underlying httpx connections
    are kept alive and reused for the server's entire lifetime. Supabase can
    close an idle one from its side at any moment; the next request to reuse
    it fails before a single byte reaches Supabase, as
    httpx.RemoteProtocolError("Server disconnected without sending a
    response") -- exactly what a batch job reported. It is not a real
    failure of that request: httpx drops the dead connection and opens a
    fresh one on retry, and a batch is exactly when this bites, since several
    uploads fire back to back and one lands on a connection that went stale
    between jobs.
    """
    try:
        return fn(*args, **kwargs)
    except httpx.TransportError:
        return fn(*args, **kwargs)


def _upload_image(img_np: np.ndarray, storage_path: str, quality: int = 92) -> str:
    data = _img_to_jpeg_bytes(img_np, quality)
    if USE_LOCAL:
        local_store.save_image(STATIC_DIR, storage_path, data)
        return f"/images/{storage_path}"
    sb = _get_sb()
    _sb_retry(
        sb.storage.from_(STORAGE_BUCKET).upload,
        path=storage_path,
        file=data,
        file_options={"content-type": "image/jpeg", "upsert": "true"},
    )
    return f"/images/{storage_path}"


def _delete_images(prefix: str) -> None:
    if USE_LOCAL:
        local_store.delete_images(STATIC_DIR, prefix)
        return
    _get_sb().storage.from_(STORAGE_BUCKET).remove(
        [f"{prefix}/original.jpg", f"{prefix}/corrected.jpg", f"{prefix}/thumb.jpg"]
    )


def _insert_row(table: str, row: dict) -> None:
    if USE_LOCAL:
        if table == "jobs":
            local_store.insert_job(DB_PATH, row)
        elif table == "test_runs":
            local_store.insert_test_run(DB_PATH, row)
        else:
            raise ValueError(f"Unknown table: {table}")
        return
    _sb_retry(_get_sb().table(table).insert(row).execute)


async def _to_thread(fn, *args):
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(_executor, fn, *args)


async def _persist_images_and_row(
    prefix: str,
    orig: np.ndarray,
    corr: np.ndarray,
    table: str,
    row: dict,
) -> dict:
    """Upload original, corrected and a thumbnail in parallel, then insert.

    Compensating delete on failure. The thumbnail's URL is not stored -- see
    _thumb_url -- so it adds no column and no migration.
    """
    orig_path = f"{prefix}/original.jpg"
    corr_path = f"{prefix}/corrected.jpg"
    try:
        orig_url, corrected_url, _ = await asyncio.gather(
            _to_thread(_upload_image, orig, orig_path),
            _to_thread(_upload_image, corr, corr_path),
            _to_thread(_upload_image, _thumbnail(corr), f"{prefix}/thumb.jpg", 80),
        )
        row = {**row, "original_url": orig_url, "corrected_url": corrected_url}
        await _to_thread(_insert_row, table, row)
        return row
    except Exception:
        await _to_thread(_delete_images, prefix)
        raise


def _page_bounds(limit: int, offset: int, default: int, maximum: int) -> tuple:
    lim = default if limit is None else int(limit)
    off = 0 if offset is None else int(offset)
    return max(1, min(maximum, lim)), max(0, off)


# ── Lifespan ───────────────────────────────────────────────────────────────────
async def _purge_loop() -> None:
    while True:
        try:
            await _to_thread(_purge_expired)
        except asyncio.CancelledError:
            break
        except Exception as exc:
            print(f"[ACRA] Purge error: {exc}")
        try:
            await asyncio.sleep(PURGE_INTERVAL_S)
        except asyncio.CancelledError:
            break


@asynccontextmanager
async def lifespan(app: FastAPI):
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(_executor, _ensure_private_storage)
    await loop.run_in_executor(_executor, _load_yolo)
    purge_task = asyncio.create_task(_purge_loop())
    try:
        yield
    finally:
        purge_task.cancel()
        try:
            await purge_task
        except asyncio.CancelledError:
            pass
        _executor.shutdown(wait=False, cancel_futures=True)


# ── App ────────────────────────────────────────────────────────────────────────
app = FastAPI(
    title="ACRA", version="1.0.0", lifespan=lifespan,
    docs_url="/docs" if EXPOSE_DOCS else None,
    redoc_url="/redoc" if EXPOSE_DOCS else None,
    openapi_url="/openapi.json" if EXPOSE_DOCS else None,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ORIGINS,
    allow_credentials=ALLOW_CREDENTIALS,
    allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type"],
)


# ── Security headers ────────────────────────────────────────────────────────────
# Sent on every response. These tell the browser to stop guessing MIME types,
# refuse to render the API inside an iframe (clickjacking), and not leak the
# full URL in the Referer header. HSTS forces HTTPS for two years.
@app.middleware("http")
async def _security_headers(request: Request, call_next):
    resp = await call_next(request)
    resp.headers["X-Content-Type-Options"] = "nosniff"
    resp.headers["X-Frame-Options"] = "DENY"
    resp.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
    resp.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains"
    # no-store is right for JSON holding a user's data, but on generated images
    # it forbids the browser cache, so every view re-downloads the file and
    # re-spends rate-limit budget. Job images are already unguessable URLs, so
    # let the BROWSER keep them ("private") while shared proxies still may not.
    if request.url.path.startswith("/static/"):
        resp.headers["Cache-Control"] = "private, max-age=300"
    else:
        resp.headers["Cache-Control"] = "no-store"
    return resp


# ── Rate limiting ───────────────────────────────────────────────────────────────
# A single logged-in account should not be able to fire hundreds of inference
# jobs a minute -- each one burns CPU and, on password/email paths, project
# quota. This is a plain in-process sliding window keyed by client IP.
# ponytail: per-replica counter. HF Spaces can run more than one replica, so the
# real global limit is (this number x replica count). Good enough to stop casual
# abuse; swap for Redis if a determined attacker matters.
import time as _time
from collections import defaultdict, deque

# 240, not 60: the results page polls job status about once a second and pulls
# several panels per job, so a 60 budget locked out ordinary use. The point of
# the limit is to stop someone queueing hundreds of INFERENCE jobs a minute,
# which is the expensive path -- not to ration normal page loads.
RATE_MAX      = int(os.getenv("RATE_LIMIT_PER_MIN", "240"))   # requests
RATE_WINDOW_S = 60
_hits: dict[str, deque] = defaultdict(deque)
_RATE_EXEMPT = {"/", "/health"}
# Serving an already-generated image is a cheap disk read, not model compute.
# Counting them was what broke image viewing: one results page can pull dozens
# of files and trip the limiter before the user has done anything unusual.
_RATE_EXEMPT_PREFIXES = ("/static/",)

@app.middleware("http")
async def _rate_limit(request: Request, call_next):
    if (request.url.path in _RATE_EXEMPT
            or request.url.path.startswith(_RATE_EXEMPT_PREFIXES)
            or request.method == "OPTIONS"):
        return await call_next(request)
    ip = (request.headers.get("x-forwarded-for", "").split(",")[0].strip()
          or (request.client.host if request.client else "unknown"))
    now = _time.monotonic()
    dq = _hits[ip]
    while dq and dq[0] < now - RATE_WINDOW_S:
        dq.popleft()
    if len(dq) >= RATE_MAX:
        from fastapi.responses import JSONResponse
        return JSONResponse(
            {"detail": "Too many requests. Slow down and try again shortly."},
            status_code=429, headers={"Retry-After": str(RATE_WINDOW_S)},
        )
    dq.append(now)
    return await call_next(request)

# ── Auth ───────────────────────────────────────────────────────────────────────
def _extract_user_id(request: Request) -> str:
    auth  = request.headers.get("Authorization", "")
    token = auth.removeprefix("Bearer ").strip()

    if SKIP_AUTH:
        if token.startswith("mock-token-"):
            return "local-dev-user"
        if token:
            # Derive a stable user id from the JWT sub claim without full verification
            try:
                import base64, json as _json
                payload_b64 = token.split(".")[1]
                payload_b64 += "=" * (-len(payload_b64) % 4)
                sub = _json.loads(base64.urlsafe_b64decode(payload_b64)).get("sub", "")
                if sub:
                    return sub
            except Exception:
                pass
        return "local-dev-user"

    if not token:
        raise HTTPException(status_code=401, detail="Missing authorization token")

    try:
        import jwt as pyjwt
        from jwt import PyJWKClient

        if SUPABASE_URL:
            try:
                jwks_client = PyJWKClient(f"{SUPABASE_URL}/auth/v1/.well-known/jwks.json")
                signing_key = jwks_client.get_signing_key_from_jwt(token)
                # Only the asymmetric algorithms here. Accepting HS256 alongside
                # a key fetched from JWKS invites algorithm confusion: an
                # attacker signs a token with HS256 using the *public* key as
                # the shared secret. PyJWT blocks that combination, but the
                # safe list is not something to rely on a library to enforce.
                payload = pyjwt.decode(
                    token, signing_key.key,
                    algorithms=["ES256", "RS256"],
                    options={"verify_aud": False},
                )
                return payload.get("sub", "unknown")
            except Exception:
                pass

        if SUPABASE_JWT_SECRET:
            payload = pyjwt.decode(
                token, SUPABASE_JWT_SECRET,
                algorithms=["HS256"],
                options={"verify_aud": False},
            )
            return payload.get("sub", "unknown")

        raise HTTPException(status_code=401, detail="No JWT verification method configured")
    except HTTPException:
        raise
    except Exception:
        raise HTTPException(status_code=401, detail="Invalid or expired token")


# ── Class mapping ──────────────────────────────────────────────────────────────
def _map_class(class_name: str) -> str:
    KNOWN = {"roi-color", "roi-object", "roi-text", "roi-symbol", "exclude-person"}
    canonical = class_name.lower().strip().replace("_", "-").replace(" ", "-")
    if canonical in KNOWN:
        return canonical
    name = class_name.lower()
    if any(k in name for k in ("person", "human", "face", "people")):
        return "exclude-person"
    if any(k in name for k in ("symbol", "icon", "logo", "mark", "check", "sign")):
        return "roi-symbol"
    if any(k in name for k in ("color", "colour", "swatch", "palette")):
        return "roi-color"
    if any(k in name for k in ("text", "word", "letter", "label")):
        return "roi-text"
    return "roi-object"


# ── Pipeline runner (blocking - runs in thread pool) ──────────────────────────
# Native pipeline (OpenBLAS + ONNX) is not safe to run on two images at once.
_pipeline_lock = threading.Lock()


def _run_pipeline_sync(
    img_np: np.ndarray,
    cvd_type: str,
    severity: float,
    conf_threshold: float,
    use_segmentation: bool = True,
    seg_soft: float = 3.5,
    n_clusters: Optional[int] = None,
    seg_clusters_per_roi: Optional[int] = None,
) -> tuple:
    from pipeline import run_full_pipeline

    with _pipeline_lock:
        return _run_pipeline_locked(
            img_np, cvd_type, severity, conf_threshold,
            use_segmentation, seg_soft, n_clusters, seg_clusters_per_roi,
            run_full_pipeline,
        )


def _run_pipeline_locked(
    img_np, cvd_type, severity, conf_threshold,
    use_segmentation, seg_soft, n_clusters, seg_clusters_per_roi,
    run_full_pipeline,
):
    seg_ready = use_segmentation and _ensure_yolo_loaded()

    corrected_uint8, raw_metrics = run_full_pipeline(
        img_np, severity, cvd_type,
        n_clusters=n_clusters,
        use_segmentation=seg_ready,
        seg_model=SEG_MODEL_PATH,
        seg_conf=conf_threshold,
        seg_soft=seg_soft,
        seg_clusters_per_roi=seg_clusters_per_roi,
        max_proc_pixels=1_500_000,
    )

    timings = raw_metrics.get("_stage_timings")
    if timings:
        print(f"[ACRA] stage timings (s): {timings}")

    boxes: List[Dict] = [
        {**box, "class": _map_class(box.get("class", ""))}
        for box in (raw_metrics.get("yolo_boxes") or [])
    ]

    metrics = {
        "delta_e_improvement":      float(raw_metrics.get("de_improvement", 0.0)),
        "de_before_mean":           float(raw_metrics.get("de_before_mean", 0.0)),
        "de_after_mean":            float(raw_metrics.get("de_after_mean", 0.0)),
        "conflict_resolution_rate": float(raw_metrics.get("conflict_resolution_rate", 0.0)),
        "naturalness_preservation": float(raw_metrics.get("naturalness_preservation", 0.0)),
        "boxes_detected":           len(boxes),
        "conflicts_found":          int(raw_metrics.get("n_conflicts_total", 0)),
        "auto_clusters":            int(raw_metrics.get("auto_clusters", 0)),
        "inference_ms":             float(raw_metrics.get("inference_ms", 0.0)),
        "segmentation_active":      seg_ready,
        "seg_class_names":          raw_metrics.get("seg_class_names"),
        "already_accessible":       bool(raw_metrics.get("already_accessible", False)),
        "pass_de_improvement":      bool(raw_metrics.get("pass_de_improvement", False)),
        "pass_resolution_rate":     bool(raw_metrics.get("pass_resolution_rate", False)),
        "pass_naturalness":         bool(raw_metrics.get("pass_naturalness", False)),
        "conflict_diagnostics":     raw_metrics.get("conflict_diagnostics", {}),
    }

    return corrected_uint8, metrics, boxes


# ── Upload validation ──────────────────────────────────────────────────────────
async def _validate_upload(
    image: UploadFile,
    cvd_type: str,
    severity: float,
    conf_threshold: float,
    seg_soft: float,
    use_segmentation: int,
    n_clusters: Optional[int],
    seg_clusters_per_roi: Optional[int],
    max_dim: Optional[int] = None,
) -> tuple:
    if not _is_allowed_upload(image):
        raise HTTPException(400, detail="Unsupported image format. Accepted: JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF, HEIC.")

    raw_bytes = await image.read()
    if len(raw_bytes) > MAX_IMAGE_BYTES:
        raise HTTPException(400, detail="File size must be under 10 MB.")

    if cvd_type not in ("protan", "deutan"):
        raise HTTPException(400, detail="cvd_type must be 'protan' or 'deutan'.")

    params = {
        "severity":              max(0.0, min(1.0, float(severity))),
        "conf_threshold":        max(0.1, min(0.9, float(conf_threshold))),
        "seg_soft":              max(0.0, min(8.0, float(seg_soft))),
        "use_seg_bool":          bool(use_segmentation),
        "n_clusters":            max(2, min(100, int(n_clusters))) if n_clusters is not None else None,
        "seg_clusters_per_roi":  max(2, min(8, int(seg_clusters_per_roi))) if seg_clusters_per_roi is not None else None,
    }

    try:
        pil_img = Image.open(io.BytesIO(raw_bytes))
        # Phone cameras store the photo in the sensor's native orientation and
        # add an EXIF tag saying how to rotate it. Without this the detector
        # sees every portrait photo lying on its side. Must run BEFORE convert()
        # -- convert() drops the EXIF block along with the tag.
        pil_img = ImageOps.exif_transpose(pil_img)
        pil_img = pil_img.convert("RGB")
        if max_dim is not None and max(pil_img.size) > max_dim:
            pil_img.thumbnail((max_dim, max_dim), Image.Resampling.LANCZOS)
        img_np = np.array(pil_img, dtype=np.uint8)
    except Exception:
        raise HTTPException(400, detail="Could not decode image file.")

    return img_np, params


# ── Response serializers ───────────────────────────────────────────────────────
def _image_deadline(row: dict) -> datetime:
    deadline = datetime.fromisoformat(row["created_at"]) + timedelta(hours=24)
    if row.get("expires_at"):
        deadline = min(deadline, datetime.fromisoformat(row["expires_at"]))
    return deadline


def _image_url(row: dict, collection: str, filename: str) -> Optional[str]:
    if _image_deadline(row) <= datetime.now(timezone.utc):
        return None
    identifier = row["job_id"] if collection == "jobs" else row["run_id"]
    return f"/images/{collection}/{identifier}/{filename}"


def _job_to_response(row: dict) -> Dict[str, Any]:
    return {
        "job_id":               row["job_id"],
        "cvd_type":             row["cvd_type"],
        "severity":             row["severity"],
        "conf_threshold":       row["conf_threshold"],
        "use_segmentation":     bool(row.get("use_segmentation", True)),
        "seg_soft":             row.get("seg_soft", 3.5),
        "n_clusters":           row.get("n_clusters"),
        "seg_clusters_per_roi": row.get("seg_clusters_per_roi", 3),
        "created_at":           row["created_at"],
        "expires_at":           row["expires_at"],
        "original_url":         _image_url(row, "jobs", "original.jpg"),
        "corrected_url":        _image_url(row, "jobs", "corrected.jpg"),
        "thumb_url":            _image_url(row, "jobs", "thumb.jpg"),
        "metrics":              row["metrics"],
        "boxes":                row["boxes"],
    }


def _run_to_response(row: dict) -> Dict[str, Any]:
    return {
        "run_id":               row["run_id"],
        "filename":             row["filename"],
        "cvd_type":             row["cvd_type"],
        "severity":             row["severity"],
        "conf_threshold":       row["conf_threshold"],
        "use_segmentation":     bool(row.get("use_segmentation", True)),
        "seg_soft":             row.get("seg_soft", 3.5),
        "n_clusters":           row.get("n_clusters"),
        "seg_clusters_per_roi": row.get("seg_clusters_per_roi", 3),
        "created_at":           row["created_at"],
        "original_url":         _image_url(row, "test-runs", "original.jpg"),
        "corrected_url":        _image_url(row, "test-runs", "corrected.jpg"),
        "metrics":              row["metrics"],
        "boxes":                row["boxes"],
    }


# ── Metrics export ─────────────────────────────────────────────────────────────
def _export_body(rows: List[dict], fmt: str) -> Response:
    import metrics_export

    kind = (fmt or "csv").lower()
    if kind not in ("csv", "json"):
        raise HTTPException(400, detail="format must be 'csv' or 'json'.")
    if kind == "json":
        body = metrics_export.to_json(rows)
        media = "application/json"
        filename = "acra-metrics.json"
    else:
        body = metrics_export.to_csv(rows)
        media = "text/csv; charset=utf-8"
        filename = "acra-metrics.csv"
    return Response(
        content=body,
        media_type=media,
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )


def _remote_user_rows(table: str, user_id: str, page_size: int = 200) -> List[dict]:
    rows: List[dict] = []
    offset = 0
    while True:
        result = (
            _get_sb().table(table)
            .select("*")
            .eq("user_id", user_id)
            .order("created_at", desc=True)
            .order("job_id" if table == "jobs" else "run_id")
            .range(offset, offset + page_size - 1)
            .execute()
        )
        batch = result.data or []
        rows.extend(batch)
        if len(batch) < page_size:
            break
        offset += page_size
    return rows


async def _metrics_export_rows(request: Request) -> List[dict]:
    import metrics_export

    user_id = _extract_user_id(request)
    now = datetime.now(timezone.utc).isoformat()
    if USE_LOCAL:
        jobs = await _to_thread(local_store.list_jobs, DB_PATH, user_id)
        runs = await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id)
    else:
        jobs = await _to_thread(_remote_user_rows, "jobs", user_id)
        runs = await _to_thread(_remote_user_rows, "test_runs", user_id)

    rows = [
        metrics_export.metric_row("job", job)
        for job in jobs
        if (job.get("expires_at") or "") > now
    ]
    rows.extend(metrics_export.metric_row("test_run", run) for run in runs)
    rows.sort(key=lambda row: row.get("created_at") or "", reverse=True)
    return rows


# ── Routes ─────────────────────────────────────────────────────────────────────

@app.get("/")
def root():
    return {
        "status": "ok",
        "service": "ACRA Backend",
        "health": "/health",
        "docs": "/docs",
    }


@app.get('/device-engine', include_in_schema=False)
def device_engine(request: Request):
    _extract_user_id(request)
    from device_engine import engine_response
    return engine_response(SEG_MODEL_PATH)


@app.get("/health")
def health():
    return {
        "status":             "ok",
        "model_loaded":       _model_loaded,
        "model_path":         SEG_MODEL_PATH,
        "segmentation_ready": bool(SEG_MODEL_PATH and Path(SEG_MODEL_PATH).is_file()),
        "uptime_seconds":     round(time.time() - _startup_time, 1),
    }


@app.post("/process")
async def process_image(
    request:              Request,
    image:                UploadFile    = File(...),
    cvd_type:             str           = Form(...),
    severity:             float         = Form(...),
    conf_threshold:       float         = Form(...),
    use_segmentation:     int           = Form(1),
    seg_soft:             float         = Form(3.5),
    n_clusters:           Optional[int] = Form(None),
    seg_clusters_per_roi: Optional[int] = Form(None),
):
    user_id = _extract_user_id(request)

    img_np, params = await _validate_upload(
        image, cvd_type, severity, conf_threshold, seg_soft,
        use_segmentation, n_clusters, seg_clusters_per_roi, max_dim=1920,
    )
    severity             = params["severity"]
    conf_threshold       = params["conf_threshold"]
    seg_soft             = params["seg_soft"]
    use_seg_bool         = params["use_seg_bool"]
    n_clusters           = params["n_clusters"]
    seg_clusters_per_roi = params["seg_clusters_per_roi"]

    t0 = time.time()

    try:
        corrected_uint8, metrics, boxes = await _to_thread(
            _run_pipeline_sync,
            img_np, cvd_type, severity, conf_threshold,
            use_seg_bool, seg_soft, n_clusters, seg_clusters_per_roi,
        )
    except Exception as exc:
        raise HTTPException(500, detail=f"Pipeline error: {exc}")

    metrics["inference_ms"] = round((time.time() - t0) * 1000, 1)

    job_id     = str(uuid.uuid4())
    now        = datetime.now(timezone.utc)
    expires_at = now + timedelta(hours=JOB_EXPIRY_HOURS)

    row = {
        "job_id":               job_id,
        "user_id":              user_id,
        "cvd_type":             cvd_type,
        "severity":             severity,
        "conf_threshold":       conf_threshold,
        "use_segmentation":     use_seg_bool,
        "seg_soft":             seg_soft,
        "n_clusters":           n_clusters,
        "seg_clusters_per_roi": seg_clusters_per_roi if seg_clusters_per_roi is not None else 3,
        "created_at":           now.isoformat(),
        "expires_at":           expires_at.isoformat(),
        "metrics":              metrics,
        "boxes":                boxes,
    }
    try:
        row = await _persist_images_and_row(f"jobs/{job_id}", img_np, corrected_uint8, "jobs", row)
    except Exception as exc:
        raise HTTPException(500, detail=f"Failed to save job: {exc}")

    return _job_to_response(row)


@app.get("/metrics/export")
async def export_metrics(request: Request, format: str = Query("csv")):
    """Every stored image for this user.

    Failed pass flags and images with zero conflicts are included. Expired
    jobs are left out because their rows are already gone from the active list.
    """
    rows = await _metrics_export_rows(request)
    return _export_body(rows, format)


@app.get("/jobs")
async def list_jobs(request: Request):
    user_id = _extract_user_id(request)
    # No cleanup here any more. _purge_expired used to run first on EVERY visit
    # to Storage -- a select plus a delete against Supabase, plus a storage
    # delete per expired job -- and the list waited on all of it before a
    # single card could render. _purge_loop already runs the same cleanup in
    # the background every PURGE_INTERVAL_S. Expired jobs are simply filtered
    # out of the query below, so the user still never sees one.
    now = datetime.now(timezone.utc).isoformat()

    if USE_LOCAL:
        rows = await _to_thread(local_store.list_jobs, DB_PATH, user_id)
        return [_job_to_response(r) for r in rows if r["expires_at"] > now]

    def _query(uid=user_id):
        return (
            _get_sb().table("jobs")
            .select("*")
            .eq("user_id", uid)
            .gt("expires_at", now)
            .order("created_at", desc=True)
            .execute()
        )

    result = await _to_thread(_query)
    return [_job_to_response(r) for r in result.data]


@app.get("/jobs/{job_id}/metrics")
async def export_job_metrics(job_id: str, request: Request, format: str = Query("csv")):
    user_id = _extract_user_id(request)
    if USE_LOCAL:
        row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id)
    else:
        def _query(jid=job_id, uid=user_id):
            return (
                _get_sb().table("jobs")
                .select("*")
                .eq("job_id", jid)
                .eq("user_id", uid)
                .execute()
            )

        result = await _to_thread(_query)
        row = result.data[0] if result.data else None
    if not row or (row.get("expires_at") or "") <= datetime.now(timezone.utc).isoformat():
        raise HTTPException(404, detail="Job not found or has expired.")
    import metrics_export
    return _export_body([metrics_export.metric_row("job", row)], format)


@app.get("/jobs/{job_id}")
async def get_job(job_id: str, request: Request):
    user_id = _extract_user_id(request)

    if USE_LOCAL:
        row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id)
        if not row or _image_deadline(row) <= datetime.now(timezone.utc):
            raise HTTPException(404, detail="Job not found or has expired.")
        return _job_to_response(row)

    def _query(jid=job_id, uid=user_id):
        return (
            _get_sb().table("jobs")
            .select("*")
            .eq("job_id", jid)
            .eq("user_id", uid)
            .execute()
        )

    result = await _to_thread(_query)
    if not result.data or _image_deadline(result.data[0]) <= datetime.now(timezone.utc):
        raise HTTPException(404, detail="Job not found or has expired.")
    return _job_to_response(result.data[0])


@app.get("/images/{collection}/{record_id}/{filename}")
async def get_private_image(collection: str, record_id: str, filename: str, request: Request):
    user_id = _extract_user_id(request)
    if collection not in {"jobs", "test-runs"} or filename not in {"original.jpg", "corrected.jpg", "thumb.jpg"}:
        raise HTTPException(404, detail="Image not found or has expired.")
    table = "jobs" if collection == "jobs" else "test_runs"
    key = "job_id" if collection == "jobs" else "run_id"
    if USE_LOCAL:
        lookup = local_store.get_job if table == "jobs" else local_store.get_test_run
        row = await _to_thread(lookup, DB_PATH, record_id, user_id)
    else:
        def lookup():
            result = (_get_sb().table(table).select("*").eq(key, record_id)
                      .eq("user_id", user_id).execute())
            return result.data[0] if result.data else None
        row = await _to_thread(lookup)
    if not row or _image_deadline(row) <= datetime.now(timezone.utc):
        raise HTTPException(404, detail="Image not found or has expired.")
    # Derive the path from the owned record, never from a stored external URL.
    path = f"{collection}/{row[key]}/{filename}"
    try:
        if USE_LOCAL:
            data = await _to_thread((STATIC_DIR / path).read_bytes)
        else:
            data = await _to_thread(_get_sb().storage.from_(STORAGE_BUCKET).download, path)
    except FileNotFoundError:
        raise HTTPException(404, detail="Image not found or has expired.")
    except Exception:
        raise HTTPException(503, detail="Image storage is temporarily unavailable.")
    return Response(data, media_type="image/jpeg", headers={
        "Cache-Control": "private, no-store", "Vary": "Authorization",
    })


@app.delete("/jobs/{job_id}")
async def delete_job(job_id: str, request: Request):
    user_id = _extract_user_id(request)

    if USE_LOCAL:
        row = await _to_thread(local_store.get_job, DB_PATH, job_id, user_id)
        if not row:
            raise HTTPException(404, detail="Job not found.")
        await _to_thread(_delete_images, f"jobs/{job_id}")
        await _to_thread(local_store.delete_job, DB_PATH, job_id)
        return {"deleted": job_id}

    def _lookup(jid=job_id, uid=user_id):
        return (
            _get_sb().table("jobs")
            .select("job_id")
            .eq("job_id", jid)
            .eq("user_id", uid)
            .execute()
        )

    result = await _to_thread(_lookup)
    if not result.data:
        raise HTTPException(404, detail="Job not found.")

    def _delete(jid=job_id, uid=user_id):
        # The owner filter is repeated here deliberately. The lookup above
        # already refuses to continue for someone else's job, so this is belt
        # and braces -- but the backend talks to Supabase with the service-role
        # key, which carries BYPASSRLS and skips every row level security
        # policy. A delete statement with no owner filter therefore has NOTHING
        # behind it: any future caller reaching this line deletes whatever id
        # it was handed. Scope the statement itself, not just the path to it.
        _get_sb().table("jobs").delete().eq("job_id", jid).eq("user_id", uid).execute()

    await _to_thread(_delete_images, f"jobs/{job_id}")
    await _to_thread(_delete)
    return {"deleted": job_id}


@app.delete("/account")
async def delete_account(request: Request):
    """Erase everything belonging to the caller, then the login itself.

    The privacy policy promises erasure in writing, so this has to actually
    erase: the stored image FILES first, then the rows, then the auth user.
    Order matters -- delete the rows first and the job ids are gone, leaving
    orphaned images in the bucket that nothing points at and nobody will ever
    clean up.

    Deleting the auth user last means a failure part-way through leaves the
    account still usable and the request repeatable, rather than locking
    someone out of data that is still sitting there.
    """
    user_id = _extract_user_id(request)

    if USE_LOCAL:
        for row in await _to_thread(local_store.list_jobs, DB_PATH, user_id):
            await _to_thread(_delete_images, f"jobs/{row['job_id']}")
            await _to_thread(local_store.delete_job, DB_PATH, row["job_id"])
        for row in await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id):
            await _to_thread(_delete_images, f"test-runs/{row['run_id']}")
        await _to_thread(local_store.clear_test_runs, DB_PATH, user_id)
        return {"deleted": True, "jobs": "all", "note": "local mode: no auth user to remove"}

    sb = _get_sb()

    def _list_jobs(uid=user_id):
        return sb.table("jobs").select("job_id").eq("user_id", uid).execute()

    jobs = (await _to_thread(_list_jobs)).data or []
    for row in jobs:
        await _to_thread(_delete_images, f"jobs/{row['job_id']}")
    runs = await _to_thread(_remote_user_rows, "test_runs", user_id)
    for row in runs:
        await _to_thread(_delete_images, f"test-runs/{row['run_id']}")

    def _wipe_rows(uid=user_id):
        sb.table("jobs").delete().eq("user_id", uid).execute()
        sb.table("test_runs").delete().eq("user_id", uid).execute()

    await _to_thread(_wipe_rows)

    # Removing the auth user needs the service-role key, which this process
    # already holds. Without this the email stays registered and the person
    # cannot sign up again with it -- which is not deletion.
    def _drop_user(uid=user_id):
        sb.auth.admin.delete_user(uid)

    try:
        await _to_thread(_drop_user)
    except Exception as exc:
        print(f"[ACRA] Auth user delete failed for {user_id}: {exc}")
        raise HTTPException(
            500,
            detail="Your images and records were deleted, but the login itself "
                   "could not be removed. Please contact us so we can finish it.",
        )

    return {"deleted": True, "jobs_removed": len(jobs)}


# ── Test-runs ──────────────────────────────────────────────────────────────────

@app.post("/test-runs")
async def create_test_run(
    request:              Request,
    image:                UploadFile    = File(...),
    cvd_type:             str           = Form(...),
    severity:             float         = Form(...),
    conf_threshold:       float         = Form(...),
    use_segmentation:     int           = Form(1),
    seg_soft:             float         = Form(3.5),
    n_clusters:           Optional[int] = Form(None),
    seg_clusters_per_roi: Optional[int] = Form(None),
):
    user_id  = _extract_user_id(request)
    filename = image.filename or "image.jpg"

    img_np, params = await _validate_upload(
        image, cvd_type, severity, conf_threshold, seg_soft,
        use_segmentation, n_clusters, seg_clusters_per_roi,
    )
    severity             = params["severity"]
    conf_threshold       = params["conf_threshold"]
    seg_soft             = params["seg_soft"]
    use_seg_bool         = params["use_seg_bool"]
    n_clusters           = params["n_clusters"]
    seg_clusters_per_roi = params["seg_clusters_per_roi"]

    t0 = time.time()

    try:
        corrected_uint8, metrics, boxes = await _to_thread(
            _run_pipeline_sync,
            img_np, cvd_type, severity, conf_threshold,
            use_seg_bool, seg_soft, n_clusters, seg_clusters_per_roi,
        )
    except Exception as exc:
        raise HTTPException(500, detail=f"Pipeline error: {exc}")

    metrics["inference_ms"] = round((time.time() - t0) * 1000, 1)

    run_id = str(uuid.uuid4())
    now    = datetime.now(timezone.utc)

    row = {
        "run_id":               run_id,
        "user_id":              user_id,
        "filename":             filename,
        "cvd_type":             cvd_type,
        "severity":             severity,
        "conf_threshold":       conf_threshold,
        "use_segmentation":     use_seg_bool,
        "seg_soft":             seg_soft,
        "n_clusters":           n_clusters,
        "seg_clusters_per_roi": seg_clusters_per_roi if seg_clusters_per_roi is not None else 3,
        "created_at":           now.isoformat(),
        "metrics":              metrics,
        "boxes":                boxes,
        "de_improvement":       float(metrics.get("delta_e_improvement", 0.0)),
        "conflict_resolution":  float(metrics.get("conflict_resolution_rate", 0.0)),
        "naturalness":          float(metrics.get("naturalness_preservation", 0.0)),
        "conflicts_found":      int(metrics.get("conflicts_found", 0)),
        "boxes_detected":       int(metrics.get("boxes_detected", 0)),
        "inference_ms":         float(metrics.get("inference_ms", 0)),
        "pass_de":              bool(metrics.get("pass_de_improvement", False)),
        "pass_resolution":      bool(metrics.get("pass_resolution_rate", False)),
        "pass_naturalness":     bool(metrics.get("pass_naturalness", False)),
    }
    try:
        row = await _persist_images_and_row(
            f"test-runs/{run_id}", img_np, corrected_uint8, "test_runs", row,
        )
    except Exception as exc:
        raise HTTPException(500, detail=f"Failed to save test run: {exc}")

    return _run_to_response(row)


_ANALYTICS_COLS = (
    "run_id,filename,cvd_type,severity,conf_threshold,created_at,metrics,"
    "de_improvement,conflict_resolution,naturalness,"
    "pass_de,pass_resolution,pass_naturalness,conflicts_found,boxes_detected,inference_ms"
)


def _run_to_analytics(row: dict) -> Dict[str, Any]:
    return {
        "run_id":         row["run_id"],
        "filename":       row.get("filename"),
        "cvd_type":       row["cvd_type"],
        "severity":       row["severity"],
        "conf_threshold": row["conf_threshold"],
        "created_at":     row["created_at"],
        "metrics":        row.get("metrics") or {},
    }


@app.get("/test-runs/analytics")
async def test_analytics(request: Request, limit: int = 100, offset: int = 0):
    user_id = _extract_user_id(request)
    limit, offset = _page_bounds(limit, offset, default=100, maximum=200)

    if USE_LOCAL:
        rows = await _to_thread(local_store.analytics_rows, DB_PATH, user_id)
        page_rows = await _to_thread(local_store.analytics_page, DB_PATH, user_id, limit, offset)
    else:
        def _agg(uid=user_id):
            return (
                _get_sb().table("test_runs")
                .select("de_improvement,conflict_resolution,naturalness,pass_de,pass_resolution,pass_naturalness")
                .eq("user_id", uid)
                .execute()
            )

        def _page(uid=user_id, lim=limit, off=offset):
            return (
                _get_sb().table("test_runs")
                .select(_ANALYTICS_COLS)
                .eq("user_id", uid)
                .order("created_at", desc=True)
                .range(off, off + lim - 1)
                .execute()
            )

        agg_result, page_result = await asyncio.gather(_to_thread(_agg), _to_thread(_page))
        rows = agg_result.data
        page_rows = page_result.data

    if not rows:
        return {"total": 0, "limit": limit, "offset": offset, "runs": []}

    total = len(rows)

    def col(name):
        return [r[name] for r in rows if r.get(name) is not None]

    def avg(vals): return sum(vals) / len(vals) if vals else 0.0
    def mn(vals):  return min(vals) if vals else 0.0
    def mx(vals):  return max(vals) if vals else 0.0

    de_vals  = col("de_improvement")
    res_vals = col("conflict_resolution")
    nat_vals = col("naturalness")

    return {
        "total": total,
        "limit": limit,
        "offset": offset,
        "averages": {
            "de_improvement":      round(avg(de_vals),  2),
            "conflict_resolution": round(avg(res_vals), 4),
            "naturalness":         round(avg(nat_vals), 2),
        },
        "minimums": {
            "de_improvement":      round(mn(de_vals),  2),
            "conflict_resolution": round(mn(res_vals), 4),
            "naturalness":         round(mn(nat_vals), 2),
        },
        "maximums": {
            "de_improvement":      round(mx(de_vals),  2),
            "conflict_resolution": round(mx(res_vals), 4),
            "naturalness":         round(mx(nat_vals), 2),
        },
        "pass_rates": {
            "de_improvement":      round(sum(1 for r in rows if r.get("pass_de")) / total, 4),
            "conflict_resolution": round(sum(1 for r in rows if r.get("pass_resolution")) / total, 4),
            "naturalness":         round(sum(1 for r in rows if r.get("pass_naturalness")) / total, 4),
        },
        "targets": {
            "de_improvement":      15.0,
            "conflict_resolution": 0.80,
            "naturalness":         12.0,
        },
        "runs": [_run_to_analytics(r) for r in page_rows],
    }


@app.get("/test-runs")
async def list_test_runs(request: Request, limit: int = 50, offset: int = 0):
    user_id = _extract_user_id(request)
    limit, offset = _page_bounds(limit, offset, default=50, maximum=100)

    if USE_LOCAL:
        rows = await _to_thread(local_store.list_test_runs, DB_PATH, user_id, limit, offset)
        return [_run_to_response(r) for r in rows]

    def _query(uid=user_id, lim=limit, off=offset):
        return (
            _get_sb().table("test_runs")
            .select("*")
            .eq("user_id", uid)
            .order("created_at", desc=True)
            .range(off, off + lim - 1)
            .execute()
        )

    result = await _to_thread(_query)
    return [_run_to_response(r) for r in result.data]


@app.delete("/test-runs/{run_id}")
async def delete_test_run(run_id: str, request: Request):
    user_id = _extract_user_id(request)

    if USE_LOCAL:
        row = await _to_thread(local_store.get_test_run, DB_PATH, run_id, user_id)
        if not row:
            raise HTTPException(404, detail="Test run not found.")
        await _to_thread(_delete_images, f"test-runs/{run_id}")
        await _to_thread(local_store.delete_test_run, DB_PATH, run_id)
        return {"deleted": run_id}

    def _lookup(rid=run_id, uid=user_id):
        return (
            _get_sb().table("test_runs")
            .select("run_id")
            .eq("run_id", rid)
            .eq("user_id", uid)
            .execute()
        )

    result = await _to_thread(_lookup)
    if not result.data:
        raise HTTPException(404, detail="Test run not found.")

    def _delete(rid=run_id, uid=user_id):
        # Same reasoning as delete_job: the service-role key ignores row level
        # security, so this filter is the only thing scoping the statement.
        _get_sb().table("test_runs").delete().eq("run_id", rid).eq("user_id", uid).execute()

    await _to_thread(_delete_images, f"test-runs/{run_id}")
    await _to_thread(_delete)
    return {"deleted": run_id}


@app.delete("/test-runs")
async def clear_test_runs(request: Request):
    user_id = _extract_user_id(request)

    if USE_LOCAL:
        rows = await _to_thread(local_store.list_all_test_runs, DB_PATH, user_id)
        ids = [row["run_id"] for row in rows]
        for rid in ids:
            await _to_thread(_delete_images, f"test-runs/{rid}")
        await _to_thread(local_store.clear_test_runs, DB_PATH, user_id)
        return {"cleared": len(ids)}

    def _lookup(uid=user_id):
        return (
            _get_sb().table("test_runs")
            .select("run_id")
            .eq("user_id", uid)
            .execute()
        )

    result = await _to_thread(_lookup)

    def _clear(uid=user_id):
        _get_sb().table("test_runs").delete().eq("user_id", uid).execute()

    for r in result.data:
        await _to_thread(_delete_images, f"test-runs/{r['run_id']}")
    await _to_thread(_clear)
    return {"cleared": len(result.data)}


# ── Expiry cleanup ─────────────────────────────────────────────────────────────
def _purge_expired() -> None:
    if USE_LOCAL:
        try:
            local_store.purge_expired(DB_PATH, STATIC_DIR)
        except Exception as exc:
            print(f"[ACRA] Purge error: {exc}")
        return

    now = datetime.now(timezone.utc).isoformat()
    try:
        sb      = _get_sb()
        expired = sb.table("jobs").select("job_id").lte("expires_at", now).execute()
        for r in expired.data:
            _delete_images(f"jobs/{r['job_id']}")
            sb.table("jobs").delete().eq("job_id", r["job_id"]).execute()
        cutoff = (datetime.now(timezone.utc) - timedelta(hours=24)).isoformat()
        expired_runs = (sb.table("test_runs").select("run_id").lte("created_at", cutoff)
                        .neq("original_url", "").execute())
        for r in expired_runs.data:
            _delete_images(f"test-runs/{r['run_id']}")
            sb.table("test_runs").update({"original_url": "", "corrected_url": ""}).eq("run_id", r["run_id"]).execute()
    except Exception as exc:
        print(f"[ACRA] Purge error: {exc}")