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
 
 
 
 
 
 
bfc5e2a
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
# import cv2
# import numpy as np
# from PIL import Image
# import io
# import json
# from datetime import datetime
# from typing import List, Tuple, Dict, Optional
# from dataclasses import dataclass
# import time
# import os
# import warnings
# import gc
# from collections import OrderedDict

# # ============================================================================
# # CLOUD DEPLOYMENT OPTIMIZATIONS
# # ============================================================================
# IS_HF_SPACE = os.environ.get('SPACE_ID') is not None or os.environ.get('HF_SPACE') is not None
# IS_RENDER = os.environ.get('RENDER') is not None
# IS_CLOUD = IS_HF_SPACE or IS_RENDER

# # Memory limits for cloud
# MAX_IMAGE_SIZE = (1280, 960) if IS_CLOUD else (1920, 1440)
# MAX_CACHE_SIZE = 50 if IS_CLOUD else 100
# ENABLE_GC = IS_CLOUD  # Force garbage collection on cloud

# # Lazy imports for faster cold start
# _torch = None
# _torchvision = None
# _YOLO = None

# def _get_torch():
#     global _torch
#     if _torch is None:
#         import torch
#         _torch = torch
#         if IS_CLOUD:
#             _torch.set_num_threads(2)
#     return _torch

# def _get_torchvision():
#     global _torchvision
#     if _torchvision is None:
#         import torchvision
#         _torchvision = torchvision
#     return _torchvision

# def _get_yolo():
#     global _YOLO
#     if _YOLO is None:
#         try:
#             from ultralytics import YOLO
#             _YOLO = YOLO
#         except ImportError:
#             _YOLO = False
#     return _YOLO

# def _yolo_available():
#     yolo = _get_yolo()
#     return yolo is not False and yolo is not None

# warnings.filterwarnings('ignore')

# # Import optimized validators
# try:
#     from saddle_structure_validator import SaddleStructureValidator, SaddleStructure
#     STRUCTURE_VALIDATOR_AVAILABLE = True
# except ImportError:
#     STRUCTURE_VALIDATOR_AVAILABLE = False
#     SaddleStructure = None
#     print("[WARN] saddle_structure_validator not available")

# try:
#     from geometric_validator import OptimizedGeometricValidator, PhysicalDimensions, PixelToMMCalibrator
#     OPTIMIZED_VALIDATOR_AVAILABLE = True
# except ImportError:
#     OPTIMIZED_VALIDATOR_AVAILABLE = False
#     print("[WARN] geometric_validator not available")

# if IS_HF_SPACE:
#     print("[HF Space] Memory-optimized mode enabled")
# elif IS_RENDER:
#     print("[Render] Cloud-optimized mode enabled")


# @dataclass
# class SaddleROI:
#     """Saddle region of interest with rotation and structure info"""
#     id: int
#     bbox: Tuple[int, int, int, int]
#     crop: np.ndarray
#     center: Tuple[int, int]
#     area: int
#     angle: float
#     confidence: float
#     structure: Optional[any] = None
    
#     def to_dict(self):
#         result = {
#             'id': int(self.id),
#             'bbox': [int(x) for x in self.bbox],
#             'center': [int(self.center[0]), int(self.center[1])],
#             'area': int(self.area),
#             'angle': float(self.angle),
#             'confidence': float(self.confidence)
#         }
#         if self.structure is not None:
#             result['has_semicircle'] = bool(getattr(self.structure, 'has_semicircle', False))
#             result['has_middle_arc'] = bool(getattr(self.structure, 'has_middle_arc', False))
#             result['structure_confidence'] = float(getattr(self.structure, 'structure_confidence', 0.0))
#         return result
    
#     def cleanup(self):
#         """Free memory"""
#         if hasattr(self, 'crop'):
#             del self.crop
#         self.crop = None
#         self.structure = None


# @dataclass
# class SaddleInspectionResult:
#     """Inspection result for one saddle"""
#     saddle_id: int
#     status: str
#     similarity_score: float
#     confidence: float
#     feature_distance: float
#     detected: bool
    
#     def to_dict(self):
#         return {
#             'saddle_id': int(self.saddle_id),
#             'status': str(self.status),
#             'similarity_score': float(self.similarity_score),
#             'confidence': float(self.confidence),
#             'feature_distance': float(self.feature_distance),
#             'detected': bool(self.detected)
#         }


# @dataclass
# class BlockInspectionResult:
#     """Complete block inspection result"""
#     block_status: str
#     total_saddles: int
#     detected_saddles: int
#     defective_saddles: int
#     saddle_results: List[SaddleInspectionResult]
#     processing_time_ms: float
#     alignment_status: str
#     block_angle: float
    
#     def to_dict(self):
#         return {
#             'block_status': str(self.block_status),
#             'total_saddles': int(self.total_saddles),
#             'detected_saddles': int(self.detected_saddles),
#             'defective_saddles': int(self.defective_saddles),
#             'saddle_results': [r.to_dict() for r in self.saddle_results],
#             'processing_time_ms': float(self.processing_time_ms),
#             'alignment_status': str(self.alignment_status),
#             'block_angle': float(self.block_angle)
#         }


# class LRUCache:
#     """Thread-safe LRU cache with size limit"""
    
#     def __init__(self, max_size=100):
#         self.cache = OrderedDict()
#         self.max_size = max_size
    
#     def get(self, key):
#         if key in self.cache:
#             self.cache.move_to_end(key)
#             return self.cache[key]
#         return None
    
#     def put(self, key, value):
#         if key in self.cache:
#             self.cache.move_to_end(key)
#         self.cache[key] = value
#         if len(self.cache) > self.max_size:
#             self.cache.popitem(last=False)
    
#     def clear(self):
#         self.cache.clear()
#         if ENABLE_GC:
#             gc.collect()


# class YOLOOBBDetector:
#     """YOLO-OBB Detector with lazy loading and memory management"""
    
#     def __init__(self, model_path: Optional[str] = None):
#         self.model = None
#         self.model_loaded = False
#         self._model_path = model_path if model_path else 'yolo26n-obb.pt'
#         self._initialized = False
    
#     def _lazy_init(self):
#         if self._initialized:
#             return
#         self._initialized = True
        
#         if not _yolo_available():
#             print("⚠ YOLO not available")
#             return
        
#         YOLO = _get_yolo()
        
#         try:
#             self.model = YOLO(self._model_path)
#             self.model_loaded = True
#             print(f"βœ“ YOLO-OBB loaded: {self._model_path}")
#         except Exception as e:
#             try:
#                 fallback = 'yolo11n-obb.pt' if self._model_path == 'yolo26n-obb.pt' else 'yolo26n-obb.pt'
#                 self.model = YOLO(fallback)
#                 self.model_loaded = True
#                 print(f"βœ“ YOLO-OBB fallback: {fallback}")
#             except:
#                 print(f"βœ— YOLO load failed: {e}")
#                 self.model_loaded = False
    
#     @property
#     def available(self):
#         if not self._initialized:
#             self._lazy_init()
#         return self.model_loaded

#     def detect_saddles(self, image: np.ndarray, conf_threshold: float = 0.25) -> List[SaddleROI]:
#         """Detect saddles using YOLO-OBB with memory optimization"""
        
#         if not self.available or self.model is None:
#             return []
        
#         # Resize if too large
#         h, w = image.shape[:2]
#         if w > MAX_IMAGE_SIZE[0] or h > MAX_IMAGE_SIZE[1]:
#             scale = min(MAX_IMAGE_SIZE[0]/w, MAX_IMAGE_SIZE[1]/h)
#             new_w, new_h = int(w*scale), int(h*scale)
#             image_resized = cv2.resize(image, (new_w, new_h))
#         else:
#             image_resized = image
#             scale = 1.0
        
#         # Convert to grayscale for faster inference
#         if len(image_resized.shape) == 3:
#             gray = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)
#             gray_3ch = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
#         else:
#             gray_3ch = cv2.cvtColor(image_resized, cv2.COLOR_GRAY2BGR)
        
#         results = self.model(gray_3ch, conf=conf_threshold, verbose=False)
        
#         saddles = []
        
#         for result in results:
#             if hasattr(result, 'obb') and result.obb is not None:
#                 for i, obb in enumerate(result.obb):
#                     xyxyxyxy = obb.xyxyxyxy[0].cpu().numpy()
#                     conf = float(obb.conf[0])
                    
#                     # Scale back to original coordinates
#                     xyxyxyxy = xyxyxyxy / scale
                    
#                     angle = self._calculate_angle(xyxyxyxy)
                    
#                     x_coords = xyxyxyxy[:, 0]
#                     y_coords = xyxyxyxy[:, 1]
                    
#                     x_min, x_max = int(x_coords.min()), int(x_coords.max())
#                     y_min, y_max = int(y_coords.min()), int(y_coords.max())
                    
#                     w = x_max - x_min
#                     h = y_max - y_min
                    
#                     cx = int(np.mean(x_coords))
#                     cy = int(np.mean(y_coords))
                    
#                     # Crop from original image
#                     crop = image[y_min:y_max, x_min:x_max].copy()
#                     area = w * h
                    
#                     saddles.append(SaddleROI(
#                         id=i,
#                         bbox=(x_min, y_min, w, h),
#                         crop=crop,
#                         center=(cx, cy),
#                         area=area,
#                         angle=angle,
#                         confidence=conf
#                     ))
            
#             elif hasattr(result, 'boxes') and result.boxes is not None:
#                 for i, box in enumerate(result.boxes):
#                     xyxy = box.xyxy[0].cpu().numpy()
#                     conf = float(box.conf[0])
                    
#                     # Scale back
#                     xyxy = xyxy / scale
                    
#                     x_min, y_min, x_max, y_max = map(int, xyxy)
#                     w = x_max - x_min
#                     h = y_max - y_min
                    
#                     cx = (x_min + x_max) // 2
#                     cy = (y_min + y_max) // 2
                    
#                     crop = image[y_min:y_max, x_min:x_max].copy()
#                     area = w * h
                    
#                     saddles.append(SaddleROI(
#                         id=i,
#                         bbox=(x_min, y_min, w, h),
#                         crop=crop,
#                         center=(cx, cy),
#                         area=area,
#                         angle=0.0,
#                         confidence=conf
#                     ))
        
#         # Sort by position
#         saddles.sort(key=lambda s: (s.center[1], s.center[0]))
        
#         for i, saddle in enumerate(saddles):
#             saddle.id = i
        
#         print(f"βœ“ YOLO detected: {len(saddles)} saddles")
        
#         # Memory cleanup
#         if ENABLE_GC:
#             del gray_3ch, results
#             gc.collect()
        
#         return saddles
    
#     def _calculate_angle(self, xyxyxyxy: np.ndarray) -> float:
#         p1 = xyxyxyxy[0]
#         p2 = xyxyxyxy[1]
        
#         dx = p2[0] - p1[0]
#         dy = p2[1] - p1[1]
        
#         angle = np.degrees(np.arctan2(dy, dx))
        
#         if angle > 180:
#             angle -= 360
#         elif angle < -180:
#             angle += 360
        
#         return float(angle)
    
#     def cleanup(self):
#         """Release model from memory"""
#         if self.model is not None:
#             del self.model
#             self.model = None
#             self.model_loaded = False
#         if ENABLE_GC:
#             gc.collect()


# class GeometricSaddleDetector:
#     """Optimized geometric detector with better 4-saddle detection"""
    
#     def __init__(self, max_cache_size=None):
#         if max_cache_size is None:
#             max_cache_size = MAX_CACHE_SIZE
#         self._mask_cache = LRUCache(max_cache_size)
    
#     def detect_saddles(self, image: np.ndarray) -> List[SaddleROI]:
#         """Detect using improved geometric segmentation"""
        
#         print(f"[GeometricDetector] Input shape: {image.shape}")
        
#         h, w = image.shape[:2]
        
#         # Resize if too large
#         if w > MAX_IMAGE_SIZE[0] or h > MAX_IMAGE_SIZE[1]:
#             scale = min(MAX_IMAGE_SIZE[0]/w, MAX_IMAGE_SIZE[1]/h)
#             new_w, new_h = int(w*scale), int(h*scale)
#             image_work = cv2.resize(image, (new_w, new_h))
#             print(f"[GeometricDetector] Resized to {new_w}x{new_h}")
#         else:
#             image_work = image
#             scale = 1.0
        
#         # Detect circles with improved method
#         outer_circle, inner_circle = self._detect_circles_improved(image_work)
        
#         if outer_circle is None:
#             print("[GeometricDetector] βœ— Circle detection failed")
#             return []
        
#         ox, oy, or_ = outer_circle
#         ix, iy, ir = inner_circle
        
#         # Scale back to original
#         if scale != 1.0:
#             ox, oy = int(ox/scale), int(oy/scale)
#             or_, ir = int(or_/scale), int(ir/scale)
#             h, w = image.shape[:2]
        
#         print(f"[GeometricDetector] Outer: ({ox},{oy}) r={or_}, Inner: ({ix},{iy}) r={ir}")
        
#         # Validate
#         if or_ < 50 or or_ > min(h, w):
#             print(f"[GeometricDetector] βœ— Invalid outer radius: {or_}")
#             return []
        
#         if ir >= or_:
#             ir = int(or_ * 0.4)
#             print(f"[GeometricDetector] Adjusted inner radius to {ir}")
        
#         # Create annular mask
#         annular_mask = np.zeros((h, w), dtype=np.uint8)
#         cv2.circle(annular_mask, (ox, oy), or_, 255, -1)
#         cv2.circle(annular_mask, (ix, iy), ir, 0, -1)
        
#         mask_pixels = np.sum(annular_mask > 0)
#         print(f"[GeometricDetector] Annular mask pixels: {mask_pixels}")
        
#         if mask_pixels < 1000:
#             print(f"[GeometricDetector] βœ— Mask too small")
#             return []
        
#         # Find saddles using contour detection instead of fixed quadrants
#         saddles = self._detect_saddles_from_annular_region(image, annular_mask, (ox, oy), or_, ir)
        
#         print(f"[GeometricDetector] Total saddles detected: {len(saddles)}")
        
#         # Memory cleanup
#         if ENABLE_GC:
#             del annular_mask, image_work
#             gc.collect()
        
#         return saddles
    
#     def _detect_saddles_from_annular_region(
#         self, 
#         image: np.ndarray, 
#         annular_mask: np.ndarray,
#         center: Tuple[int, int],
#         outer_r: int,
#         inner_r: int
#     ) -> List[SaddleROI]:
#         """
#         Improved saddle detection using contour-based approach
#         """
#         h, w = annular_mask.shape
        
#         # Apply mask to image
#         if len(image.shape) == 3:
#             gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#         else:
#             gray = image
        
#         masked = cv2.bitwise_and(gray, gray, mask=annular_mask)
        
#         # Enhance contrast
#         masked = cv2.equalizeHist(masked)
        
#         # Edge detection on masked region
#         edges = cv2.Canny(masked, 50, 150)
        
#         # Find contours
#         contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
#         # Filter and group contours
#         valid_contours = []
#         for cnt in contours:
#             area = cv2.contourArea(cnt)
#             if area > 500:  # Minimum area threshold
#                 valid_contours.append(cnt)
        
#         if len(valid_contours) < 4:
#             # Fallback to quadrant-based detection
#             print("[GeometricDetector] Using quadrant fallback")
#             return self._detect_quadrant_based(image, annular_mask, center, outer_r, inner_r)
        
#         # Sort contours by position (left to right, top to bottom)
#         valid_contours = sorted(valid_contours, key=lambda c: (cv2.boundingRect(c)[1], cv2.boundingRect(c)[0]))
        
#         # Take top 4 contours
#         saddles = []
#         for idx, cnt in enumerate(valid_contours[:4]):
#             x, y, w_box, h_box = cv2.boundingRect(cnt)
            
#             # Validate size
#             if w_box < 10 or h_box < 10:
#                 continue
            
#             # Extract crop
#             crop = image[y:y+h_box, x:x+w_box].copy()
#             mask_crop = annular_mask[y:y+h_box, x:x+w_box].copy()
#             crop_masked = cv2.bitwise_and(crop, crop, mask=mask_crop)
            
#             # Calculate center
#             M = cv2.moments(cnt)
#             if M['m00'] != 0:
#                 cx = int(M['m10'] / M['m00'])
#                 cy = int(M['m01'] / M['m00'])
#             else:
#                 cx = x + w_box // 2
#                 cy = y + h_box // 2
            
#             area = int(M['m00'])
            
#             saddles.append(SaddleROI(
#                 id=idx,
#                 bbox=(x, y, w_box, h_box),
#                 crop=crop_masked,
#                 center=(cx, cy),
#                 area=area,
#                 angle=0.0,
#                 confidence=0.8  # Geometric detection confidence
#             ))
        
#         return saddles
    
#     def _detect_quadrant_based(
#         self,
#         image: np.ndarray,
#         annular_mask: np.ndarray,
#         center: Tuple[int, int],
#         outer_r: int,
#         inner_r: int
#     ) -> List[SaddleROI]:
#         """Fallback quadrant-based detection"""
        
#         h, w = annular_mask.shape
#         ox, oy = center
        
#         quadrants = [
#             (0, 90, "Top-Right"),
#             (90, 180, "Top-Left"),
#             (180, 270, "Bottom-Left"),
#             (270, 360, "Bottom-Right")
#         ]
        
#         saddles = []
        
#         for idx, (start_angle, end_angle, name) in enumerate(quadrants):
#             mask_key = (h, w, ox, oy, outer_r, inner_r, start_angle, end_angle)
            
#             sector_mask = self._mask_cache.get(mask_key)
#             if sector_mask is None:
#                 sector_mask = self._create_sector_mask(
#                     (h, w), (ox, oy), outer_r, inner_r, start_angle, end_angle
#                 )
#                 self._mask_cache.put(mask_key, sector_mask)
            
#             saddle_mask = cv2.bitwise_and(annular_mask, sector_mask)
            
#             ys, xs = np.where(saddle_mask > 0)
            
#             if len(xs) == 0 or len(ys) == 0:
#                 print(f"[GeometricDetector] ⚠ Quadrant {idx} ({name}): No pixels")
#                 continue
            
#             x_min, x_max = xs.min(), xs.max()
#             y_min, y_max = ys.min(), ys.max()
            
#             if (x_max - x_min) < 10 or (y_max - y_min) < 10:
#                 print(f"[GeometricDetector] ⚠ Quadrant {idx} ({name}): Box too small")
#                 continue
            
#             crop = image[y_min:y_max+1, x_min:x_max+1].copy()
#             mask_crop = saddle_mask[y_min:y_max+1, x_min:x_max+1].copy()
#             crop_masked = cv2.bitwise_and(crop, crop, mask=mask_crop)
            
#             cx = int(np.mean(xs))
#             cy = int(np.mean(ys))
#             area = np.sum(saddle_mask > 0)
            
#             saddles.append(SaddleROI(
#                 id=idx,
#                 bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
#                 crop=crop_masked,
#                 center=(cx, cy),
#                 area=area,
#                 angle=0.0,
#                 confidence=1.0
#             ))
        
#         return saddles
    
#     def _detect_circles_improved(self, image: np.ndarray) -> Tuple[Optional[Tuple], Optional[Tuple]]:
#         """Improved circle detection with multiple strategies"""
        
#         gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
#         h, w = gray.shape
        
#         # Strategy 1: Standard HoughCircles with optimized params
#         gray_blur = cv2.GaussianBlur(gray, (9, 9), 2)
        
#         minRadius = int(min(h, w) * 0.2)
#         maxRadius = int(min(h, w) * 0.7)
        
#         # Try multiple parameter sets
#         param_sets = [
#             (80, 25),  # Standard
#             (60, 30),  # More lenient
#             (100, 20), # More strict
#         ]
        
#         for param1, param2 in param_sets:
#             circles = cv2.HoughCircles(
#                 gray_blur,
#                 cv2.HOUGH_GRADIENT,
#                 dp=1.0,
#                 minDist=80,
#                 param1=param1,
#                 param2=param2,
#                 minRadius=minRadius,
#                 maxRadius=maxRadius
#             )
            
#             if circles is not None and len(circles[0]) >= 1:
#                 circles = np.round(circles[0, :]).astype(int)
#                 circles = sorted(circles, key=lambda c: c[2], reverse=True)
#                 outer = tuple(circles[0])
#                 inner_radius = int(outer[2] * 0.4)
#                 inner = (outer[0], outer[1], inner_radius)
#                 print(f"βœ“ HoughCircles success (param1={param1}, param2={param2})")
#                 return outer, inner
        
#         # Strategy 2: Contour-based detection
#         print("β†’ Using contour fallback")
#         edges = cv2.Canny(gray_blur, 30, 100)
        
#         # Dilate to connect edges
#         kernel = np.ones((3, 3), np.uint8)
#         edges = cv2.dilate(edges, kernel, iterations=2)
        
#         contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
#         if contours:
#             # Find largest contour
#             largest = max(contours, key=cv2.contourArea)
#             (cx, cy), radius = cv2.minEnclosingCircle(largest)
            
#             center_x, center_y = int(cx), int(cy)
#             outer_radius = int(radius * 0.85)
#             inner_radius = int(outer_radius * 0.4)
            
#             print(f"βœ“ Contour-based: center=({center_x},{center_y}), radius={outer_radius}")
#             return ((center_x, center_y, outer_radius), (center_x, center_y, inner_radius))
        
#         # Strategy 3: Dimension-based estimate
#         center_x, center_y = w // 2, h // 2
#         outer_radius = min(w, h) // 2 - 50
#         inner_radius = int(outer_radius * 0.4)
#         print(f"β†’ Using dimension estimate: center=({center_x},{center_y}), radius={outer_radius}")
#         return ((center_x, center_y, outer_radius), (center_x, center_y, inner_radius))
    
#     def _create_sector_mask(self, shape, center, outer_r, inner_r, start_angle, end_angle):
#         """Create sector mask with caching"""
        
#         h, w = shape
#         mask = np.zeros((h, w), dtype=np.uint8)
        
#         y, x = np.ogrid[:h, :w]
#         dx = x - center[0]
#         dy = y - center[1]
        
#         angles = np.rad2deg(np.arctan2(dy, dx)) % 360
#         radius = np.sqrt(dx**2 + dy**2)
        
#         if start_angle < end_angle:
#             angle_mask = (angles >= start_angle) & (angles < end_angle)
#         else:
#             angle_mask = (angles >= start_angle) | (angles < end_angle)
        
#         radius_mask = (radius >= inner_r) & (radius <= outer_r)
#         sector = angle_mask & radius_mask
#         mask[sector] = 255
        
#         return mask
    
#     def cleanup(self):
#         """Release cache"""
#         self._mask_cache.clear()


# class AlignmentCorrector:
#     """Affine transformation for rotation correction"""
    
#     @staticmethod
#     def correct_rotation(image: np.ndarray, angle: float) -> np.ndarray:
#         h, w = image.shape[:2]
#         center = (w // 2, h // 2)
        
#         M = cv2.getRotationMatrix2D(center, -angle, 1.0)
        
#         cos = np.abs(M[0, 0])
#         sin = np.abs(M[0, 1])
        
#         new_w = int((h * sin) + (w * cos))
#         new_h = int((h * cos) + (w * sin))
        
#         M[0, 2] += (new_w / 2) - center[0]
#         M[1, 2] += (new_h / 2) - center[1]
        
#         rotated = cv2.warpAffine(image, M, (new_w, new_h), 
#                                  flags=cv2.INTER_LINEAR,
#                                  borderMode=cv2.BORDER_CONSTANT,
#                                  borderValue=(0, 0, 0))
        
#         return rotated
    
#     @staticmethod
#     def correct_saddle(saddle: SaddleROI) -> np.ndarray:
#         if abs(saddle.angle) < 1.0:
#             return saddle.crop
#         return AlignmentCorrector.correct_rotation(saddle.crop, saddle.angle)


# class CNNFeatureExtractor:
#     """ResNet-18 feature extraction with memory optimization"""
    
#     def __init__(self, onnx_path: str = "resnet18_features.onnx"):
#         self.onnx_path = onnx_path
#         self.session = None
#         self.model = None
#         self.device = None
#         self.feature_dim = 1024
#         self._initialized = False
    
#     def _lazy_init(self):
#         if self._initialized:
#             return
#         self._initialized = True
        
#         # Use PyTorch with fused features
#         self._init_pytorch_model()
    
#     def _init_pytorch_model(self):
#         torch = _get_torch()
#         torchvision = _get_torchvision()
#         from torchvision.models import resnet18, ResNet18_Weights
#         import torch.nn as nn
        
#         self.device = torch.device('cpu')
#         weights = ResNet18_Weights.IMAGENET1K_V1
#         base_model = resnet18(weights=weights)
        
#         class FeatureFusionModel(nn.Module):
#             def __init__(self, base):
#                 super().__init__()
#                 self.conv1 = base.conv1
#                 self.bn1 = base.bn1
#                 self.relu = base.relu
#                 self.maxpool = base.maxpool
#                 self.layer1 = base.layer1
#                 self.layer2 = base.layer2
#                 self.layer3 = base.layer3
#                 self.layer4 = base.layer4
#                 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
#                 self.maxpool_global = nn.AdaptiveMaxPool2d((1, 1))

#             def forward(self, x):
#                 x = self.conv1(x)
#                 x = self.bn1(x)
#                 x = self.relu(x)
#                 x = self.maxpool(x)
#                 x = self.layer1(x)
#                 x = self.layer2(x)
#                 l3 = self.layer3(x)
#                 l4 = self.layer4(l3)
                
#                 f3_avg = self.avgpool(l3).view(l3.size(0), -1)
#                 f3_max = self.maxpool_global(l3).view(l3.size(0), -1)
#                 f4_avg = self.avgpool(l4).view(l4.size(0), -1)
                
#                 return torch.cat([f3_avg, f3_max, f4_avg], dim=1)

#         self.model = FeatureFusionModel(base_model)
#         self.model.to(self.device)
#         self.model.eval()
#         print(f"βœ“ PyTorch FeatureFusion ResNet-18 (dim={self.feature_dim})")
    
#     def _preprocess_image(self, image: np.ndarray) -> np.ndarray:
#         if image is None or image.size == 0:
#             return np.zeros((3, 224, 224), dtype=np.float32)
        
#         if len(image.shape) == 2:
#             image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
#         elif len(image.shape) == 3 and image.shape[2] == 4:
#             image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGB)
#         elif len(image.shape) == 3 and image.shape[2] == 3:
#             image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        
#         image = cv2.resize(image, (224, 224))
        
#         image = image.astype(np.float32) / 255.0
#         mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
#         std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
#         image = (image - mean) / std
        
#         image = image.transpose(2, 0, 1)
        
#         return image
    
#     def extract_features(self, image: np.ndarray) -> np.ndarray:
#         self._lazy_init()
#         batch = self._preprocess_image(image)[np.newaxis, ...]
#         features = self.extract_batch(batch)
#         return features[0]
    
#     def extract_batch(self, images: List[np.ndarray]) -> np.ndarray:
#         self._lazy_init()
        
#         if isinstance(images, np.ndarray) and len(images.shape) == 4:
#             batch = images.astype(np.float32)
#         else:
#             preprocessed = [self._preprocess_image(img) for img in images]
#             batch = np.stack(preprocessed, axis=0).astype(np.float32)
        
#         torch = _get_torch()
#         batch_tensor = torch.from_numpy(batch).to(self.device)
#         with torch.no_grad():
#             features = self.model(batch_tensor)
#         features = features.squeeze(-1).squeeze(-1).cpu().numpy()
        
#         norms = np.linalg.norm(features, axis=1, keepdims=True) + 1e-8
#         features = features / norms
        
#         # Memory cleanup
#         if ENABLE_GC:
#             del batch_tensor
#             gc.collect()
        
#         return features
    
#     def compute_similarity(self, features1: np.ndarray, features2: np.ndarray) -> float:
#         similarity = np.dot(features1, features2) / (
#             np.linalg.norm(features1) * np.linalg.norm(features2) + 1e-8
#         )
#         return float(np.clip(similarity, 0, 1))
    
#     def cleanup(self):
#         """Release model from memory"""
#         if self.model is not None:
#             del self.model
#             self.model = None
#         if ENABLE_GC:
#             gc.collect()


# class GeometricConstraintValidator:
#     """Validate saddle positions using geometric constraints"""
    
#     def __init__(self, expected_count: int = 4):
#         self.expected_count = expected_count
#         self.reference_positions = None
#         self.reference_distances = {}
    
#     def set_reference_positions(self, saddles: List[SaddleROI]):
#         if len(saddles) != self.expected_count:
#             print(f"⚠ Reference has {len(saddles)} saddles, expected {self.expected_count}")
#             return False
        
#         centers = [s.center for s in saddles]
        
#         centroid = (
#             int(np.mean([c[0] for c in centers])),
#             int(np.mean([c[1] for c in centers]))
#         )
        
#         self.reference_positions = [
#             (c[0] - centroid[0], c[1] - centroid[1]) for c in centers
#         ]
        
#         self.reference_distances = {}
#         for i in range(len(saddles)):
#             for j in range(i+1, len(saddles)):
#                 dist = np.linalg.norm(
#                     np.array(saddles[i].center) - np.array(saddles[j].center)
#                 )
#                 self.reference_distances[(i, j)] = dist
        
#         print(f"βœ“ Reference geometry learned: {len(saddles)} saddles")
#         return True
    
#     def infer_missing_saddles(
#         self, 
#         detected_saddles: List[SaddleROI],
#         image: np.ndarray
#     ) -> List[SaddleROI]:
#         if len(detected_saddles) >= self.expected_count:
#             return detected_saddles
        
#         if self.reference_positions is None:
#             print("⚠ No reference geometry")
#             return detected_saddles
        
#         if len(detected_saddles) < 2:
#             print("⚠ Need at least 2 saddles to infer")
#             return detected_saddles
        
#         centers = [s.center for s in detected_saddles]
#         centroid = (
#             int(np.mean([c[0] for c in centers])),
#             int(np.mean([c[1] for c in centers]))
#         )
        
#         scale = self._estimate_scale(detected_saddles)
        
#         detected_ids = {s.id for s in detected_saddles}
#         all_saddles = list(detected_saddles)
        
#         for expected_id in range(self.expected_count):
#             if expected_id not in detected_ids:
#                 rel_x, rel_y = self.reference_positions[expected_id]
                
#                 expected_x = int(centroid[0] + rel_x * scale)
#                 expected_y = int(centroid[1] + rel_y * scale)
                
#                 crop_size = 100
                
#                 x_min = max(0, expected_x - crop_size // 2)
#                 y_min = max(0, expected_y - crop_size // 2)
#                 x_max = min(image.shape[1], expected_x + crop_size // 2)
#                 y_max = min(image.shape[0], expected_y + crop_size // 2)
                
#                 crop = image[y_min:y_max, x_min:x_max].copy()
                
#                 inferred = SaddleROI(
#                     id=expected_id,
#                     bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
#                     crop=crop,
#                     center=(expected_x, expected_y),
#                     area=(x_max - x_min) * (y_max - y_min),
#                     angle=0.0,
#                     confidence=0.0
#                 )
                
#                 all_saddles.append(inferred)
#                 print(f"  βš™ Inferred Saddle {expected_id} at ({expected_x}, {expected_y})")
        
#         all_saddles.sort(key=lambda s: s.id)
        
#         return all_saddles
    
#     def _estimate_scale(self, saddles: List[SaddleROI]) -> float:
#         if len(saddles) < 2 or not self.reference_distances:
#             return 1.0
        
#         if len(saddles) >= 2:
#             s0, s1 = saddles[0], saddles[1]
#             current_dist = np.linalg.norm(
#                 np.array(s0.center) - np.array(s1.center)
#             )
            
#             key = (min(s0.id, s1.id), max(s0.id, s1.id))
#             if key in self.reference_distances:
#                 ref_dist = self.reference_distances[key]
#                 scale = current_dist / ref_dist
#                 return scale
        
#         return 1.0
    
#     def validate_geometry(self, saddles: List[SaddleROI], tolerance: float = 0.05) -> Tuple[bool, str]:
#         if len(saddles) != self.expected_count:
#             return False, f"Expected {self.expected_count} saddles, got {len(saddles)}"
        
#         if self.reference_distances is None or not self.reference_distances:
#             return True, "No reference geometry to validate"
        
#         sorted_saddles = sorted(saddles, key=lambda s: s.id)
#         centers = [np.array(s.center) for s in sorted_saddles]
        
#         # Collinearity check
#         if len(centers) >= 3:
#             v1 = centers[1] - centers[0]
#             for i in range(2, len(centers)):
#                 v2 = centers[i] - centers[0]
#                 cross = abs(v1[0] * v2[1] - v1[1] * v2[0])
#                 line_length = np.linalg.norm(v1) * np.linalg.norm(v2)
#                 if line_length > 0:
#                     deviation = cross / line_length
#                     if deviation > 0.1:
#                         return False, f"Saddles not collinear (deviation: {deviation:.2f})"
        
#         # Distance validation
#         for i in range(len(sorted_saddles) - 1):
#             s0, s1 = sorted_saddles[i], sorted_saddles[i + 1]
#             current_dist = np.linalg.norm(centers[i + 1] - centers[i])
            
#             key = (min(s0.id, s1.id), max(s0.id, s1.id))
#             if key in self.reference_distances:
#                 ref_dist = self.reference_distances[key]
#                 if ref_dist > 0:
#                     deviation = abs(current_dist - ref_dist) / ref_dist
#                     if deviation > tolerance:
#                         return False, f"Distance S{s0.id}-S{s1.id} off by {deviation*100:.1f}%"
        
#         return True, "Geometry valid"


# class MultiReferenceManager:
#     """Manage multiple golden template images with memory optimization"""
    
#     def __init__(self, feature_extractor: CNNFeatureExtractor):
#         self.feature_extractor = feature_extractor
#         self.references = []
#         self.max_references = 20 if not IS_CLOUD else 10
        
#     def add_reference(self, image: np.ndarray, saddles: List[SaddleROI]) -> bool:
#         if len(saddles) != 4:
#             print(f"⚠ Reference must have 4 saddles, got {len(saddles)}")
#             return False
        
#         # Limit number of references
#         if len(self.references) >= self.max_references:
#             print(f"⚠ Max references ({self.max_references}) reached, removing oldest")
#             old_ref = self.references.pop(0)
#             # Cleanup
#             if ENABLE_GC:
#                 del old_ref
#                 gc.collect()
        
#         features_list = []
        
#         for saddle in saddles:
#             aligned_crop = AlignmentCorrector.correct_saddle(saddle)
#             features = self.feature_extractor.extract_features(aligned_crop)
#             features_list.append(features)
        
#         # Compress image for storage
#         if image.shape[0] > 800 or image.shape[1] > 800:
#             scale = min(800/image.shape[1], 800/image.shape[0])
#             new_w, new_h = int(image.shape[1]*scale), int(image.shape[0]*scale)
#             image_stored = cv2.resize(image, (new_w, new_h))
#         else:
#             image_stored = image
        
#         self.references.append({
#             'image': image_stored,
#             'saddles': saddles,
#             'features': features_list
#         })
        
#         print(f"βœ“ Reference {len(self.references)} added")
#         return True
    
#     def match_saddle(self, saddle: SaddleROI) -> Tuple[float, float]:
#         if not self.references:
#             return 0.0, 999.0
        
#         aligned_crop = AlignmentCorrector.correct_saddle(saddle)
#         test_features = self.feature_extractor.extract_features(aligned_crop)
        
#         similarities = []
#         distances = []
        
#         for ref in self.references:
#             if saddle.id < len(ref['features']):
#                 ref_features = ref['features'][saddle.id]
                
#                 sim = self.feature_extractor.compute_similarity(test_features, ref_features)
#                 dist = np.linalg.norm(test_features - ref_features)
                
#                 similarities.append(sim)
#                 distances.append(dist)
        
#         if similarities:
#             best_sim = max(similarities)
#             avg_dist = np.mean(distances)
#             return best_sim, avg_dist
        
#         return 0.0, 999.0
    
#     def get_reference_count(self) -> int:
#         return len(self.references)

#     def get_references(self) -> List[str]:
#         refs = []
#         for ref in self.references:
#             try:
#                 _, buffer = cv2.imencode('.jpg', ref['image'], [cv2.IMWRITE_JPEG_QUALITY, 50])
#                 import base64
#                 img_str = base64.b64encode(buffer).decode('utf-8')
#                 refs.append(f"data:image/jpeg;base64,{img_str}")
#             except:
#                 continue
#         return refs
    
#     def cleanup(self):
#         """Release all references"""
#         self.references.clear()
#         if ENABLE_GC:
#             gc.collect()


# class AdvancedBlockInspector:
#     """
#     Advanced Engine Block Inspector - CLOUD OPTIMIZED
    
#     Memory leak fixes:
#     - LRU caching with limits
#     - Automatic cleanup after processing
#     - Garbage collection triggers
#     - Reference counting limits
    
#     Improved 4-saddle detection:
#     - Contour-based detection
#     - Multiple circle detection strategies
#     - Structure validation integration
#     - Geometric validator integration
#     """
    
#     def __init__(self, yolo_model_path: Optional[str] = None, onnx_path: str = "resnet18_features.onnx"):
#         self.yolo_detector = YOLOOBBDetector(yolo_model_path)
#         self.geometric_detector = GeometricSaddleDetector()
        
#         self.cnn_extractor = CNNFeatureExtractor(onnx_path=onnx_path)
        
#         self.reference_manager = MultiReferenceManager(self.cnn_extractor)
        
#         # Use optimized validator if available
#         if OPTIMIZED_VALIDATOR_AVAILABLE:
#             self.geo_validator = OptimizedGeometricValidator(expected_count=4)
#             self.use_optimized_validator = True
#             print("βœ“ Optimized Validator: RANSAC + Physical Dims")
#         else:
#             self.geo_validator = GeometricConstraintValidator(expected_count=4)
#             self.use_optimized_validator = False
        
#         # Structure validator
#         self.structure_validator = None
#         if STRUCTURE_VALIDATOR_AVAILABLE:
#             self.structure_validator = SaddleStructureValidator(
#                 arc_center_tolerance=0.05,
#                 min_arc_length_ratio=0.6,
#                 min_structure_confidence=0.65
#             )
#             print("βœ“ Structure Validator: Semicircle + Middle Arc")
        
#         self.config = {
#             'expected_saddles': 4,
#             'similarity_threshold': 0.88,
#             'use_yolo': self.yolo_detector.model_loaded,
#             'use_geometric_fallback': True,
#             'use_alignment_correction': True,
#             'infer_missing_saddles': True,
#             'yolo_confidence': 0.25,
#             'use_geometry_validation': True,
#             'use_structure_validation': STRUCTURE_VALIDATOR_AVAILABLE,
#             'use_optimized_validator': self.use_optimized_validator,
#             'min_brightness': 20.0,
#         }
        
#         # Memory tracking
#         self.last_saddles = []
#         self.last_image = None
        
#         print("[OK] Advanced Inspector initialized (Cloud-Optimized)")
#         print(f"  YOLO-OBB: {'Enabled' if self.config['use_yolo'] else 'Disabled'}")
#         print(f"  Max cache size: {MAX_CACHE_SIZE}")
#         print(f"  GC enabled: {ENABLE_GC}")
    
#     def add_reference_image(self, image: np.ndarray) -> bool:
#         """Add a golden template image"""
        
#         try:
#             # Quality check
#             gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
#             brightness = np.mean(gray)
#             if brightness < 20:
#                 print(f"βœ— Reference too dark (brightness: {brightness:.1f})")
#                 return False
            
#             # Detect saddles
#             if self.config['use_yolo']:
#                 saddles = self.yolo_detector.detect_saddles(
#                     image, conf_threshold=self.config['yolo_confidence']
#                 )
#             else:
#                 saddles = []
            
#             if len(saddles) < self.config['expected_saddles'] and self.config['use_geometric_fallback']:
#                 print("β†’ Falling back to geometric detection")
#                 saddles = self.geometric_detector.detect_saddles(image)
            
#             # Validate with structure validator
#             if self.structure_validator and len(saddles) > 0:
#                 for saddle in saddles:
#                     if saddle.crop is not None and saddle.crop.size > 0:
#                         saddle.structure = self.structure_validator.validate_structure(saddle.crop)
            
#             # Use optimized validator to refine
#             if self.use_optimized_validator and hasattr(self.geo_validator, 'validate_and_refine'):
#                 saddles, _ = self.geo_validator.validate_and_refine(saddles, image)
            
#             if len(saddles) != self.config['expected_saddles']:
#                 print(f"βœ— Reference failed: {len(saddles)}/{self.config['expected_saddles']} saddles")
#                 return False
            
#             success = self.reference_manager.add_reference(image, saddles)
            
#             if success and self.reference_manager.get_reference_count() == 1:
#                 self.geo_validator.set_reference_positions(saddles)
            
#             # Cleanup
#             self._cleanup_after_processing()
            
#             return success
            
#         except Exception as e:
#             print(f"βœ— Reference error: {e}")
#             import traceback
#             traceback.print_exc()
#             return False
    
#     def inspect_block(self, image: np.ndarray) -> BlockInspectionResult:
#         """Inspect engine block with memory optimization"""
        
#         start_time = time.time()
        
#         try:
#             # Quality check
#             gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
#             brightness = np.mean(gray)
#             if brightness < 15:
#                 return BlockInspectionResult(
#                     block_status='WASTE_IMAGE',
#                     total_saddles=self.config['expected_saddles'],
#                     detected_saddles=0,
#                     defective_saddles=0,
#                     saddle_results=[],
#                     processing_time_ms=(time.time() - start_time) * 1000,
#                     alignment_status='REJECTED_DARK',
#                     block_angle=0.0
#                 )

#             # Resize if needed
#             h, w = image.shape[:2]
#             if w > 800 or h > 600:
#                 image = cv2.resize(image, (640, 480))
                
#             # Detect saddles
#             if self.config['use_yolo']:
#                 saddles = self.yolo_detector.detect_saddles(
#                     image, conf_threshold=self.config['yolo_confidence']
#                 )
#             else:
#                 saddles = []
            
#             if len(saddles) < self.config['expected_saddles'] and self.config['use_geometric_fallback']:
#                 print("β†’ Falling back to geometric detection")
#                 saddles = self.geometric_detector.detect_saddles(image)
            
#             detected_count = len(saddles)
            
#             # Validate and refine with optimized validator
#             if self.use_optimized_validator and hasattr(self.geo_validator, 'validate_and_refine'):
#                 saddles, refine_report = self.geo_validator.validate_and_refine(saddles, image)
#                 print(f"  Refined: {refine_report}")
#             elif len(saddles) < self.config['expected_saddles'] and self.config['infer_missing_saddles']:
#                 print(f"  Inferring {self.config['expected_saddles'] - len(saddles)} missing saddles")
#                 saddles = self.geo_validator.infer_missing_saddles(saddles, image)
            
#             # Structure validation
#             if self.structure_validator and self.config.get('use_structure_validation', False):
#                 for saddle in saddles:
#                     if saddle.crop is not None and saddle.crop.size > 0:
#                         saddle.structure = self.structure_validator.validate_structure(saddle.crop)
            
#             # Validate count
#             if len(saddles) != self.config['expected_saddles']:
#                 alignment_status = f"ERROR: {len(saddles)}/{self.config['expected_saddles']} saddles"
#                 return self._error_result(alignment_status, 0.0, saddles, detected_count)
            
#             # Geometry validation
#             if self.config.get('use_geometry_validation', True):
#                 is_valid, reason = self.geo_validator.validate_geometry(saddles, 0.05)
#                 if not is_valid:
#                     return self._error_result(f"GEOMETRY: {reason}", 0.0, saddles, detected_count)
            
#             alignment_status = "OK"
#             block_angle = np.mean([s.angle for s in saddles])
            
#             # Batch feature extraction
#             aligned_crops = [AlignmentCorrector.correct_saddle(s) for s in saddles]
#             batch_features = self.cnn_extractor.extract_batch(aligned_crops)
            
#             # Compare against references
#             saddle_results = []
#             for i, saddle in enumerate(saddles):
#                 test_features = batch_features[i]
#                 best_sim = 0.0
#                 avg_dist = 999.0
                
#                 for ref in self.reference_manager.references:
#                     if saddle.id < len(ref['features']):
#                         ref_features = ref['features'][saddle.id]
#                         sim = self.cnn_extractor.compute_similarity(test_features, ref_features)
#                         dist = np.linalg.norm(test_features - ref_features)
#                         if sim > best_sim:
#                             best_sim = sim
#                             avg_dist = dist
                
#                 status = 'PERFECT' if best_sim >= self.config['similarity_threshold'] else 'DEFECTIVE'
#                 saddle_results.append(SaddleInspectionResult(
#                     saddle_id=saddle.id,
#                     status=status,
#                     similarity_score=best_sim,
#                     confidence=best_sim,
#                     feature_distance=avg_dist,
#                     detected=saddle.confidence > 0.0
#                 ))
            
#             # Block decision
#             defective_count = sum(1 for r in saddle_results if r.status == 'DEFECTIVE')
#             avg_sim = np.mean([r.similarity_score for r in saddle_results]) if saddle_results else 0
            
#             if defective_count == self.config['expected_saddles'] and avg_sim < 0.70:
#                 block_status = 'WASTE_IMAGE'
#             elif detected_count == 0:
#                 if avg_sim < 0.75:
#                     block_status = 'WASTE_IMAGE'
#                 else:
#                     block_status = 'DEFECTIVE'
#             else:
#                 block_status = 'DEFECTIVE' if defective_count > 0 else 'PERFECT'
            
#             processing_time = (time.time() - start_time) * 1000
            
#             self.last_saddles = saddles
#             self.last_image = image
            
#             result = BlockInspectionResult(
#                 block_status=block_status,
#                 total_saddles=self.config['expected_saddles'],
#                 detected_saddles=detected_count,
#                 defective_saddles=defective_count,
#                 saddle_results=saddle_results,
#                 processing_time_ms=processing_time,
#                 alignment_status=alignment_status,
#                 block_angle=block_angle
#             )
            
#             # Cleanup
#             self._cleanup_after_processing()
            
#             return result
            
#         except Exception as e:
#             print(f"βœ— Inspection error: {e}")
#             import traceback
#             traceback.print_exc()
#             return self._error_result(str(e), 0.0, [], 0)

#     def get_reference_images(self) -> List[str]:
#         return self.reference_manager.get_references()
    
#     def _error_result(self, message: str, angle: float, saddles: List, detected_count: int) -> BlockInspectionResult:
#         self.last_saddles = saddles
        
#         return BlockInspectionResult(
#             block_status='ERROR',
#             total_saddles=self.config['expected_saddles'],
#             detected_saddles=detected_count,
#             defective_saddles=0,
#             saddle_results=[],
#             processing_time_ms=0.0,
#             alignment_status=message,
#             block_angle=angle
#         )
    
#     def visualize_results(
#         self,
#         original_image: np.ndarray,
#         saddles: List[SaddleROI],
#         results: List[SaddleInspectionResult]
#     ) -> np.ndarray:
#         """Create detailed visualization"""
        
#         vis = original_image.copy()
        
#         for saddle, result in zip(saddles, results):
#             if not result.detected:
#                 color = (255, 165, 0)  # Orange
#             elif result.status == 'PERFECT':
#                 color = (0, 255, 0)  # Green
#             else:
#                 color = (0, 0, 255)  # Red
            
#             x, y, w, h = saddle.bbox
#             cv2.rectangle(vis, (x, y), (x+w, y+h), color, 3)
            
#             cx, cy = saddle.center
#             cv2.circle(vis, (cx, cy), 10, color, -1)
            
#             if abs(saddle.angle) > 1.0:
#                 rad = np.deg2rad(saddle.angle)
#                 end_x = int(cx + 30 * np.cos(rad))
#                 end_y = int(cy + 30 * np.sin(rad))
#                 cv2.arrowedLine(vis, (cx, cy), (end_x, end_y), color, 3)
            
#             detection_marker = "" if result.detected else "βš™"
#             label = f"{detection_marker} S{saddle.id}: {result.status}"
#             sim_text = f"{result.similarity_score:.3f}"
#             angle_text = f"{saddle.angle:.1f}Β°"
            
#             cv2.rectangle(vis, (cx-70, cy-70), (cx+70, cy+40), color, -1)
            
#             cv2.putText(vis, label, (cx-65, cy-45),
#                        cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2)
#             cv2.putText(vis, sim_text, (cx-65, cy-20),
#                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
#             cv2.putText(vis, f"C:{saddle.confidence:.2f}", (cx-65, cy+28),
#                        cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)
        
#         # Add angle info if it doesn't overlap text
#         # (Simplified visualization for better performance)
        
#         return vis
    
#     def _cleanup_after_processing(self):
#         """Clean up resources after processing"""
#         # Clear old saddles
#         for saddle in self.last_saddles:
#             if hasattr(saddle, 'cleanup'):
#                 saddle.cleanup()
        
#         # Trigger garbage collection
#         if ENABLE_GC:
#             gc.collect()
    
#     def cleanup(self):
#         """Full cleanup - call when done"""
#         print("Cleaning up resources...")
        
#         # Cleanup components
#         if hasattr(self.yolo_detector, 'cleanup'):
#             self.yolo_detector.cleanup()
        
#         if hasattr(self.geometric_detector, 'cleanup'):
#             self.geometric_detector.cleanup()
        
#         if hasattr(self.cnn_extractor, 'cleanup'):
#             self.cnn_extractor.cleanup()
        
#         if hasattr(self.reference_manager, 'cleanup'):
#             self.reference_manager.cleanup()
        
#         # Clear state
#         self.last_saddles.clear()
#         self.last_image = None
        
#         # Force garbage collection
#         if ENABLE_GC:
#             gc.collect()
        
#         print("βœ“ Cleanup complete")


import cv2
import numpy as np
from PIL import Image
import io
import json
from datetime import datetime
from typing import List, Tuple, Dict, Optional
from dataclasses import dataclass
import time
import os
import warnings
import gc
from collections import OrderedDict

# ============================================================================
# CLOUD DEPLOYMENT OPTIMIZATIONS
# ============================================================================
IS_HF_SPACE = os.environ.get('SPACE_ID') is not None or os.environ.get('HF_SPACE') is not None
IS_RENDER = os.environ.get('RENDER') is not None
IS_CLOUD = IS_HF_SPACE or IS_RENDER

# Memory limits for cloud
MAX_IMAGE_SIZE = (1280, 960) if IS_CLOUD else (1920, 1440)
MAX_CACHE_SIZE = 50 if IS_CLOUD else 100
ENABLE_GC = IS_CLOUD

# Lazy imports for faster cold start
_torch = None
_torchvision = None
_YOLO = None

def _get_torch():
    global _torch
    if _torch is None:
        import torch
        _torch = torch
        if IS_CLOUD:
            _torch.set_num_threads(2)
    return _torch

def _get_torchvision():
    global _torchvision
    if _torchvision is None:
        import torchvision
        _torchvision = torchvision
    return _torchvision

def _get_yolo():
    global _YOLO
    if _YOLO is None:
        try:
            from ultralytics import YOLO
            _YOLO = YOLO
        except ImportError:
            _YOLO = False
    return _YOLO

def _yolo_available():
    yolo = _get_yolo()
    return yolo is not False and yolo is not None

warnings.filterwarnings('ignore')

# Import optimized validators
try:
    from saddle_structure_validator import SaddleStructureValidator, SaddleStructure
    STRUCTURE_VALIDATOR_AVAILABLE = True
except ImportError:
    STRUCTURE_VALIDATOR_AVAILABLE = False
    SaddleStructure = None
    print("[WARN] saddle_structure_validator not available")

try:
    from geometric_validator import OptimizedGeometricValidator, PhysicalDimensions, PixelToMMCalibrator
    OPTIMIZED_VALIDATOR_AVAILABLE = True
except ImportError:
    OPTIMIZED_VALIDATOR_AVAILABLE = False
    print("[WARN] geometric_validator not available")

if IS_HF_SPACE:
    print("[HF Space] Memory-optimized mode enabled")
elif IS_RENDER:
    print("[Render] Cloud-optimized mode enabled")


@dataclass
class SaddleROI:
    """Saddle region of interest with rotation and structure info"""
    id: int
    bbox: Tuple[int, int, int, int]
    crop: np.ndarray
    center: Tuple[int, int]
    area: int
    angle: float
    confidence: float
    structure: Optional[any] = None
    
    def to_dict(self):
        result = {
            'id': int(self.id),
            'bbox': [int(x) for x in self.bbox],
            'center': [int(self.center[0]), int(self.center[1])],
            'area': int(self.area),
            'angle': float(self.angle),
            'confidence': float(self.confidence)
        }
        if self.structure is not None:
            result['has_semicircle'] = bool(getattr(self.structure, 'has_semicircle', False))
            result['has_middle_arc'] = bool(getattr(self.structure, 'has_middle_arc', False))
            result['structure_confidence'] = float(getattr(self.structure, 'structure_confidence', 0.0))
        return result
    
    def cleanup(self):
        """Free memory"""
        if hasattr(self, 'crop'):
            del self.crop
        self.crop = None
        self.structure = None


@dataclass
class SaddleInspectionResult:
    """Inspection result for one saddle"""
    saddle_id: int
    status: str
    similarity_score: float
    confidence: float
    feature_distance: float
    detected: bool
    
    def to_dict(self):
        return {
            'saddle_id': int(self.saddle_id),
            'status': str(self.status),
            'similarity_score': float(self.similarity_score),
            'confidence': float(self.confidence),
            'feature_distance': float(self.feature_distance),
            'detected': bool(self.detected)
        }


@dataclass
class BlockInspectionResult:
    """Complete block inspection result"""
    block_status: str
    total_saddles: int
    detected_saddles: int
    defective_saddles: int
    saddle_results: List[SaddleInspectionResult]
    processing_time_ms: float
    alignment_status: str
    block_angle: float
    
    def to_dict(self):
        return {
            'block_status': str(self.block_status),
            'total_saddles': int(self.total_saddles),
            'detected_saddles': int(self.detected_saddles),
            'defective_saddles': int(self.defective_saddles),
            'saddle_results': [r.to_dict() for r in self.saddle_results],
            'processing_time_ms': float(self.processing_time_ms),
            'alignment_status': str(self.alignment_status),
            'block_angle': float(self.block_angle)
        }


class LRUCache:
    """Thread-safe LRU cache with size limit"""
    
    def __init__(self, max_size=100):
        self.cache = OrderedDict()
        self.max_size = max_size
    
    def get(self, key):
        if key in self.cache:
            self.cache.move_to_end(key)
            return self.cache[key]
        return None
    
    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.max_size:
            self.cache.popitem(last=False)
    
    def clear(self):
        self.cache.clear()
        if ENABLE_GC:
            gc.collect()


class YOLOOBBDetector:
    """YOLO-OBB Detector with lazy loading and memory management"""
    
    def __init__(self, model_path: Optional[str] = None):
        self.model = None
        self.model_loaded = False
        self._model_path = model_path if model_path else 'yolo11n-obb.pt'
        self._initialized = False
    
    def _lazy_init(self):
        if self._initialized:
            return
        self._initialized = True
        
        if not _yolo_available():
            print("⚠ YOLO not available - will use geometric fallback")
            return
        
        YOLO = _get_yolo()
        
        try:
            self.model = YOLO(self._model_path)
            self.model_loaded = True
            print(f"βœ“ YOLO-OBB loaded: {self._model_path}")
        except Exception as e:
            print(f"⚠ YOLO load failed: {e} - will use geometric fallback")
            self.model_loaded = False
    
    @property
    def available(self):
        if not self._initialized:
            self._lazy_init()
        return self.model_loaded

    def detect_saddles(self, image: np.ndarray, conf_threshold: float = 0.20) -> List[SaddleROI]:
        """Detect saddles using YOLO-OBB with memory optimization"""
        
        if not self.available or self.model is None:
            return []
        
        # Resize if too large
        h, w = image.shape[:2]
        if w > MAX_IMAGE_SIZE[0] or h > MAX_IMAGE_SIZE[1]:
            scale = min(MAX_IMAGE_SIZE[0]/w, MAX_IMAGE_SIZE[1]/h)
            new_w, new_h = int(w*scale), int(h*scale)
            image_resized = cv2.resize(image, (new_w, new_h))
        else:
            image_resized = image
            scale = 1.0
        
        # Convert to grayscale for faster inference
        if len(image_resized.shape) == 3:
            gray = cv2.cvtColor(image_resized, cv2.COLOR_BGR2GRAY)
            gray_3ch = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
        else:
            gray_3ch = cv2.cvtColor(image_resized, cv2.COLOR_GRAY2BGR)
        
        results = self.model(gray_3ch, conf=conf_threshold, verbose=False)
        
        saddles = []
        
        for result in results:
            if hasattr(result, 'obb') and result.obb is not None:
                for i, obb in enumerate(result.obb):
                    xyxyxyxy = obb.xyxyxyxy[0].cpu().numpy()
                    conf = float(obb.conf[0])
                    
                    # Scale back to original coordinates
                    xyxyxyxy = xyxyxyxy / scale
                    
                    angle = self._calculate_angle(xyxyxyxy)
                    
                    x_coords = xyxyxyxy[:, 0]
                    y_coords = xyxyxyxy[:, 1]
                    
                    x_min, x_max = int(x_coords.min()), int(x_coords.max())
                    y_min, y_max = int(y_coords.min()), int(y_coords.max())
                    
                    w = x_max - x_min
                    h = y_max - y_min
                    
                    cx = int(np.mean(x_coords))
                    cy = int(np.mean(y_coords))
                    
                    # Crop from original image
                    crop = image[y_min:y_max, x_min:x_max].copy()
                    area = w * h
                    
                    saddles.append(SaddleROI(
                        id=i,
                        bbox=(x_min, y_min, w, h),
                        crop=crop,
                        center=(cx, cy),
                        area=area,
                        angle=angle,
                        confidence=conf
                    ))
            
            elif hasattr(result, 'boxes') and result.boxes is not None:
                for i, box in enumerate(result.boxes):
                    xyxy = box.xyxy[0].cpu().numpy()
                    conf = float(box.conf[0])
                    
                    # Scale back
                    xyxy = xyxy / scale
                    
                    x_min, y_min, x_max, y_max = map(int, xyxy)
                    w = x_max - x_min
                    h = y_max - y_min
                    
                    cx = (x_min + x_max) // 2
                    cy = (y_min + y_max) // 2
                    
                    crop = image[y_min:y_max, x_min:x_max].copy()
                    area = w * h
                    
                    saddles.append(SaddleROI(
                        id=i,
                        bbox=(x_min, y_min, w, h),
                        crop=crop,
                        center=(cx, cy),
                        area=area,
                        angle=0.0,
                        confidence=conf
                    ))
        
        # Sort by position
        saddles.sort(key=lambda s: (s.center[1], s.center[0]))
        
        for i, saddle in enumerate(saddles):
            saddle.id = i
        
        print(f"βœ“ YOLO detected: {len(saddles)} saddles")
        
        # Memory cleanup
        if ENABLE_GC:
            del gray_3ch, results
            gc.collect()
        
        return saddles
    
    def _calculate_angle(self, xyxyxyxy: np.ndarray) -> float:
        p1 = xyxyxyxy[0]
        p2 = xyxyxyxy[1]
        
        dx = p2[0] - p1[0]
        dy = p2[1] - p1[1]
        
        angle = np.degrees(np.arctan2(dy, dx))
        
        if angle > 180:
            angle -= 360
        elif angle < -180:
            angle += 360
        
        return float(angle)
    
    def cleanup(self):
        """Release model from memory"""
        if self.model is not None:
            del self.model
            self.model = None
            self.model_loaded = False
        if ENABLE_GC:
            gc.collect()


class GeometricSaddleDetector:
    """Optimized geometric detector with better 4-saddle detection"""
    
    def __init__(self, max_cache_size=None):
        if max_cache_size is None:
            max_cache_size = MAX_CACHE_SIZE
        self._mask_cache = LRUCache(max_cache_size)
    
    def detect_saddles(self, image: np.ndarray) -> List[SaddleROI]:
        """Detect using improved geometric segmentation"""
        
        print(f"[GeometricDetector] Input shape: {image.shape}")
        
        h, w = image.shape[:2]
        
        # Resize if too large
        if w > MAX_IMAGE_SIZE[0] or h > MAX_IMAGE_SIZE[1]:
            scale = min(MAX_IMAGE_SIZE[0]/w, MAX_IMAGE_SIZE[1]/h)
            new_w, new_h = int(w*scale), int(h*scale)
            image_work = cv2.resize(image, (new_w, new_h))
            print(f"[GeometricDetector] Resized to {new_w}x{new_h}")
        else:
            image_work = image
            scale = 1.0
        
        # Detect circles with improved method
        outer_circle, inner_circle = self._detect_circles_improved(image_work)
        
        if outer_circle is None:
            print("[GeometricDetector] βœ— Circle detection failed")
            return []
        
        ox, oy, or_ = outer_circle
        ix, iy, ir = inner_circle
        
        # Scale back to original
        if scale != 1.0:
            ox, oy = int(ox/scale), int(oy/scale)
            or_, ir = int(or_/scale), int(ir/scale)
            h, w = image.shape[:2]
        
        print(f"[GeometricDetector] Outer: ({ox},{oy}) r={or_}, Inner: ({ix},{iy}) r={ir}")
        
        # Validate
        if or_ < 50 or or_ > min(h, w):
            print(f"[GeometricDetector] βœ— Invalid outer radius: {or_}")
            return []
        
        if ir >= or_:
            ir = int(or_ * 0.4)
            print(f"[GeometricDetector] Adjusted inner radius to {ir}")
        
        # Create annular mask
        annular_mask = np.zeros((h, w), dtype=np.uint8)
        cv2.circle(annular_mask, (ox, oy), or_, 255, -1)
        cv2.circle(annular_mask, (ix, iy), ir, 0, -1)
        
        mask_pixels = np.sum(annular_mask > 0)
        print(f"[GeometricDetector] Annular mask pixels: {mask_pixels}")
        
        if mask_pixels < 1000:
            print(f"[GeometricDetector] βœ— Mask too small")
            return []
        
        # Find saddles using quadrant-based detection (more reliable for 4 saddles)
        saddles = self._detect_quadrant_based(image, annular_mask, (ox, oy), or_, ir)
        
        print(f"[GeometricDetector] Total saddles detected: {len(saddles)}")
        
        # Memory cleanup
        if ENABLE_GC:
            del annular_mask, image_work
            gc.collect()
        
        return saddles
    
    def _detect_quadrant_based(
        self,
        image: np.ndarray,
        annular_mask: np.ndarray,
        center: Tuple[int, int],
        outer_r: int,
        inner_r: int
    ) -> List[SaddleROI]:
        """Quadrant-based detection for 4 saddles"""
        
        h, w = annular_mask.shape
        ox, oy = center
        
        quadrants = [
            (0, 90, "Top-Right"),
            (90, 180, "Top-Left"),
            (180, 270, "Bottom-Left"),
            (270, 360, "Bottom-Right")
        ]
        
        saddles = []
        
        for idx, (start_angle, end_angle, name) in enumerate(quadrants):
            mask_key = (h, w, ox, oy, outer_r, inner_r, start_angle, end_angle)
            
            sector_mask = self._mask_cache.get(mask_key)
            if sector_mask is None:
                sector_mask = self._create_sector_mask(
                    (h, w), (ox, oy), outer_r, inner_r, start_angle, end_angle
                )
                self._mask_cache.put(mask_key, sector_mask)
            
            saddle_mask = cv2.bitwise_and(annular_mask, sector_mask)
            
            ys, xs = np.where(saddle_mask > 0)
            
            if len(xs) == 0 or len(ys) == 0:
                print(f"[GeometricDetector] ⚠ Quadrant {idx} ({name}): No pixels")
                continue
            
            x_min, x_max = xs.min(), xs.max()
            y_min, y_max = ys.min(), ys.max()
            
            if (x_max - x_min) < 10 or (y_max - y_min) < 10:
                print(f"[GeometricDetector] ⚠ Quadrant {idx} ({name}): Box too small")
                continue
            
            crop = image[y_min:y_max+1, x_min:x_max+1].copy()
            mask_crop = saddle_mask[y_min:y_max+1, x_min:x_max+1].copy()
            crop_masked = cv2.bitwise_and(crop, crop, mask=mask_crop)
            
            cx = int(np.mean(xs))
            cy = int(np.mean(ys))
            area = np.sum(saddle_mask > 0)
            
            saddles.append(SaddleROI(
                id=idx,
                bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
                crop=crop_masked,
                center=(cx, cy),
                area=area,
                angle=0.0,
                confidence=0.9  # Higher confidence for geometric detection
            ))
        
        return saddles
    
    def _detect_circles_improved(self, image: np.ndarray) -> Tuple[Optional[Tuple], Optional[Tuple]]:
        """Improved circle detection with multiple strategies"""
        
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
        h, w = gray.shape
        
        # Strategy 1: Standard HoughCircles with optimized params
        gray_blur = cv2.GaussianBlur(gray, (9, 9), 2)
        
        minRadius = int(min(h, w) * 0.2)
        maxRadius = int(min(h, w) * 0.7)
        
        # Try multiple parameter sets
        param_sets = [
            (80, 25),  # Standard
            (60, 30),  # More lenient
            (100, 20), # More strict
        ]
        
        for param1, param2 in param_sets:
            circles = cv2.HoughCircles(
                gray_blur,
                cv2.HOUGH_GRADIENT,
                dp=1.0,
                minDist=80,
                param1=param1,
                param2=param2,
                minRadius=minRadius,
                maxRadius=maxRadius
            )
            
            if circles is not None and len(circles[0]) >= 1:
                circles = np.round(circles[0, :]).astype(int)
                circles = sorted(circles, key=lambda c: c[2], reverse=True)
                outer = tuple(circles[0])
                inner_radius = int(outer[2] * 0.4)
                inner = (outer[0], outer[1], inner_radius)
                print(f"βœ“ HoughCircles success (param1={param1}, param2={param2})")
                return outer, inner
        
        # Strategy 2: Contour-based detection
        print("β†’ Using contour fallback")
        edges = cv2.Canny(gray_blur, 30, 100)
        
        # Dilate to connect edges
        kernel = np.ones((3, 3), np.uint8)
        edges = cv2.dilate(edges, kernel, iterations=2)
        
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        if contours:
            # Find largest contour
            largest = max(contours, key=cv2.contourArea)
            (cx, cy), radius = cv2.minEnclosingCircle(largest)
            
            center_x, center_y = int(cx), int(cy)
            outer_radius = int(radius * 0.85)
            inner_radius = int(outer_radius * 0.4)
            
            print(f"βœ“ Contour-based: center=({center_x},{center_y}), radius={outer_radius}")
            return ((center_x, center_y, outer_radius), (center_x, center_y, inner_radius))
        
        # Strategy 3: Dimension-based estimate
        center_x, center_y = w // 2, h // 2
        outer_radius = min(w, h) // 2 - 50
        inner_radius = int(outer_radius * 0.4)
        print(f"β†’ Using dimension estimate: center=({center_x},{center_y}), radius={outer_radius}")
        return ((center_x, center_y, outer_radius), (center_x, center_y, inner_radius))
    
    def _create_sector_mask(self, shape, center, outer_r, inner_r, start_angle, end_angle):
        """Create sector mask with caching"""
        
        h, w = shape
        mask = np.zeros((h, w), dtype=np.uint8)
        
        y, x = np.ogrid[:h, :w]
        dx = x - center[0]
        dy = y - center[1]
        
        angles = np.rad2deg(np.arctan2(dy, dx)) % 360
        radius = np.sqrt(dx**2 + dy**2)
        
        if start_angle < end_angle:
            angle_mask = (angles >= start_angle) & (angles < end_angle)
        else:
            angle_mask = (angles >= start_angle) | (angles < end_angle)
        
        radius_mask = (radius >= inner_r) & (radius <= outer_r)
        sector = angle_mask & radius_mask
        mask[sector] = 255
        
        return mask
    
    def cleanup(self):
        """Release cache"""
        self._mask_cache.clear()


class AlignmentCorrector:
    """Affine transformation for rotation correction"""
    
    @staticmethod
    def correct_rotation(image: np.ndarray, angle: float) -> np.ndarray:
        if image is None or image.size == 0:
            return image
        
        h, w = image.shape[:2]
        center = (w // 2, h // 2)
        
        M = cv2.getRotationMatrix2D(center, -angle, 1.0)
        
        cos = np.abs(M[0, 0])
        sin = np.abs(M[0, 1])
        
        new_w = int((h * sin) + (w * cos))
        new_h = int((h * cos) + (w * sin))
        
        M[0, 2] += (new_w / 2) - center[0]
        M[1, 2] += (new_h / 2) - center[1]
        
        rotated = cv2.warpAffine(image, M, (new_w, new_h), 
                                 flags=cv2.INTER_LINEAR,
                                 borderMode=cv2.BORDER_CONSTANT,
                                 borderValue=(0, 0, 0))
        
        return rotated
    
    @staticmethod
    def correct_saddle(saddle: SaddleROI) -> np.ndarray:
        if saddle.crop is None or saddle.crop.size == 0:
            return np.zeros((224, 224, 3), dtype=np.uint8)
        if abs(saddle.angle) < 1.0:
            return saddle.crop
        return AlignmentCorrector.correct_rotation(saddle.crop, saddle.angle)


class CNNFeatureExtractor:
    """ResNet-18 feature extraction with memory optimization"""
    
    def __init__(self, onnx_path: str = "resnet18_features.onnx"):
        self.onnx_path = onnx_path
        self.session = None
        self.model = None
        self.device = None
        self.feature_dim = 1024
        self._initialized = False
    
    def _lazy_init(self):
        if self._initialized:
            return
        self._initialized = True
        
        # Use PyTorch with fused features
        self._init_pytorch_model()
    
    def _init_pytorch_model(self):
        torch = _get_torch()
        torchvision = _get_torchvision()
        from torchvision.models import resnet18, ResNet18_Weights
        import torch.nn as nn
        
        self.device = torch.device('cpu')
        weights = ResNet18_Weights.IMAGENET1K_V1
        base_model = resnet18(weights=weights)
        
        class FeatureFusionModel(nn.Module):
            def __init__(self, base):
                super().__init__()
                self.conv1 = base.conv1
                self.bn1 = base.bn1
                self.relu = base.relu
                self.maxpool = base.maxpool
                self.layer1 = base.layer1
                self.layer2 = base.layer2
                self.layer3 = base.layer3
                self.layer4 = base.layer4
                self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
                self.maxpool_global = nn.AdaptiveMaxPool2d((1, 1))

            def forward(self, x):
                x = self.conv1(x)
                x = self.bn1(x)
                x = self.relu(x)
                x = self.maxpool(x)
                x = self.layer1(x)
                x = self.layer2(x)
                l3 = self.layer3(x)
                l4 = self.layer4(l3)
                
                f3_avg = self.avgpool(l3).view(l3.size(0), -1)
                f3_max = self.maxpool_global(l3).view(l3.size(0), -1)
                f4_avg = self.avgpool(l4).view(l4.size(0), -1)
                
                return torch.cat([f3_avg, f3_max, f4_avg], dim=1)

        self.model = FeatureFusionModel(base_model)
        self.model.to(self.device)
        self.model.eval()
        print(f"βœ“ PyTorch FeatureFusion ResNet-18 (dim={self.feature_dim})")
    
    def _preprocess_image(self, image: np.ndarray) -> np.ndarray:
        if image is None or image.size == 0:
            return np.zeros((3, 224, 224), dtype=np.float32)
        
        if len(image.shape) == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
        elif len(image.shape) == 3 and image.shape[2] == 4:
            image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGB)
        elif len(image.shape) == 3 and image.shape[2] == 3:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        
        image = cv2.resize(image, (224, 224))
        
        image = image.astype(np.float32) / 255.0
        mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
        std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
        image = (image - mean) / std
        
        image = image.transpose(2, 0, 1)
        
        return image
    
    def extract_features(self, image: np.ndarray) -> np.ndarray:
        self._lazy_init()
        batch = self._preprocess_image(image)[np.newaxis, ...]
        features = self.extract_batch(batch)
        return features[0]
    
    def extract_batch(self, images: List[np.ndarray]) -> np.ndarray:
        self._lazy_init()
        
        if isinstance(images, np.ndarray) and len(images.shape) == 4:
            batch = images.astype(np.float32)
        else:
            preprocessed = [self._preprocess_image(img) for img in images]
            batch = np.stack(preprocessed, axis=0).astype(np.float32)
        
        torch = _get_torch()
        batch_tensor = torch.from_numpy(batch).to(self.device)
        with torch.no_grad():
            features = self.model(batch_tensor)
        features = features.squeeze(-1).squeeze(-1).cpu().numpy()
        
        norms = np.linalg.norm(features, axis=1, keepdims=True) + 1e-8
        features = features / norms
        
        # Memory cleanup
        if ENABLE_GC:
            del batch_tensor
            gc.collect()
        
        return features
    
    def compute_similarity(self, features1: np.ndarray, features2: np.ndarray) -> float:
        similarity = np.dot(features1, features2) / (
            np.linalg.norm(features1) * np.linalg.norm(features2) + 1e-8
        )
        return float(np.clip(similarity, 0, 1))
    
    def cleanup(self):
        """Release model from memory"""
        if self.model is not None:
            del self.model
            self.model = None
        if ENABLE_GC:
            gc.collect()


class GeometricConstraintValidator:
    """Validate saddle positions using geometric constraints - RELAXED"""
    
    def __init__(self, expected_count: int = 4):
        self.expected_count = expected_count
        self.reference_positions = None
        self.reference_distances = {}
    
    def set_reference_positions(self, saddles: List[SaddleROI]):
        if len(saddles) != self.expected_count:
            print(f"⚠ Reference has {len(saddles)} saddles, expected {self.expected_count}")
            return False
        
        centers = [s.center for s in saddles]
        
        centroid = (
            int(np.mean([c[0] for c in centers])),
            int(np.mean([c[1] for c in centers]))
        )
        
        self.reference_positions = [
            (c[0] - centroid[0], c[1] - centroid[1]) for c in centers
        ]
        
        self.reference_distances = {}
        for i in range(len(saddles)):
            for j in range(i+1, len(saddles)):
                dist = np.linalg.norm(
                    np.array(saddles[i].center) - np.array(saddles[j].center)
                )
                self.reference_distances[(i, j)] = dist
        
        print(f"βœ“ Reference geometry learned: {len(saddles)} saddles")
        return True
    
    def infer_missing_saddles(
        self, 
        detected_saddles: List[SaddleROI],
        image: np.ndarray
    ) -> List[SaddleROI]:
        """Infer missing saddles based on reference geometry"""
        
        if len(detected_saddles) >= self.expected_count:
            return detected_saddles
        
        if self.reference_positions is None:
            print("⚠ No reference geometry - cannot infer")
            return detected_saddles
        
        if len(detected_saddles) == 0:
            print("⚠ No saddles detected - cannot infer")
            return detected_saddles
        
        centers = [s.center for s in detected_saddles]
        centroid = (
            int(np.mean([c[0] for c in centers])),
            int(np.mean([c[1] for c in centers]))
        )
        
        scale = self._estimate_scale(detected_saddles)
        
        detected_ids = {s.id for s in detected_saddles}
        all_saddles = list(detected_saddles)
        
        for expected_id in range(self.expected_count):
            if expected_id not in detected_ids:
                rel_x, rel_y = self.reference_positions[expected_id]
                
                expected_x = int(centroid[0] + rel_x * scale)
                expected_y = int(centroid[1] + rel_y * scale)
                
                crop_size = 150  # Increased crop size
                
                x_min = max(0, expected_x - crop_size // 2)
                y_min = max(0, expected_y - crop_size // 2)
                x_max = min(image.shape[1], expected_x + crop_size // 2)
                y_max = min(image.shape[0], expected_y + crop_size // 2)
                
                crop = image[y_min:y_max, x_min:x_max].copy()
                
                inferred = SaddleROI(
                    id=expected_id,
                    bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
                    crop=crop,
                    center=(expected_x, expected_y),
                    area=(x_max - x_min) * (y_max - y_min),
                    angle=0.0,
                    confidence=0.5  # Mark as inferred
                )
                
                all_saddles.append(inferred)
                print(f"  βš™ Inferred Saddle {expected_id} at ({expected_x}, {expected_y})")
        
        all_saddles.sort(key=lambda s: s.id)
        
        return all_saddles
    
    def _estimate_scale(self, saddles: List[SaddleROI]) -> float:
        if len(saddles) < 2 or not self.reference_distances:
            return 1.0
        
        if len(saddles) >= 2:
            s0, s1 = saddles[0], saddles[1]
            current_dist = np.linalg.norm(
                np.array(s0.center) - np.array(s1.center)
            )
            
            key = (min(s0.id, s1.id), max(s0.id, s1.id))
            if key in self.reference_distances:
                ref_dist = self.reference_distances[key]
                if ref_dist > 0:
                    scale = current_dist / ref_dist
                    return scale
        
        return 1.0
    
    def validate_geometry(self, saddles: List[SaddleROI], tolerance: float = 0.30) -> Tuple[bool, str]:
        """RELAXED geometry validation"""
        
        if len(saddles) != self.expected_count:
            return False, f"Expected {self.expected_count} saddles, got {len(saddles)}"
        
        if self.reference_distances is None or not self.reference_distances:
            # No reference - accept geometry
            return True, "No reference geometry (accepting)"
        
        sorted_saddles = sorted(saddles, key=lambda s: s.id)
        centers = [np.array(s.center) for s in sorted_saddles]
        
        # Skip collinearity check - too strict
        
        # Distance validation with relaxed tolerance
        max_deviation = 0.0
        for i in range(len(sorted_saddles) - 1):
            s0, s1 = sorted_saddles[i], sorted_saddles[i + 1]
            current_dist = np.linalg.norm(centers[i + 1] - centers[i])
            
            key = (min(s0.id, s1.id), max(s0.id, s1.id))
            if key in self.reference_distances:
                ref_dist = self.reference_distances[key]
                if ref_dist > 0:
                    deviation = abs(current_dist - ref_dist) / ref_dist
                    max_deviation = max(max_deviation, deviation)
                    if deviation > tolerance:
                        print(f"  Distance S{s0.id}-S{s1.id} off by {deviation*100:.1f}%")
        
        if max_deviation > tolerance:
            return False, f"Max distance deviation: {max_deviation*100:.1f}%"
        
        return True, "Geometry valid"


class MultiReferenceManager:
    """Manage multiple golden template images with memory optimization"""
    
    def __init__(self, feature_extractor: CNNFeatureExtractor):
        self.feature_extractor = feature_extractor
        self.references = []
        self.max_references = 20 if not IS_CLOUD else 10
        
    def add_reference(self, image: np.ndarray, saddles: List[SaddleROI]) -> bool:
        if len(saddles) != 4:
            print(f"⚠ Reference must have 4 saddles, got {len(saddles)}")
            return False
        
        # Limit number of references
        if len(self.references) >= self.max_references:
            print(f"⚠ Max references ({self.max_references}) reached, removing oldest")
            old_ref = self.references.pop(0)
            # Cleanup
            if ENABLE_GC:
                del old_ref
                gc.collect()
        
        features_list = []
        
        for saddle in saddles:
            aligned_crop = AlignmentCorrector.correct_saddle(saddle)
            features = self.feature_extractor.extract_features(aligned_crop)
            features_list.append(features)
        
        # Compress image for storage
        if image.shape[0] > 800 or image.shape[1] > 800:
            scale = min(800/image.shape[1], 800/image.shape[0])
            new_w, new_h = int(image.shape[1]*scale), int(image.shape[0]*scale)
            image_stored = cv2.resize(image, (new_w, new_h))
        else:
            image_stored = image
        
        self.references.append({
            'image': image_stored,
            'saddles': saddles,
            'features': features_list
        })
        
        print(f"βœ“ Reference {len(self.references)} added")
        return True
    
    def match_saddle(self, saddle: SaddleROI) -> Tuple[float, float]:
        if not self.references:
            # No references - return neutral score
            return 0.90, 0.5  # High similarity when no reference
        
        aligned_crop = AlignmentCorrector.correct_saddle(saddle)
        test_features = self.feature_extractor.extract_features(aligned_crop)
        
        similarities = []
        distances = []
        
        for ref in self.references:
            if saddle.id < len(ref['features']):
                ref_features = ref['features'][saddle.id]
                
                sim = self.feature_extractor.compute_similarity(test_features, ref_features)
                dist = np.linalg.norm(test_features - ref_features)
                
                similarities.append(sim)
                distances.append(dist)
        
        if similarities:
            best_sim = max(similarities)
            avg_dist = np.mean(distances)
            return best_sim, avg_dist
        
        return 0.90, 0.5  # Default neutral score
    
    def get_reference_count(self) -> int:
        return len(self.references)

    def get_references(self) -> List[str]:
        refs = []
        for ref in self.references:
            try:
                _, buffer = cv2.imencode('.jpg', ref['image'], [cv2.IMWRITE_JPEG_QUALITY, 50])
                import base64
                img_str = base64.b64encode(buffer).decode('utf-8')
                refs.append(f"data:image/jpeg;base64,{img_str}")
            except:
                continue
        return refs
    
    def cleanup(self):
        """Release all references"""
        self.references.clear()
        if ENABLE_GC:
            gc.collect()


class AdvancedBlockInspector:
    """
    Advanced Engine Block Inspector - CLOUD OPTIMIZED & RELAXED
    
    Key improvements:
    - Works WITHOUT reference images
    - Relaxed thresholds
    - Better error handling
    - Improved saddle detection fallback
    """
    
    def __init__(self, yolo_model_path: Optional[str] = None, onnx_path: str = "resnet18_features.onnx"):
        self.yolo_detector = YOLOOBBDetector(yolo_model_path)
        self.geometric_detector = GeometricSaddleDetector()
        
        self.cnn_extractor = CNNFeatureExtractor(onnx_path=onnx_path)
        
        self.reference_manager = MultiReferenceManager(self.cnn_extractor)
        
        # Use base validator (more flexible)
        self.geo_validator = GeometricConstraintValidator(expected_count=4)
        self.use_optimized_validator = False
        
        # Structure validator
        self.structure_validator = None
        if STRUCTURE_VALIDATOR_AVAILABLE:
            self.structure_validator = SaddleStructureValidator(
                arc_center_tolerance=0.05,
                min_arc_length_ratio=0.6,
                min_structure_confidence=0.65
            )
            print("βœ“ Structure Validator: Semicircle + Middle Arc")
        
        self.config = {
            'expected_saddles': 4,
            'similarity_threshold': 0.75,  # RELAXED from 0.88
            'use_yolo': self.yolo_detector.model_loaded,
            'use_geometric_fallback': True,
            'use_alignment_correction': True,
            'infer_missing_saddles': True,
            'yolo_confidence': 0.20,  # RELAXED from 0.25
            'use_geometry_validation': False,  # DISABLED initially
            'use_structure_validation': False,  # DISABLED initially
            'use_optimized_validator': False,
            'min_brightness': 15.0,  # RELAXED from 20.0
            'require_references': False,  # NEW: work without references
        }
        
        # Memory tracking
        self.last_saddles = []
        self.last_image = None
        
        print("[OK] Advanced Inspector initialized (Relaxed Mode)")
        print(f"  YOLO-OBB: {'Enabled' if self.config['use_yolo'] else 'Disabled (using geometric)'}")
        print(f"  Similarity threshold: {self.config['similarity_threshold']}")
        print(f"  Requires references: {self.config['require_references']}")
        print(f"  Max cache size: {MAX_CACHE_SIZE}")
        print(f"  GC enabled: {ENABLE_GC}")
    
    def add_reference_image(self, image: np.ndarray) -> bool:
        """Add a golden template image"""
        
        try:
            # Quality check
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
            brightness = np.mean(gray)
            if brightness < 15:
                print(f"βœ— Reference too dark (brightness: {brightness:.1f})")
                return False
            
            # Detect saddles
            if self.config['use_yolo']:
                saddles = self.yolo_detector.detect_saddles(
                    image, conf_threshold=self.config['yolo_confidence']
                )
            else:
                saddles = []
            
            if len(saddles) < self.config['expected_saddles'] and self.config['use_geometric_fallback']:
                print("β†’ Falling back to geometric detection")
                saddles = self.geometric_detector.detect_saddles(image)
            
            if len(saddles) != self.config['expected_saddles']:
                print(f"βœ— Reference failed: {len(saddles)}/{self.config['expected_saddles']} saddles")
                return False
            
            success = self.reference_manager.add_reference(image, saddles)
            
            if success and self.reference_manager.get_reference_count() == 1:
                self.geo_validator.set_reference_positions(saddles)
                # Enable validation after first reference
                self.config['use_geometry_validation'] = True
            
            # Cleanup
            self._cleanup_after_processing()
            
            return success
            
        except Exception as e:
            print(f"βœ— Reference error: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    def inspect_block(self, image: np.ndarray) -> BlockInspectionResult:
        """Inspect engine block with memory optimization - RELAXED MODE"""
        
        start_time = time.time()
        
        try:
            # Quality check
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
            brightness = np.mean(gray)
            if brightness < 10:  # Very relaxed
                return BlockInspectionResult(
                    block_status='WASTE_IMAGE',
                    total_saddles=self.config['expected_saddles'],
                    detected_saddles=0,
                    defective_saddles=0,
                    saddle_results=[],
                    processing_time_ms=(time.time() - start_time) * 1000,
                    alignment_status='REJECTED_TOO_DARK',
                    block_angle=0.0
                )
            
            # Detect saddles
            if self.config['use_yolo']:
                saddles = self.yolo_detector.detect_saddles(
                    image, conf_threshold=self.config['yolo_confidence']
                )
            else:
                saddles = []
            
            if len(saddles) < self.config['expected_saddles'] and self.config['use_geometric_fallback']:
                print("β†’ Falling back to geometric detection")
                saddles = self.geometric_detector.detect_saddles(image)
            
            detected_count = len(saddles)
            print(f"  Initially detected: {detected_count} saddles")
            
            # Infer missing saddles if we have reference
            if len(saddles) < self.config['expected_saddles'] and self.config['infer_missing_saddles']:
                if self.reference_manager.get_reference_count() > 0:
                    print(f"  Inferring {self.config['expected_saddles'] - len(saddles)} missing saddles")
                    saddles = self.geo_validator.infer_missing_saddles(saddles, image)
                else:
                    print("  ⚠ No references - cannot infer missing saddles")
            
            # Validate count
            if len(saddles) != self.config['expected_saddles']:
                alignment_status = f"SADDLE_COUNT: {len(saddles)}/{self.config['expected_saddles']}"
                
                # If no references, this might still be OK
                if not self.config['require_references'] and len(saddles) > 0:
                    print(f"  Warning: {alignment_status} but continuing without references")
                else:
                    return self._error_result(alignment_status, 0.0, saddles, detected_count)
            
            # Geometry validation (only if enabled and references exist)
            if self.config.get('use_geometry_validation', False) and self.reference_manager.get_reference_count() > 0:
                is_valid, reason = self.geo_validator.validate_geometry(saddles, tolerance=0.30)
                if not is_valid:
                    print(f"  Geometry validation failed: {reason}")
                    # Don't reject - just warn
            
            alignment_status = "OK"
            block_angle = np.mean([s.angle for s in saddles]) if saddles else 0.0
            
            # Feature extraction and comparison
            if len(saddles) == self.config['expected_saddles']:
                aligned_crops = [AlignmentCorrector.correct_saddle(s) for s in saddles]
                batch_features = self.cnn_extractor.extract_batch(aligned_crops)
                
                # Compare against references
                saddle_results = []
                for i, saddle in enumerate(saddles):
                    test_features = batch_features[i]
                    best_sim, avg_dist = self.reference_manager.match_saddle(saddle)
                    
                    # Relaxed status determination
                    status = 'PERFECT' if best_sim >= self.config['similarity_threshold'] else 'DEFECTIVE'
                    
                    saddle_results.append(SaddleInspectionResult(
                        saddle_id=saddle.id,
                        status=status,
                        similarity_score=best_sim,
                        confidence=saddle.confidence,
                        feature_distance=avg_dist,
                        detected=saddle.confidence > 0.0
                    ))
            else:
                # Partial detection
                saddle_results = []
                for saddle in saddles:
                    best_sim, avg_dist = self.reference_manager.match_saddle(saddle)
                    saddle_results.append(SaddleInspectionResult(
                        saddle_id=saddle.id,
                        status='UNKNOWN',
                        similarity_score=best_sim,
                        confidence=saddle.confidence,
                        feature_distance=avg_dist,
                        detected=saddle.confidence > 0.0
                    ))
            
            # Block decision - RELAXED
            defective_count = sum(1 for r in saddle_results if r.status == 'DEFECTIVE')
            avg_sim = np.mean([r.similarity_score for r in saddle_results]) if saddle_results else 0
            
            # Determine block status
            if len(saddles) == 0:
                block_status = 'WASTE_IMAGE'
            elif len(saddles) < self.config['expected_saddles']:
                if self.config['require_references']:
                    block_status = 'DEFECTIVE'
                else:
                    # No references required - accept partial detection
                    block_status = 'UNKNOWN'
            elif defective_count == 0:
                block_status = 'PERFECT'
            elif defective_count <= 2:  # Allow up to 2 defective
                block_status = 'ACCEPTABLE'
            else:
                block_status = 'DEFECTIVE'
            
            processing_time = (time.time() - start_time) * 1000
            
            self.last_saddles = saddles
            self.last_image = image
            
            result = BlockInspectionResult(
                block_status=block_status,
                total_saddles=self.config['expected_saddles'],
                detected_saddles=detected_count,
                defective_saddles=defective_count,
                saddle_results=saddle_results,
                processing_time_ms=processing_time,
                alignment_status=alignment_status,
                block_angle=block_angle
            )
            
            print(f"  Result: {block_status} ({detected_count}/{self.config['expected_saddles']} detected, {defective_count} defective)")
            
            # Cleanup
            self._cleanup_after_processing()
            
            return result
            
        except Exception as e:
            print(f"βœ— Inspection error: {e}")
            import traceback
            traceback.print_exc()
            return self._error_result(f"EXCEPTION: {str(e)}", 0.0, [], 0)

    def get_reference_images(self) -> List[str]:
        return self.reference_manager.get_references()
    
    def _error_result(self, message: str, angle: float, saddles: List, detected_count: int) -> BlockInspectionResult:
        self.last_saddles = saddles
        
        return BlockInspectionResult(
            block_status='ERROR',
            total_saddles=self.config['expected_saddles'],
            detected_saddles=detected_count,
            defective_saddles=0,
            saddle_results=[],
            processing_time_ms=0.0,
            alignment_status=message,
            block_angle=angle
        )
    
    def visualize_results(
        self,
        original_image: np.ndarray,
        saddles: List[SaddleROI],
        results: List[SaddleInspectionResult]
    ) -> np.ndarray:
        """Create detailed visualization"""
        
        vis = original_image.copy()
        
        for saddle, result in zip(saddles, results):
            # Color coding
            if result.status == 'UNKNOWN':
                color = (255, 255, 0)  # Yellow
            elif not result.detected:
                color = (255, 165, 0)  # Orange
            elif result.status == 'PERFECT' or result.status == 'ACCEPTABLE':
                color = (0, 255, 0)  # Green
            else:
                color = (0, 0, 255)  # Red
            
            x, y, w, h = saddle.bbox
            cv2.rectangle(vis, (x, y), (x+w, y+h), color, 3)
            
            cx, cy = saddle.center
            cv2.circle(vis, (cx, cy), 10, color, -1)
            
            if abs(saddle.angle) > 1.0:
                rad = np.deg2rad(saddle.angle)
                end_x = int(cx + 30 * np.cos(rad))
                end_y = int(cy + 30 * np.sin(rad))
                cv2.arrowedLine(vis, (cx, cy), (end_x, end_y), color, 3)
            
            detection_marker = "" if result.detected else "βš™"
            label = f"{detection_marker} S{saddle.id}: {result.status}"
            sim_text = f"{result.similarity_score:.3f}"
            angle_text = f"{saddle.angle:.1f}Β°"
            
            cv2.rectangle(vis, (cx-70, cy-70), (cx+70, cy+40), color, -1)
            
            cv2.putText(vis, label, (cx-65, cy-45),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2)
            cv2.putText(vis, sim_text, (cx-65, cy-20),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
            cv2.putText(vis, angle_text, (cx-65, cy+5),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 2)
            cv2.putText(vis, f"C:{saddle.confidence:.2f}", (cx-65, cy+28),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1)
        
        return vis
    
    def _cleanup_after_processing(self):
        """Clean up resources after processing"""
        # Clear old saddles
        for saddle in self.last_saddles:
            if hasattr(saddle, 'cleanup'):
                saddle.cleanup()
        
        # Trigger garbage collection
        if ENABLE_GC:
            gc.collect()
    
    def cleanup(self):
        """Full cleanup - call when done"""
        print("Cleaning up resources...")
        
        # Cleanup components
        if hasattr(self.yolo_detector, 'cleanup'):
            self.yolo_detector.cleanup()
        
        if hasattr(self.geometric_detector, 'cleanup'):
            self.geometric_detector.cleanup()
        
        if hasattr(self.cnn_extractor, 'cleanup'):
            self.cnn_extractor.cleanup()
        
        if hasattr(self.reference_manager, 'cleanup'):
            self.reference_manager.cleanup()
        
        # Clear state
        self.last_saddles.clear()
        self.last_image = None
        
        # Force garbage collection
        if ENABLE_GC:
            gc.collect()
        
        print("βœ“ Cleanup complete")