File size: 76,626 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Contract suite for every frontend-consumed endpoint (plan TEST-T2).

Two layers:

- ``TestFrontendContract`` pins the registration surface: every /api path the
  frontend calls must exist in the OpenAPI schema with the method the client
  uses (and a declared response model where the backend declares one). This is
  the 404-guard from test_chart_route_registration.py generalized to the whole
  frontend surface.
- ``TestLiveContracts``/``TestValidationErrors`` drive real requests through
  the FastAPI app: success shape, validation errors, and
  provider-timeout/error fallback. All I/O is monkeypatched (SQLite lives on a
  tmp_path via core.shared.db.DB_PATH, providers are stubs), so the suite is
  hermetic and xdist-safe.
"""

import json
import threading
import time
from datetime import date, timedelta
from pathlib import Path

import pandas as pd
import pytest
from fastapi.testclient import TestClient

import core.shared.db as db
from app.main import app
from core.domain.schemas import DiscoverPatternRequest


def _collect_api_routes() -> dict[tuple[str, str], set[str]]:
    """path -> methods for every /api route, recursing included routers."""
    from fastapi.routing import APIRoute, _IncludedRouter

    seen: dict[str, set[str]] = {}

    def collect(routes: list) -> None:
        for route in routes:
            if isinstance(route, APIRoute):
                seen.setdefault(route.path, set()).update(route.methods)
            elif isinstance(route, _IncludedRouter):
                collect(route.include_context.included_router.routes)
            elif hasattr(route, "routes"):
                collect(route.routes)

    collect(list(app.routes))
    for router in app.routes:
        if isinstance(router, _IncludedRouter):
            collect(router.include_context.included_router.routes)
    return seen


API_ROUTES = _collect_api_routes()


def _collect_ws_routes() -> set[str]:
    """Every registered WebSocket path (APIWebSocketRoute carries the full
    prefixed path; monitor's /{source} wildcard covers the feed sources)."""
    from fastapi.routing import _IncludedRouter

    seen: set[str] = set()

    def collect(routes: list) -> None:
        for route in routes:
            name = type(route).__name__
            if "WebSocketRoute" in name and getattr(route, "path", None):
                seen.add(route.path)
            elif isinstance(route, _IncludedRouter):
                collect(route.include_context.included_router.routes)
            elif hasattr(route, "routes"):
                collect(route.routes)

    collect(list(app.routes))
    for router in app.routes:
        if isinstance(router, _IncludedRouter):
            collect(router.include_context.included_router.routes)
    return seen


WS_ROUTES = _collect_ws_routes()


def _frontend_paths() -> dict[str, set[str]]:
    """Extract every /api/... URL the frontend references.

    Regexes over the TS sources keep the suite maintenance-free: a new fetch in
    static/js adds itself to the contract. URLs are normalized to registered
    shapes before comparison:

    - query strings (``?a=${x}``) are dropped — parameter contracts live on
      the endpoint, not the client URL;
    - dynamic path segments (template literals like
      ``/api/dashboard/widgets/${id}``) are matched against the registered
      ``{param}`` routes, so a renamed backend path fails here instead of
      404ing in the browser.
    """
    import re

    js_root = Path("static/js")
    if not js_root.is_dir():
        return {}
    pat_str = re.compile(r"['\"](/api/[A-Za-z0-9/_.\-]+)['\"]")
    pat_tpl = re.compile(r"`(/api/[^`\s]*)")
    raw: set[str] = set()
    for source in js_root.rglob("*.ts"):
        text = source.read_text()
        raw.update(match.group(1) for match in pat_str.finditer(text))
        raw.update(match.group(1) for match in pat_tpl.finditer(text))

    resolved: set[str] = set()
    for url in raw:
        path = url.split("?", 1)[0].rstrip("/")
        if not path or path == "/api" or not path.startswith("/api/"):
            continue
        if path in API_ROUTES:
            resolved.add(path)
            continue
        matched = _match_dynamic_path(path)
        if matched:
            resolved.add(matched)
    return {path: {"GET"} for path in resolved}


def _match_dynamic_path(path: str) -> str | None:
    """Match a client path built from a template literal (its ``${...}``
    segments already stripped) against a registered ``{param}`` route."""
    import re

    for candidate in API_ROUTES:
        escaped = re.escape(candidate)
        regex = re.sub(r"\\\{[^}]+\\\}", "[^/]+", escaped)
        if re.fullmatch(regex, path):
            return candidate
    return None


# The frontend also issues non-GET requests. This table pairs each mutating
# URL the client sends with the method it uses, so a backend that drops (or
# re-methods) an endpoint fails here instead of in the browser.
MUTATIONS: tuple[tuple[str, str], ...] = (
    ("/api/watchlist", "POST"),
    ("/api/backtest/alert-configs", "POST"),
    ("/api/backtest/alert-configs/preview", "POST"),
    ("/api/backtest/alert-configs/validate", "POST"),
    ("/api/backtest/alert-configs/{config_id}", "PUT"),
    ("/api/backtest/alert-configs/{config_id}", "DELETE"),
    ("/api/backtest/start", "POST"),
    ("/api/backtest/stop", "POST"),
    ("/api/bankruptcy/dismiss", "POST"),
    ("/api/bankruptcy/dismiss", "DELETE"),
    ("/api/chart/alerts", "GET"),
    ("/api/chart/alerts/sync", "POST"),
    ("/api/chart/alerts/{alert_id}", "PUT"),
    ("/api/chart/alerts/{alert_id}", "DELETE"),
    ("/api/chat", "POST"),
    ("/api/dashboard/tabs", "GET"),
    ("/api/dashboard/tabs", "POST"),
    ("/api/dashboard/tabs/{tab_id}", "PUT"),
    ("/api/dashboard/tabs/{tab_id}", "DELETE"),
    ("/api/dashboard/widgets", "GET"),
    ("/api/dashboard/widgets", "POST"),
    ("/api/dashboard/widgets/{widget_id}", "PUT"),
    ("/api/dashboard/widgets/{widget_id}", "DELETE"),
    ("/api/filters", "GET"),
    ("/api/filters", "POST"),
    ("/api/filters/{name}", "DELETE"),
    ("/api/hf/download-data", "POST"),
    ("/api/hf/push-config", "POST"),
    ("/api/hf/restore-config", "POST"),
    ("/api/hf/restore-config", "GET"),
    ("/api/hf/sync", "POST"),
    ("/api/llm/model", "POST"),
    ("/api/playbook", "GET"),
    ("/api/reports/dates", "GET"),
    ("/api/reports/candidates", "GET"),
    ("/api/playbook", "POST"),
    ("/api/playbook/{setup_id}", "PUT"),
    ("/api/playbook/{setup_id}", "DELETE"),
    ("/api/playbook/{setup_id}/screenshots", "POST"),
    ("/api/playbook/{setup_id}/screenshots/{screenshot_id}", "DELETE"),
    ("/api/playbook/{setup_id}/screenshots/{screenshot_id}/cover", "POST"),
    ("/api/screener", "POST"),
    ("/api/symbol-flags", "GET"),
    ("/api/symbol-flags", "POST"),
    ("/api/symbol-flags/{id}", "PUT"),
    ("/api/symbol-flags/{id}", "DELETE"),
    ("/api/symbol-flags/order", "PUT"),
    ("/api/trades/annotations", "GET"),
    ("/api/trades/annotations/{trade_key:path}", "POST"),
    ("/api/trades/auth", "POST"),
    ("/api/trades/auth/callback", "POST"),
)

# every frontend-consumed path with the methods the client needs on it
CONSUMED: dict[str, set[str]] = {}


def _add(path: str, *methods: str) -> None:
    CONSUMED.setdefault(path, set()).update(methods)


for _path, _method in MUTATIONS:
    _add(_path, _method)
for _path in (
    "/api/at-risk/screens",
    "/api/backtest/status",
    "/api/backtest/alert-elements/catalog",
    "/api/dashboard/external-feed-sources",
    "/api/dilution/{symbol}",
    "/api/discover/fallback",
    "/api/dsl/schema",
    "/api/hf/data-status",
    "/api/hf/status",
    "/api/hf/sync/progress",
    "/api/level2/status",
    "/api/llm/models",
    "/api/llm/status",
    "/api/market-pulse/enrich",
    "/api/news/batch",
    "/api/reverse-splits",
    "/api/scan",
    "/api/scan/calendar",
    "/api/scan/calendar/export",
    "/api/signals/history",
    "/api/signals/metrics",
    "/api/signals/status",
    "/api/stock-catalysts/{symbol}",
    "/api/stock-catalysts/{symbol}/fast",
    "/api/stock-catalysts/{symbol}/news",
    "/api/symbol-flags/fields",
    "/api/symbol-flags/sources",
    "/api/trades/status",
    "/api/trades/transactions",
    "/api/trades/auth-url",
):
    _add(_path, "GET")

# WebSockets the frontend opens.
WS_PATHS: tuple[str, ...] = (
    "/api/backtest/stream",
    "/api/dashboard/widgets/{widget_id}/stream",
    "/api/level2/stream",
    "/api/signals/stream",
)

# monitor serves every external feed source through one WS wildcard
# (modules/monitor/routes.py: @router.websocket("/{source}")); the frontend's
# feed widgets connect to /api/monitor/{source} for each EXTERNAL_FEED_SOURCES id.
WS_MONITOR_SOURCES: tuple[str, ...] = ("momo", "titan", "titan_news", "titan_filings", "titan_halts")


class TestFrontendContract:
    def test_frontend_urls_resolve_to_registered_routes(self) -> None:
        """Every /api URL pattern in static/js must resolve to a registered route."""
        frontend = _frontend_paths()
        assert frontend, "no frontend /api URLs found — extraction broke"

    @pytest.mark.parametrize("path", sorted(_frontend_paths()))
    def test_frontend_path_is_registered(self, path: str) -> None:
        assert path in API_ROUTES, f"frontend URL pattern {path} matches no registered route"

    def test_extraction_covers_the_known_surface(self) -> None:
        """Guard the extractor itself: if these stop matching, the frontend
        moved off core/api.ts-style URL literals and the suite is blind."""
        frontend = _frontend_paths()
        for probe in (
            "/api/watchlist",
            "/api/dashboard/widgets",
            "/api/chart/ohlc",
            "/api/trades/annotations",
            "/api/discover/fallback",
        ):
            assert probe in frontend, f"extractor missed {probe}"

    @pytest.mark.parametrize(("path", "methods"), sorted(CONSUMED.items()))
    def test_consumed_endpoint_registered_with_method(self, path: str, methods: set[str]) -> None:
        registered = API_ROUTES.get(path)
        assert registered is not None, f"{path} missing from the app"
        missing_methods = methods - registered
        assert not missing_methods, f"{path} lacks methods {sorted(missing_methods)}"

    @pytest.mark.parametrize("path", WS_PATHS)
    def test_websocket_path_is_registered(self, path: str) -> None:
        assert path in WS_ROUTES, f"{path} missing; registered WS paths: {sorted(WS_ROUTES)}"

    @pytest.mark.parametrize("source", WS_MONITOR_SOURCES)
    def test_monitor_feed_websocket_source_is_registered(self, source: str) -> None:
        assert "/api/monitor/{source}" in WS_ROUTES
        # and the id the widget sends is a valid feed source server-side
        from modules.dashboard.routes import EXTERNAL_FEED_SOURCES

        assert source in EXTERNAL_FEED_SOURCES


class _ContractBase:
    """Every live-contract test needs the same three things: a throwaway DB,
    a TestClient over the real app, and no outbound network. All three come
    from tests/conftest.py so a fix to one suite cannot leave the others
    reaching for the real config store.
    """

    @pytest.fixture()
    def client(self, app_client: TestClient) -> TestClient:
        return app_client

    @pytest.fixture()
    def raw_client(self, raw_app_client: TestClient) -> TestClient:
        """Surfaces server-side exceptions as real 500s, for routes with no
        wrap_provider_errors safety net."""
        return raw_app_client


def _session_on_disk(session: str) -> bool:
    """Whether the daily database holds a bar for *session*.

    Read through the study module rather than a second DuckDB handle: this is
    the same question `available_dates` answers, asked independently.
    """
    from modules.reports.study import has_session

    return has_session(session)


class TestLiveContracts(_ContractBase):
    # ── watchlist ──
    # Mutations are POST with a JSON body; a GET must never change data.
    @staticmethod
    def _wl(client: TestClient, action: str, symbol: str = "", data: str | None = None):
        return client.post("/api/watchlist", json={"action": action, "symbol": symbol, "data": data})

    def test_watchlist_round_trip(self, client: TestClient) -> None:
        resp = self._wl(client, "add", "aapl")
        assert resp.status_code == 200
        body = client.get("/api/watchlist").json()
        assert [i["symbol"] for i in body["watchlist"]] == ["AAPL"]

        resp = self._wl(client, "remove", "AAPL")
        assert resp.status_code == 200
        assert client.get("/api/watchlist").json()["watchlist"] == []

    def test_watchlist_get_refuses_mutations(self, client: TestClient) -> None:
        resp = client.get("/api/watchlist", params={"action": "add", "symbol": "NVDA"})
        assert resp.status_code == 405
        assert client.get("/api/watchlist").json()["watchlist"] == []

    def test_watchlist_save_rejects_non_array(self, client: TestClient) -> None:
        resp = self._wl(client, "save", data=json.dumps({"symbol": "AAPL"}))
        assert resp.status_code == 400
        assert resp.json()["detail"].startswith("Watchlist data must be a JSON array")

    def test_watchlist_save_rejects_bad_json(self, client: TestClient) -> None:
        resp = self._wl(client, "save", data="{not json")
        assert resp.status_code == 400
        assert resp.json()["detail"].startswith("Invalid JSON")

    def test_watchlist_save_round_trip(self, client: TestClient) -> None:
        payload = [{"symbol": "MSFT", "addedAt": "2026-09-25T10:00:00"}]
        resp = self._wl(client, "save", data=json.dumps(payload))
        assert resp.status_code == 200
        body = client.get("/api/watchlist").json()
        assert body["watchlist"][0]["symbol"] == "MSFT"
        assert body["watchlist"][0]["addedAt"] == "2026-09-25T10:00:00"

    def test_watchlist_clear(self, client: TestClient) -> None:
        self._wl(client, "add", "TSLA")
        assert self._wl(client, "clear").status_code == 200
        assert client.get("/api/watchlist").json()["watchlist"] == []

    # ── filters ──
    def test_filters_crud(self, client: TestClient) -> None:
        from modules.settings.routes import DEFAULT_FILTERS

        by_name = sorted(DEFAULT_FILTERS, key=lambda f: str(f["name"]))
        assert client.get("/api/filters").json()["filters"] == by_name
        created = client.post("/api/filters", json={"name": "my filter", "expression": "price > vwap"})
        assert created.status_code == 200
        assert created.json()["filters"] == sorted(
            [*by_name, {"name": "my filter", "expression": "price > vwap"}],
            key=lambda f: str(f["name"]),
        )
        # upsert on the same name
        client.post("/api/filters", json={"name": "my filter", "expression": "gap_pct > 5"})
        assert client.get("/api/filters").json()["filters"][-1]["expression"] == "gap_pct > 5"
        deleted = client.delete("/api/filters/my filter")
        assert deleted.status_code == 200
        assert client.get("/api/filters").json()["filters"] == by_name

    # ── dashboard tabs ──
    def test_dashboard_tabs_lifecycle(self, client: TestClient) -> None:
        tabs = client.get("/api/dashboard/tabs").json()["tabs"]
        assert len(tabs) == 1 and tabs[0]["id"] == 1
        created = client.post("/api/dashboard/tabs", json={"name": "Crypto", "position": 1})
        assert created.status_code == 200
        assert created.json()["name"] == "Crypto"
        tab_id = created.json()["id"]
        renamed = client.put(f"/api/dashboard/tabs/{tab_id}", json={"name": "Crypto2"})
        assert renamed.json()["name"] == "Crypto2"
        assert client.put(f"/api/dashboard/tabs/{tab_id}", json={"name": "  "}).status_code == 400
        assert client.put("/api/dashboard/tabs/999", json={"name": "x"}).status_code == 404
        assert client.delete("/api/dashboard/tabs/1").status_code == 400  # default tab
        assert client.delete(f"/api/dashboard/tabs/{tab_id}").json() == {"success": True}

    # ── dashboard widgets ──
    def test_dashboard_widget_lifecycle(self, client: TestClient) -> None:
        assert client.get("/api/dashboard/widgets").json() == {"widgets": []}
        created = client.post(
            "/api/dashboard/widgets",
            json={"type": "watchlist", "config_ref": {}, "position": 2, "col_span": 2, "tab_id": 1},
        )
        assert created.status_code == 200
        widget = created.json()
        assert widget["type"] == "watchlist" and widget["position"] == 2 and widget["col_span"] == 2
        updated = client.put(
            f"/api/dashboard/widgets/{widget['id']}",
            json={"type": "watchlist", "config_ref": {}, "position": 5, "muted": True},
        )
        assert updated.json()["position"] == 5 and updated.json()["muted"] is True
        assert client.put("/api/dashboard/widgets/999", json={"type": "watchlist", "config_ref": {}}).status_code == 404
        assert client.delete(f"/api/dashboard/widgets/{widget['id']}").json() == {"success": True}

    def test_dashboard_widget_validation_errors(self, client: TestClient) -> None:
        # unknown widget type is a 422 (Literal type)
        assert client.post("/api/dashboard/widgets", json={"type": "nope", "config_ref": {}}).status_code == 422
        # a symbol widget may omit its symbol and follow the dashboard selection
        resp = client.post("/api/dashboard/widgets", json={"type": "chart", "config_ref": {}})
        assert resp.status_code == 200
        # a symbol that is present must be text
        resp = client.post("/api/dashboard/widgets", json={"type": "chart", "config_ref": {"symbol": 42}})
        assert resp.status_code == 400 and "symbol" in resp.json()["detail"]
        # unknown at_risk tab
        resp = client.post("/api/dashboard/widgets", json={"type": "at_risk", "config_ref": {"tab": "moon"}})
        assert resp.status_code == 400 and "tab" in resp.json()["detail"]
        # out-of-range layout
        resp = client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "col_span": 9})
        assert resp.status_code == 400 and "col_span" in resp.json()["detail"]
        resp = client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "row_height": 10})
        assert resp.status_code == 400 and "row_height" in resp.json()["detail"]
        # unknown external feed source
        resp = client.post("/api/dashboard/widgets", json={"type": "external_feed", "config_ref": {"source": "rss"}})
        assert resp.status_code == 400 and "source" in resp.json()["detail"]

    def test_dashboard_custom_widget_validation(self, client: TestClient) -> None:
        ok = {"url": "/api/bankruptcy", "columns": ["symbol", "filed_at"]}
        assert client.post("/api/dashboard/widgets", json={"type": "custom", "config_ref": ok}).status_code == 200

        # The URL must stay on this server's own /api surface: a stored widget
        # is a persistent, auto-refreshing request the user may forget about.
        for bad_url in ("https://evil.example/api/x", "//evil.example/api/x", "/static/x", "api/x", "/api/..\\x"):
            resp = client.post(
                "/api/dashboard/widgets",
                json={"type": "custom", "config_ref": {**ok, "url": bad_url}},
            )
            assert resp.status_code == 400, bad_url
            assert "url" in resp.json()["detail"]

        for bad_columns in ([], "symbol", [""], [1], ["ok"] * 9):
            resp = client.post(
                "/api/dashboard/widgets",
                json={"type": "custom", "config_ref": {**ok, "columns": bad_columns}},
            )
            assert resp.status_code == 400, bad_columns
            assert "columns" in resp.json()["detail"]

        for bad_limit in (0, 201, "10", True):
            resp = client.post(
                "/api/dashboard/widgets",
                json={"type": "custom", "config_ref": {**ok, "limit": bad_limit}},
            )
            assert resp.status_code == 400, bad_limit
            assert "limit" in resp.json()["detail"]

        # Optional keys: absent rows_path and a present one both round-trip.
        created = client.post(
            "/api/dashboard/widgets",
            json={"type": "custom", "config_ref": {**ok, "rows_path": "data.results", "limit": 10}},
        ).json()
        assert created["config_ref"]["rows_path"] == "data.results"
        assert created["config_ref"]["limit"] == 10

    def test_dashboard_widgets_tab_filter(self, client: TestClient) -> None:
        client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "tab_id": 1})
        tab = client.post("/api/dashboard/tabs", json={"name": "Two"}).json()
        client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "tab_id": tab["id"]})
        all_widgets = client.get("/api/dashboard/widgets").json()["widgets"]
        assert len(all_widgets) == 2
        filtered = client.get("/api/dashboard/widgets", params={"tab_id": tab["id"]}).json()["widgets"]
        assert [w["tab_id"] for w in filtered] == [tab["id"]]

    def test_external_feed_sources_catalog(self, client: TestClient) -> None:
        body = client.get("/api/dashboard/external-feed-sources").json()
        ids = {s["id"] for s in body["sources"]}
        assert {"momo", "titan", "titan_news", "titan_filings", "titan_halts"} <= ids
        for source in body["sources"]:
            assert source["label"] and source["ws_path"].startswith("/api/monitor/")

    # ── bankruptcy dismiss ──
    def test_bankruptcy_dismiss_round_trip(self, client: TestClient) -> None:
        resp = client.post("/api/bankruptcy/dismiss", json=["AAPL", "TSLA"])
        assert resp.status_code == 200
        assert resp.json() == {"success": True, "dismissed": 2}
        dismissed = client.get("/api/bankruptcy/dismissed").json()
        assert sorted(d["symbol"] for d in dismissed["dismissed"]) == ["AAPL", "TSLA"]
        assert client.request("DELETE", "/api/bankruptcy/dismiss", json=["AAPL"]).json()["undismissed"] == 1
        after = client.get("/api/bankruptcy/dismissed").json()["dismissed"]
        assert [d["symbol"] for d in after] == ["TSLA"]

    def test_bankruptcy_dismiss_rejects_missing_body(self, client: TestClient) -> None:
        assert client.post("/api/bankruptcy/dismiss").status_code == 422

    # ── signals history ──
    def test_signals_history_filters(self, client: TestClient) -> None:
        db.add_signal(
            {
                "symbol": "AAPL",
                "signal": "crossing_vwap",
                "timestamp": 1.0,
                "price": 100.0,
                "stop": 95.0,
                "target": 110.0,
                "confidence": 0.9,
                "retracement_pct": 0.1,
                "reason": "test",
                "created_at": "2026-09-25",
            },
            config_id=7,
        )
        db.add_signal(
            {
                "symbol": "MSFT",
                "signal": "crossing_vwap",
                "timestamp": 2.0,
                "price": 50.0,
                "stop": 48.0,
                "target": 55.0,
                "confidence": 0.8,
                "retracement_pct": 0.2,
                "reason": "test",
                "created_at": "2026-09-25",
            },
            config_id=8,
        )
        all_signals = client.get("/api/signals/history").json()["signals"]
        assert len(all_signals) == 2
        by_symbol = client.get("/api/signals/history", params={"symbol": "aapl"}).json()["signals"]
        assert [s["symbol"] for s in by_symbol] == ["AAPL"]
        by_config = client.get("/api/signals/history", params={"config_id": 8}).json()["signals"]
        assert [s["config_id"] for s in by_config] == [8]
        by_outcome = client.get("/api/signals/history", params={"outcome": "win"}).json()["signals"]
        assert by_outcome == []
        # validation bounds
        assert client.get("/api/signals/history", params={"limit": 0}).status_code == 422
        assert client.get("/api/signals/history", params={"limit": 501}).status_code == 422

    # ── signals metrics ──
    def test_signals_metrics_rolls_up_by_signal_type(self, client: TestClient) -> None:
        seeded = 0

        def seed(signal: str, outcome: str, config_id: int) -> None:
            nonlocal seeded
            seeded += 1
            signal_id = db.add_signal(
                {
                    "symbol": "AAPL",
                    "signal": signal,
                    # add_signal is INSERT OR IGNORE over a uniqueness key, so
                    # each seed needs its own timestamp to be stored at all.
                    "timestamp": float(seeded),
                    "price": 100.0,
                    "stop": 95.0,
                    "target": 110.0,
                    "confidence": 0.5,
                    "retracement_pct": 0.1,
                    "reason": "test",
                    "created_at": "2026-09-25",
                },
                config_id=config_id,
            )
            assert signal_id is not None, "the seed row was rejected as a duplicate"
            if outcome != "pending":
                db.set_signal_outcome(signal_id, outcome=outcome)

        # No rows yet: "nothing resolved" must not read as a 0% hit rate.
        empty = client.get("/api/signals/metrics").json()
        assert empty["total"] == 0
        assert empty["win_rate"] is None

        seed("crossing_vwap", "win", 3)
        seed("crossing_vwap", "loss", 3)
        seed("breakout", "win", 3)
        seed("breakout", "pending", 4)

        pooled = client.get("/api/signals/metrics").json()
        assert pooled["total"] == 4
        assert pooled["wins"] == 2
        assert pooled["losses"] == 1
        # An unresolved signal is pending, never counted as a loss.
        assert pooled["pending"] == 1
        assert pooled["win_rate"] == 2 / 3
        by_signal = {row["signal"]: row for row in pooled["by_signal"]}
        assert by_signal["crossing_vwap"]["wins"] == 1
        assert by_signal["crossing_vwap"]["pending"] == 0
        assert by_signal["breakout"]["wins"] == 1
        assert by_signal["breakout"]["pending"] == 1
        assert by_signal["breakout"]["losses"] == 0

        scoped = client.get("/api/signals/metrics", params={"config_id": 3}).json()
        assert scoped["total"] == 3
        assert [row["signal"] for row in scoped["by_signal"]] == ["crossing_vwap", "breakout"]

    # ── symbol-flags delete path (contract others don't cover) ──
    def test_symbol_flag_delete_404(self, client: TestClient) -> None:
        assert client.delete("/api/symbol-flags/424242").status_code == 404

    # ── reports section ──
    def test_reports_dates_are_sessions_the_database_actually_has(self, client: TestClient) -> None:
        """The picker must not offer a day the study cannot answer for.

        The market calendar runs to 2029, so deriving the list from it would
        offer 260 dates with no data behind them.
        """
        body = client.get("/api/reports/dates").json()
        assert body["dates"], "the daily database should yield sessions"
        assert body["dates"] == sorted(body["dates"], reverse=True)
        assert body["latest"] == body["dates"][0]
        assert body["latest"] <= date.today().isoformat()
        assert _session_on_disk(body["latest"]), f"{body['latest']} has no daily bars"

    def test_reports_dates_ships_the_plan_the_page_paints_into_its_boxes(self, client: TestClient) -> None:
        """The defaults the page shows have to be the defaults it gets.

        The page fills its plan boxes from here, so a second copy of the
        numbers in the frontend would be a default that quietly stops being
        true. The two that are empty stay empty, and the assertion is that they
        build the plan the endpoint claims -- not that they merely parse.
        """
        from modules.reports.plan import build_plan

        body = client.get("/api/reports/dates").json()
        shown = body["plan_defaults"]
        assert set(shown) == {
            "entry",
            "trigger",
            "tp1",
            "tp1_size",
            "tp2",
            "stop",
            "breakeven",
        }
        # Empty is the default for these two and there is no text to put there.
        assert shown["trigger"] == ""
        assert shown["tp2"] == ""

        plan = build_plan(
            entry=shown["entry"],
            tp1=shown["tp1"],
            tp1_size=shown["tp1_size"],
            stop=shown["stop"],
            breakeven=shown["breakeven"],
        )
        assert plan.entry_expr == shown["entry"]
        assert plan.targets[0].offset == 20.0
        assert plan.targets[0].size == 1.0
        assert plan.stop_pct == 1.0
        assert plan.breakeven is False

    def test_reports_dates_defaults_are_what_an_empty_request_measures(self, client: TestClient) -> None:
        """The boxes have to describe the study a request with nothing in it runs.

        Otherwise the page states a plan and silently measures another one, which
        is the failure the whole section is about: numbers that answer a
        question nobody asked.
        """
        from modules.reports import service

        shown = client.get("/api/reports/dates").json()["plan_defaults"]
        session = client.get("/api/reports/dates").json()["latest"]
        assert _session_on_disk(session), f"{session} has no daily bars"
        # An empty plan and the shown plan are the same plan, so the level,
        # the targets and the stop the page prints are the ones measured.
        assert service.build_plan() == service.build_plan(
            entry=shown["entry"],
            tp1=shown["tp1"],
            tp1_size=shown["tp1_size"],
            stop=shown["stop"],
            breakeven=shown["breakeven"],
        )

    def test_reports_candidates_rejects_a_non_iso_date(self, client: TestClient) -> None:
        resp = client.get("/api/reports/candidates", params={"date": "28-10-2025", "filter": "close > 1"})
        assert resp.status_code == 422
        assert "YYYY-MM-DD" in resp.json()["detail"]

    def test_reports_candidates_requires_a_filter(self, client: TestClient) -> None:
        """No filter, no universe: the study measures what an expression selects."""
        resp = client.get("/api/reports/candidates", params={"date": "2026-01-05"})
        assert resp.status_code == 422
        assert "filter is required" in resp.json()["detail"]

    def test_reports_candidates_says_a_filter_matched_nothing(self, client: TestClient) -> None:
        """A parseable filter that selects no name is its own answer.

        Distinct from a date with no bars: the day exists, the expression just
        excludes everything on it, and the two want different fixes.
        """
        session = client.get("/api/reports/dates").json()["latest"]
        assert _session_on_disk(session), f"{session} has no daily bars"
        resp = client.get(
            "/api/reports/candidates",
            params={"date": session, "filter": "close > 100000"},
        )
        assert resp.status_code == 422
        assert f"No names matched the filter on {session}" in resp.json()["detail"]

    def test_reports_candidates_rejects_an_unparseable_filter(self, client: TestClient) -> None:
        """The compiler's own wording reaches the caller, not a stack trace."""
        session = client.get("/api/reports/dates").json()["latest"]
        resp = client.get(
            "/api/reports/candidates",
            params={"date": session, "filter": "close >< nonsense"},
        )
        assert resp.status_code == 422
        assert resp.json()["detail"]

    def test_reports_candidates_rejects_a_date_with_no_bars(self, client: TestClient) -> None:
        """A well-formed date the database has never heard of is a 422, not a 500."""
        resp = client.get("/api/reports/candidates", params={"date": "1999-01-04", "filter": "close > 1"})
        assert resp.status_code == 422
        assert "No daily bars" in resp.json()["detail"]

    @pytest.mark.parametrize(
        "plan",
        [
            {"tp1": "1.2"},
            {"tp1": "0"},
            {"tp2": "40%"},
            {"tp1": "5%", "tp2": "3%"},
            {"tp1_size": "150%"},
            {"tp1_size": "half"},
            {"stop": "abc"},
            # `close >< nope` parses to a comparison with no right operand, so a
            # parse-only check accepts it and every name fills unfiltered.
            {"trigger": "close >< nope"},
            {"trigger": "nope_column > 1"},
        ],
    )
    def test_reports_candidates_refuses_a_plan_it_cannot_measure(self, client: TestClient, plan: dict) -> None:
        """A plan the parser cannot read is a 422 carrying its own wording.

        The study is a measurement of one particular trade, so a level that
        reads as something other than what was written is worse than a refusal:
        it returns numbers, and the numbers answer a question nobody asked.
        """
        session = client.get("/api/reports/dates").json()["latest"]
        resp = client.get(
            "/api/reports/candidates",
            params={"date": session, "filter": "close > 1", **plan},
        )
        assert resp.status_code == 422
        assert resp.json()["detail"]

    def test_dilution_page_redirects_to_its_own_document(self, client: TestClient) -> None:
        """The Dilution Profile is a page of its own, so /dilution forwards to it.

        `symbol` is the whole identity of the link, so a bookmark or shared URL
        that names one has to land on that symbol's profile.
        """
        resp = client.get(
            "/dilution",
            params={"symbol": "AAPL"},
            follow_redirects=False,
        )
        assert resp.status_code == 307
        assert resp.headers["location"] == "/research?view=dilution&symbol=AAPL"

    def test_dilution_page_redirect_drops_a_stale_tab(self, client: TestClient) -> None:
        """A bare /dilution has no query, and a stale `tab` from the old At Risk tab is dropped.

        The tab named a screen of At Risk, which this page no longer is, so it
        must not follow the reader onto the profile.
        """
        resp = client.get("/dilution", follow_redirects=False)
        assert resp.status_code == 307
        assert resp.headers["location"] == "/research?view=dilution"

        resp = client.get(
            "/dilution",
            params={"symbol": "AAPL", "tab": "holders"},
            follow_redirects=False,
        )
        assert resp.status_code == 307
        assert resp.headers["location"] == "/research?view=dilution&symbol=AAPL"

    def test_dilution_registrations_answers_a_valid_symbol(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """`/api/dilution/<symbol>/registrations` answers 200 for a well-formed ticker.

        The SEC payload is stubbed: this asserts the route's contract, not what
        EDGAR says about AAPL today. Unstubbed it was a live SEC round trip that
        cost 79s of the suite's wall clock and whose result depended on the
        filings of the day.
        """
        monkeypatch.setattr(
            "modules.dilution.routes.fetch_sec_submissions",
            lambda *args, **kwargs: {"filings": {"recent": {"form": [], "filingDate": []}}},
        )
        resp = client.get("/api/dilution/AAPL/registrations")
        assert resp.status_code == 200
        body = resp.json()
        assert body["ticker"] == "AAPL"
        assert body["registrations"] == []
        assert body["error"] is None

    def test_at_risk_page_redirect_carries_the_tab_query(self, client: TestClient) -> None:
        """The query is the tab's identity, so /at-risk forwards it.

        The client resolves `?tab=` (and the dilution profile's `symbol`)
        from the query it is served with; dropping it here would undo the
        /dilution legacy redirect's work and land every bookmark on a page
        with no screen open.
        """
        resp = client.get(
            "/at-risk",
            params={"tab": "dilution", "symbol": "AAPL"},
            follow_redirects=False,
        )
        assert resp.status_code == 307
        assert resp.headers["location"] == "/static/at-risk.html?tab=dilution&symbol=AAPL"

        resp = client.get("/at-risk", follow_redirects=False)
        assert resp.status_code == 307
        assert resp.headers["location"] == "/static/at-risk.html"

    def test_reports_page_redirects_to_the_backtest_tab(self, client: TestClient) -> None:
        """/reports is now the Reports tab of /backtest, not a page of its own.

        The query is the study's identity -- which session, measured by which
        filter -- so a link or bookmark that names one has to land on that same
        study, not on the run tab with the study thrown away.
        """
        resp = client.get(
            "/reports",
            params={"date": "2026-09-25", "filter": "gap_pct > 5"},
            follow_redirects=False,
        )
        assert resp.status_code in (302, 307)
        location = resp.headers["location"]
        assert location.startswith("/backtest?")
        assert "tab=reports" in location
        assert "date=2026-09-25" in location
        assert "gap_pct" in location

    def test_reports_page_redirect_carries_no_stale_parameters(self, client: TestClient) -> None:
        """A bare /reports still names the tab, and the API routes are untouched."""
        resp = client.get("/reports", follow_redirects=False)
        assert resp.status_code in (302, 307)
        assert resp.headers["location"] == "/backtest?tab=reports"

        assert client.get("/api/reports/dates").status_code == 200

    # ── playbook CRUD ──
    def test_playbook_crud_round_trip(self, client: TestClient) -> None:
        assert client.get("/api/playbook").json() == {"setups": []}
        created = client.post("/api/playbook", json={"name": "Gap and go", "category": "momentum"})
        assert created.status_code == 200
        setup = created.json()
        assert setup["name"] == "Gap and go"
        assert setup["screenshots"] == []
        updated = client.put(f"/api/playbook/{setup['id']}", json={"name": "Gap 'n go", "notes": "premarket"})
        assert updated.json()["name"] == "Gap 'n go"
        assert client.put("/api/playbook/999", json={"name": "x"}).status_code == 404
        assert client.delete(f"/api/playbook/{setup['id']}").json() == {"success": True}
        assert client.delete("/api/playbook/999").status_code == 404
        assert client.get("/api/playbook").json() == {"setups": []}

    # ── trades (provider-agnostic surface) ──
    def test_trades_status_shape(self, client: TestClient) -> None:
        resp = client.get("/api/trades/status")
        assert resp.status_code == 200
        body = resp.json()
        assert {"status", "has_api_credentials", "has_token_file", "callback_url"} <= set(body)

    def test_trades_transactions_unauthenticated_is_empty(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # The provider is stubbed unauthenticated: on a machine with a real
        # ~/.schwab_token.json the status route would authenticate the shared
        # client, and this test would read that machine's cached trades.
        class _UnauthenticatedProvider:
            def get_status(self) -> dict[str, object]:
                return {"status": "no_token"}

            def load_cached_transactions(self) -> list[dict[str, object]] | None:
                return None

        monkeypatch.setattr("modules.trades.routes.get_trade_provider", _UnauthenticatedProvider)
        resp = client.get("/api/trades/transactions")
        assert resp.status_code == 200
        body = resp.json()
        assert body["count"] == 0 and body["transactions"] == []

    def test_trades_cached_transactions_are_not_served_for_another_account(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # trades_cache is one row for the whole app: a request naming a
        # different account (or a wider window) must not be answered with the
        # cached account's fills under the currently resolved account number.
        class _CachedOtherAccountProvider:
            def __init__(self) -> None:
                self.fetched: list[tuple[int, str | None]] = []

            def is_authenticated(self) -> bool:
                return True

            def get_status(self) -> dict[str, object]:
                return {
                    "status": "authenticated",
                    "account_number": "RESOLVED",
                    "cache": {"account": "OTHER", "days": 30, "transaction_count": 1},
                }

            def load_cached_transactions(self) -> list[dict[str, object]]:
                return [{"transaction_id": "cached-one", "symbol": "OTHER"}]

            def load_transactions(self, days: int = 30, account: str | None = None) -> list[dict[str, object]]:
                self.fetched.append((days, account))
                return [{"transaction_id": "fresh", "symbol": "MINE"}]

        provider = _CachedOtherAccountProvider()
        monkeypatch.setattr("modules.trades.routes.get_trade_provider", lambda: provider)

        same = client.get("/api/trades/transactions", params={"account": "OTHER"}).json()
        assert same["cached"] is True
        assert same["account_number"] == "OTHER"

        other = client.get("/api/trades/transactions", params={"account": "MINE"}).json()
        assert other["cached"] is False
        assert other["transactions"] == [{"transaction_id": "fresh", "symbol": "MINE"}]
        assert provider.fetched == [(30, "MINE")]

        wider = client.get("/api/trades/transactions", params={"days": 90}).json()
        assert wider["cached"] is False
        assert provider.fetched[-1] == (90, None)

    def test_trades_annotations_round_trip(self, client: TestClient) -> None:
        assert client.get("/api/trades/annotations").json() == {"annotations": []}
        saved = client.post(
            "/api/trades/annotations/2026-09-25 AAPL 1",
            json={"tags": ["gap"], "playbook_setup_id": None, "notes": "clean break"},
        )
        assert saved.status_code == 200
        assert saved.json()["trade_key"] == "2026-09-25 AAPL 1"
        listed = client.get("/api/trades/annotations").json()["annotations"]
        assert len(listed) == 1 and listed[0]["notes"] == "clean break"

    def test_trades_auth_callback_requires_redirect_url(self, client: TestClient) -> None:
        resp = client.post("/api/trades/auth/callback", json={"redirect_url": ""})
        assert resp.status_code == 400
        assert "redirect_url" in resp.json()["detail"]

    # ── at-risk generic screen ──
    def test_at_risk_unknown_screen_404(self, client: TestClient) -> None:
        resp = client.get("/api/at-risk/screen/does-not-exist")
        assert resp.status_code == 404

    # ── hf settings surface ──
    def test_hf_sync_progress_shape(self, client: TestClient) -> None:
        body = client.get("/api/hf/sync/progress").json()
        assert {"active", "stage", "detail", "batches_done", "batches_total"} <= set(body)

    def test_hf_status_shape(self, client: TestClient) -> None:
        body = client.get("/api/hf/status").json()
        assert {"repo", "token_set", "last_sync"} <= set(body)

    def test_hf_push_success_contract(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr("modules.settings.routes.hf_manager.push_config", lambda: True)
        assert client.post("/api/hf/push-config").json() == {"success": True}

    def test_hf_restore_starts_in_background_and_reports_outcome(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """Restore must answer immediately and report the real outcome later.

        It used to be awaited inside the request (a full app_state.db
        download plus an import that holds the DB lock), which blocked the
        caller for the whole transfer.
        """
        gate = threading.Event()

        def fake_restore() -> bool:
            gate.wait(timeout=30)
            return True

        monkeypatch.setattr("modules.settings.routes.hf_manager.restore_config", fake_restore)

        started = client.post("/api/hf/restore-config").json()
        assert started["status"] == "started"
        assert client.get("/api/hf/restore-config").json()["status"] == "running"
        # A second POST while one is in flight must not start a duplicate
        # import against the same connection.
        assert client.post("/api/hf/restore-config").json()["status"] == "running"

        gate.set()
        deadline = time.monotonic() + 30
        status = "running"
        while time.monotonic() < deadline:
            status = client.get("/api/hf/restore-config").json()["status"]
            if status != "running":
                break
            time.sleep(0.02)
        assert status == "ok"

    def test_hf_restore_failure_is_reported_not_raised(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        def boom() -> bool:
            raise RuntimeError("hf down")

        monkeypatch.setattr("modules.settings.routes.hf_manager.restore_config", boom)
        assert client.post("/api/hf/restore-config").json()["status"] == "started"
        deadline = time.monotonic() + 30
        body: dict[str, str] = {}
        while time.monotonic() < deadline:
            body = client.get("/api/hf/restore-config").json()
            if body["status"] == "error":
                break
            time.sleep(0.02)
        assert body["status"] == "error"
        assert "hf down" in body["detail"]

    def test_db_lock_stats_shape(self, client: TestClient) -> None:
        body = client.get("/api/db/lock-stats").json()
        assert {"acquisitions", "hold_seconds", "max_hold_seconds", "wait_seconds", "max_wait_seconds"} <= set(
            body["totals"]
        )
        assert isinstance(body["by_operation"], dict)

    # ── screener cache clear ──
    def test_screener_clear_finviz_cache(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.screener.routes.clear_finviz_cache",
            lambda: {"symbols": 3},
        )
        body = client.post("/api/screener/clear-finviz-cache").json()
        assert body["status"] == "success" and body["cleared"] == {"symbols": 3}

    # ── backtest surface ──
    def test_backtest_status_shape(self, client: TestClient) -> None:
        body = client.get("/api/backtest/status").json()
        assert body["state"] in ("idle", "running", "paused")
        for key in ("processed", "total", "error", "warning"):
            assert key in body

    def test_backtest_alert_configs_round_trip(self, client: TestClient) -> None:
        assert client.get("/api/backtest/alert-configs").json() == {"alert_configs": []}
        created = client.post(
            "/api/backtest/alert-configs",
            json={"name": "vwap break", "detector_expression": "close > 5"},
        )
        assert created.status_code == 200
        config = created.json()
        assert config["detector_types"] == ["dsl_expression"]
        updated = client.put(
            f"/api/backtest/alert-configs/{config['id']}",
            json={"name": "vwap break 2", "detector_expression": "close < 5"},
        )
        assert updated.json()["name"] == "vwap break 2"
        assert (
            client.put(
                "/api/backtest/alert-configs/999", json={"name": "nope", "detector_expression": "close > 1"}
            ).status_code
            == 404
        )
        assert client.delete(f"/api/backtest/alert-configs/{config['id']}").json() == {"success": True}

    def test_backtest_alert_config_validation(self, client: TestClient) -> None:
        resp = client.post("/api/backtest/alert-configs", json={"name": "  "})
        assert resp.status_code == 400 and "Name" in resp.json()["detail"]
        resp = client.post("/api/backtest/alert-configs", json={"name": "no logic"})
        assert resp.status_code == 400 and "condition" in resp.json()["detail"].lower()
        resp = client.post(
            "/api/backtest/alert-configs",
            json={"name": "bad expr", "detector_expression": "close >"},
        )
        assert resp.status_code == 400
        resp = client.post(
            "/api/backtest/alert-configs",
            json={"name": "bad detector", "detector_types": ["moon_phase"]},
        )
        assert resp.status_code == 400 and "Unsupported" in resp.json()["detail"]

    def test_backtest_alert_elements_catalog(self, client: TestClient) -> None:
        body = client.get("/api/backtest/alert-elements/catalog").json()
        assert isinstance(body["elements"], list) and body["elements"]
        for element in body["elements"]:
            assert "key" in element

    def test_backtest_start_rejects_unknown_config(self, client: TestClient) -> None:
        resp = client.post(
            "/api/backtest/start",
            json={"date": "2026-09-25", "from_time": "09:30", "to_time": "16:00", "alert_config_id": 424242},
        )
        assert resp.status_code == 400
        assert "not found" in resp.json()["detail"]

    # ── level2 subscribe response shape (refcounted, no WS needed) ──
    def test_level2_subscribe_rejects_missing_symbol(self, client: TestClient) -> None:
        assert client.post("/api/level2/subscribe").status_code == 422

    # ── discover groups ──
    def test_discover_patterns_returns_the_group_shape(self, client: TestClient) -> None:
        resp = client.post("/api/discover/patterns", json={"session": "momentum", "rows": [], "min_support": 4})
        assert resp.status_code == 200
        body = resp.json()
        assert body["status"] == "success"
        assert body["universe_size"] == 0
        assert body["described_count"] == 0
        assert body["groups"] == []

    def test_discover_patterns_rejects_bad_support(self, client: TestClient) -> None:
        assert client.post("/api/discover/patterns", json={"rows": [], "min_support": 99}).status_code == 422
        assert client.post("/api/discover/patterns", json={"rows": [], "min_support": 1}).status_code == 422

    def test_discover_patterns_ignores_intraday(self, client: TestClient) -> None:
        """`include_intraday` is gone from the request, and cannot be smuggled back in."""
        assert "include_intraday" not in DiscoverPatternRequest.model_fields
        resp = client.post("/api/discover/patterns", json={"rows": [], "include_intraday": True})
        assert resp.status_code == 200
        assert resp.json()["groups"] == []

    # ── llm ──
    def test_llm_model_rejects_unknown_model(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        class _FakeAgent:
            model = "m1"

            async def get_available_models(self):
                return ["m1"]

        monkeypatch.setattr("app.main.get_llm_agent", lambda: _FakeAgent())
        resp = client.post("/api/llm/model", json={"model": "nope"})
        assert resp.status_code == 400
        assert "not available" in resp.json()["detail"]


class TestValidationErrors(_ContractBase):
    """Validation errors on read endpoints the frontend builds URLs for."""

    def test_scan_rejects_bad_filter(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("must not run")),
        )
        resp = client.get("/api/scan", params={"filter": "close >", "symbols": ""})
        # A malformed expression is the caller's input: 400, not a server fault (decided 2026-10-17).
        assert resp.status_code == 400
        assert "Unexpected end" in resp.json()["detail"]

    @pytest.mark.parametrize("limit", [-1, 0, 1001])
    def test_scan_rejects_out_of_range_limit(self, client: TestClient, limit: int) -> None:
        resp = client.get("/api/scan", params={"limit": limit})
        assert resp.status_code == 422

    @pytest.mark.parametrize("limit", [250, 1000])
    def test_scan_accepts_in_range_limit(self, client: TestClient, monkeypatch: pytest.MonkeyPatch, limit: int) -> None:
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: ([], False),
        )
        resp = client.get("/api/scan", params={"limit": limit, "symbols": "AAPL"})
        assert resp.status_code == 200


class TestScanLimitInstruction(_ContractBase):
    """`limit N` written in the filter expression, resolved at the boundary."""

    @staticmethod
    def _capture(monkeypatch: pytest.MonkeyPatch) -> list[tuple]:
        """Stub the scan service and capture the arguments it was called with."""
        calls: list[tuple] = []

        def _fake(*args, **kwargs):
            calls.append(args)
            return []

        def _fake_with_flag(*args, **kwargs):
            value = _fake(*args, **kwargs)
            return (value, False) if isinstance(value, list) else (value["results"], False)

        monkeypatch.setattr("modules.scan.routes.scan_service.scan", _fake_with_flag)
        return calls

    def test_the_instruction_becomes_the_request_limit(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        calls = self._capture(monkeypatch)
        resp = client.get("/api/scan", params={"filter": "close > 5 limit 30"})
        assert resp.status_code == 200
        # positional: filter, symbols, timeframe, start, end, limit
        assert calls[0][0] == "close > 5"
        assert calls[0][-1] == 30

    def test_an_explicit_param_beats_the_instruction(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        calls = self._capture(monkeypatch)
        assert client.get("/api/scan", params={"filter": "close > 5 limit 30", "limit": 77}).status_code == 200
        assert calls[0][-1] == 77

    def test_no_limit_anywhere_falls_back_to_the_default(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        calls = self._capture(monkeypatch)
        assert client.get("/api/scan", params={"filter": "close > 5"}).status_code == 200
        assert calls[0][-1] == 250

    def test_the_instruction_never_reaches_the_expression_body(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # The SQL compiler and the calendar's month-pinned plan read this text
        # as a boolean body; a `limit` clause there would be a parse error.
        calls = self._capture(monkeypatch)
        client.get("/api/scan", params={"filter": "close > 5 and volume > 1M sort close desc limit 5"})
        assert calls[0][0] == "close > 5 and volume > 1M sort close desc"

    def test_a_result_count_at_the_cap_is_reported_as_truncated(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: ([{"symbol": "AAA"}] * 2, False),
        )
        body = client.get("/api/scan", params={"filter": "close > 5 limit 2"}).json()
        assert (body["count"], body["truncated"]) == (2, True)

    def test_a_short_result_set_is_not_reported_as_truncated(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: ([{"symbol": "AAA"}], False),
        )
        # A distinct body from the other cases on purpose: the cache key is
        # (stripped filter, limit), so a filter reused across these tests
        # would return the previous case's cached response.
        body = client.get("/api/scan", params={"filter": "close > 9 limit 250"}).json()
        assert (body["count"], body["truncated"]) == (1, False)

    def test_a_malformed_instruction_is_rejected_not_ignored(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        calls = self._capture(monkeypatch)
        # `limit abc` is left in the text by the splitter, so the expression
        # parser is what rejects it -- a typo must not silently scan everything.
        resp = client.get("/api/scan", params={"filter": "close > 5 limit abc"})
        assert resp.status_code == 400
        assert calls == []

    def test_scan_rejects_overlong_filter(self, client: TestClient) -> None:
        resp = client.get("/api/scan", params={"filter": "a" * 3001})
        assert resp.status_code == 400
        assert "too long" in resp.json()["detail"]

    def test_scan_explain_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.explain_scan",
            lambda *args, **kwargs: {"sql": "SELECT 1", "diagnostics": [], "matched_by_clause": {}},
        )
        resp = client.get("/api/scan", params={"explain": "1", "filter": "price > vwap"})
        assert resp.status_code == 200
        body = resp.json()
        assert body["sql"] == "SELECT 1" and body["diagnostics"] == []

    def test_chart_ohlc_rejects_bad_timeframe(self, client: TestClient) -> None:
        resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "2w"})
        assert resp.status_code == 400
        assert "timeframe" in resp.json()["detail"]
        resp = client.get("/api/chart/ohlc", params={"symbol": "", "timeframe": "1d"})
        assert resp.status_code == 400

    def test_chart_ohlc_provider_failure_is_502(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()

        async def _no_bars(symbol: str, timeframe: str):
            return None, None

        monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _no_bars)
        monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {})
        resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"})
        assert resp.status_code == 502
        cache_clear()

    def test_chart_ohlc_success_and_cache(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()
        calls: list[str] = []

        async def _bars(symbol: str, timeframe: str):
            calls.append(f"{symbol}:{timeframe}")
            return [
                {"time": "2026-09-24T14:30:00Z", "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100}
            ], "yahoo"

        monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _bars)
        monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {"close": 1.2})
        resp = client.get("/api/chart/ohlc", params={"symbol": "aapl", "timeframe": "1d"})
        assert resp.status_code == 200
        body = resp.json()
        assert body["symbol"] == "AAPL" and body["source"] == "yahoo"
        assert body["bars"][0]["close"] == 1.5 and body["prev_day"] == {"close": 1.2}
        # second hit served from the (symbol, timeframe) cache, not the provider
        client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"})
        assert calls == ["AAPL:1d"]
        cache_clear()

    def test_stock_catalysts_rejects_bad_date(self, client: TestClient) -> None:
        resp = client.get("/api/stock-catalysts/AAPL", params={"signal_date": "25-09-2026"})
        assert resp.status_code == 400
        assert "YYYY-MM-DD" in resp.json()["detail"]
        resp = client.get("/api/stock-catalysts/AAPL/news", params={"as_of_date": "yesterday"})
        assert resp.status_code == 400
        assert "YYYY-MM-DD" in resp.json()["detail"]

    def test_stock_catalysts_news_success(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.analysis.routes.fetch_press_release",
            lambda symbol, as_of, limit: [{"title": "PR", "url": "https://example.com", "published_at": "2026-09-25"}],
        )
        resp = client.get("/api/stock-catalysts/AAPL/news")
        assert resp.status_code == 200
        assert resp.json()["press_releases"][0]["title"] == "PR"

    def test_market_pulse_empty_symbols_400(self, client: TestClient) -> None:
        resp = client.get("/api/market-pulse/enrich", params={"symbols": " , ,"})
        assert resp.status_code == 400
        assert "No symbols" in resp.json()["detail"]

    def test_market_pulse_too_many_symbols_400(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.market_pulse.routes.get_market_pulse_enrichment",
            lambda symbols: (_ for _ in ()).throw(ValueError("Too many symbols (31); max 30 per request")),
        )
        symbols = ",".join(f"S{i}" for i in range(31))
        resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols})
        assert resp.status_code == 400
        assert "max 30" in resp.json()["detail"]

    def test_market_pulse_30_symbols_accepted(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        seen: list[list[str]] = []

        def fake(symbols: list[str]) -> dict[str, dict[str, float]]:
            seen.append(list(symbols))
            return {s: {"float_shares": 1.0} for s in symbols}

        monkeypatch.setattr("modules.market_pulse.routes.get_market_pulse_enrichment", fake)
        symbols = ",".join(f"S{i}" for i in range(30))
        resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols})
        assert resp.status_code == 200
        assert len(resp.json()) == 30
        assert len(seen) == 1 and len(seen[0]) == 30

    def test_market_pulse_31_symbols_400_from_real_service(self, client: TestClient) -> None:
        symbols = ",".join(f"S{i}" for i in range(31))
        resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols})
        assert resp.status_code == 400
        assert "max 30" in resp.json()["detail"]

    def test_market_pulse_success(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.market_pulse.routes.get_market_pulse_enrichment",
            lambda symbols: {"AAPL": {"float_shares": 1.0}},
        )
        resp = client.get("/api/market-pulse/enrich", params={"symbols": "aapl"})
        assert resp.status_code == 200
        assert resp.json() == {"AAPL": {"float_shares": 1.0}}

    def test_news_batch_empty_symbols_is_empty_map(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.analysis.routes.finviz.fetch_news_bulk",
            lambda symbols: (_ for _ in ()).throw(AssertionError("must not run")),
        )
        resp = client.get("/api/news/batch", params={"symbols": ""})
        assert resp.status_code == 200
        assert resp.json() == {}

    def test_news_batch_dedupes_and_caches(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared import cache

        cache.cache_clear()
        calls: list[list[str]] = []

        def _bulk(symbols: list[str]) -> dict[str, object]:
            calls.append(list(symbols))
            return {"AAPL": {"headline": "hi", "url": "u", "created_at": "t", "source": "finviz"}}

        monkeypatch.setattr("modules.analysis.routes.finviz.fetch_news_bulk", _bulk)
        resp = client.get("/api/news/batch", params={"symbols": "aapl,AAPL,msft"})
        assert resp.status_code == 200
        body = resp.json()
        assert body["AAPL"]["headline"] == "hi" and "MSFT" not in body
        # the same normalized batch is served from cache without a re-fetch
        client.get("/api/news/batch", params={"symbols": "AAPL,msft"})
        assert len(calls) == 1
        cache.cache_clear()

    def test_news_batch_provider_failure_is_500(self, raw_client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared import cache

        cache.cache_clear()

        def _boom(symbols: list[str]) -> dict[str, object]:
            raise RuntimeError("finviz down")

        monkeypatch.setattr("modules.analysis.routes.finviz.fetch_news_bulk", _boom)
        resp = raw_client.get("/api/news/batch", params={"symbols": "AAPL"})
        assert resp.status_code == 500
        cache.cache_clear()

    def test_discover_fallback_success_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            "modules.discover.routes._service.get_webull_fallback",
            lambda session, direction="gainers": [{"name": "AAPL", "close": 1.0, "volume": 10, "change": 2.0}],
        )
        resp = client.get("/api/discover/fallback", params={"session": "market"})
        assert resp.status_code == 200
        body = resp.json()
        assert body["status"] == "success" and body["source"] == "webull"
        assert body["total_count"] == 1 and body["results"][0]["name"] == "AAPL"

    def test_discover_fallback_provider_failure_is_500(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        def _boom(session: str, direction: str = "gainers") -> list[dict[str, object]]:
            raise RuntimeError("webull down")

        monkeypatch.setattr("modules.discover.routes._service.get_webull_fallback", _boom)
        resp = client.get("/api/discover/fallback", params={"session": "market"})
        assert resp.status_code == 500
        # The provider's own text must not reach the client (HTTP-9): the handler
        # logs it and answers with the generic detail.
        assert resp.json()["detail"] == "Internal server error"
        assert "webull down" not in resp.text

    def test_reverse_splits_provider_failure_is_500(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        def _boom(symbol: str, days: int) -> list[dict[str, object]]:
            raise RuntimeError("defeatbeta down")

        monkeypatch.setattr("modules.lists.service._get_reverse_splits", _boom)
        resp = client.get("/api/reverse-splits", params={"symbol": "AAPL"})
        assert resp.status_code == 500
        assert resp.json()["detail"] == "Internal server error"
        assert "defeatbeta down" not in resp.text

    def test_reverse_splits_batch_ignores_per_symbol_failures(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        def _splits(symbol: str, days: int) -> list[dict[str, object]]:
            if symbol == "BAD":
                raise RuntimeError("no data")
            return [{"symbol": symbol, "ex_date": "2026-09-01", "ratio": "1:10", "old_rate": 10, "new_rate": 1}]

        monkeypatch.setattr("modules.lists.service._get_reverse_splits", _splits)
        # Detail runs only for symbols the calendar discovers (SRC-2): discover GOOD and BAD,
        # with an isolated discovery cache so no other test's rows leak in.
        monkeypatch.setattr("modules.lists.service._discovery_cache", {})
        monkeypatch.setattr(
            "modules.lists.service._calendar_discover",
            lambda: [
                {"symbol": "GOOD", "split_date": date.today().isoformat(), "ratio": "1:10"},
                {"symbol": "BAD", "split_date": date.today().isoformat(), "ratio": "1:10"},
            ],
        )
        resp = client.get("/api/reverse-splits", params={"symbols": "GOOD,BAD"})
        assert resp.status_code == 200
        body = resp.json()
        assert body["count"] == 1 and body["reverse_splits"][0]["symbol"] == "GOOD"

    def test_reverse_splits_keeps_fractional_rates_and_skips_degenerate_ones(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # int() truncation turned 1:2.5 into 1:2 and 0.2:1 into 0:1; a zero
        # rate is not a split at all and must be dropped, not rendered.
        recent = pd.Timestamp(date.today() - timedelta(days=1)).date()
        frame = pd.DataFrame(
            [
                {"symbol": "AAPL", "ex_date": recent, "ratio": 1 / 2.5, "old_rate": 2.5, "new_rate": 1.0},
                {"symbol": "AAPL", "ex_date": recent, "ratio": 0.2, "old_rate": 1.0, "new_rate": 0.2},
                {"symbol": "AAPL", "ex_date": recent, "ratio": 0.0, "old_rate": 1.0, "new_rate": 0.0},
            ]
        )
        monkeypatch.setattr("modules.lists.service.splits_provider.get_splits", lambda symbol: frame)

        resp = client.get("/api/reverse-splits", params={"symbol": "AAPL"})

        assert resp.status_code == 200
        rows = resp.json()["reverse_splits"]
        assert [r["ratio"] for r in rows] == ["1:2.5", "0.2:1"]
        assert [r["new_rate"] for r in rows] == [1.0, 0.2]

    def test_screener_invalid_filter_is_400(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        class _FakeService:
            def run(self, **kwargs: object):
                raise ValueError("unknown column")

        monkeypatch.setattr("modules.screener.routes.ScreenerService", _FakeService)
        resp = client.post(
            "/api/screener",
            json={"columns": ["name"], "filters": [], "limit": 10},
        )
        assert resp.status_code == 400
        assert "unknown column" in resp.json()["detail"]

    def test_screener_provider_failure_is_500(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        class _FakeService:
            def run(self, **kwargs: object):
                raise RuntimeError("tradingview down")

        monkeypatch.setattr("modules.screener.routes.ScreenerService", _FakeService)
        resp = client.post("/api/screener", json={"columns": ["name"], "filters": [], "limit": 10})
        assert resp.status_code == 500
        assert resp.json()["detail"] == "Internal server error"
        assert "tradingview down" not in resp.text

    def test_dashboard_news_feed_limit_bounds(self, client: TestClient) -> None:
        assert client.get("/api/dashboard/news-feed", params={"limit": 0}).status_code == 422
        assert client.get("/api/dashboard/news-feed", params={"limit": 101}).status_code == 422

    def test_dashboard_news_feed_upstream_failure_serves_empty(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        import modules.dashboard.routes as dash

        dash._news_feed_cache = None
        monkeypatch.setattr("modules.dashboard.routes._NEWS_FEED_TTL", 0.0)

        class _BoomClient:
            def __init__(self, *args: object, **kwargs: object) -> None:
                pass

            async def __aenter__(self) -> "_BoomClient":
                return self

            async def __aexit__(self, *args: object) -> None:
                return None

            async def get(self, url: str) -> object:
                raise RuntimeError("rss down")

            def raise_for_status(self) -> None:
                return None

        monkeypatch.setattr(dash.httpx, "AsyncClient", _BoomClient)
        resp = client.get("/api/dashboard/news-feed")
        assert resp.status_code == 200
        assert resp.json() == {"items": []}

    def test_dashboard_filings_provider_failure_is_500(
        self, raw_client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        def _boom(symbol: str) -> None:
            raise RuntimeError("edgar down")

        monkeypatch.setattr("modules.dashboard.routes.fetch_sec_submissions", _boom)
        resp = raw_client.get("/api/dashboard/filings/AAPL")
        assert resp.status_code == 500  # unexpected exception propagates as 500

    def test_dashboard_filings_no_submissions_is_empty(
        self, client: TestClient, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr("modules.dashboard.routes.fetch_sec_submissions", lambda symbol: None)
        resp = client.get("/api/dashboard/filings/AAPL")
        assert resp.status_code == 200
        assert resp.json() == {"filings": []}

    def test_scan_calendar_export_no_data_404(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.get_scan_calendar_data",
            lambda *args, **kwargs: {},
        )
        resp = client.get("/api/scan/calendar/export")
        assert resp.status_code == 404
        cache_clear()

    def test_scan_calendar_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.get_scan_calendar_data",
            lambda *args, **kwargs: {"2026-09-25": []},
        )
        resp = client.get("/api/scan/calendar", params={"year": 2026, "month": 9})
        assert resp.status_code == 200
        body = resp.json()
        assert body["year"] == 2026 and body["month"] == 9
        assert body["data"] == {"2026-09-25": []}
        cache_clear()

    def test_scan_etag_round_trip(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()
        row = {
            "symbol": "AAPL",
            "date": "2026-09-25",
            "daily_bars": [{"time": "2026-09-25", "open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1}],
        }
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: ([row], False),
        )
        first = client.get("/api/scan", params={"symbols": "AAPL", "timeframe": "1D"})
        assert first.status_code == 200
        etag = first.headers.get("ETag")
        assert etag
        assert first.json()["count"] == 1
        second = client.get("/api/scan", params={"symbols": "AAPL", "timeframe": "1D"}, headers={"if-none-match": etag})
        assert second.status_code == 304
        cache_clear()

    def test_scan_symbol_list_with_filter_warns(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        from core.shared.cache import cache_clear

        cache_clear()
        monkeypatch.setattr(
            "modules.scan.routes.scan_service.scan",
            lambda *args, **kwargs: ([], False),
        )
        resp = client.get("/api/scan", params={"symbols": "AAPL", "filter": "price > vwap", "timeframe": "1D"})
        assert resp.status_code == 200
        assert any("not applied" in w for w in resp.json()["warnings"])
        cache_clear()

    def test_chat_rejects_missing_body(self, client: TestClient) -> None:
        assert client.post("/api/chat").status_code == 422


class TestProviderTimeoutFallback(_ContractBase):
    """Provider-timeout fallback: transient upstream failures must never be
    served as cached empty results (plan TEST-T4 crosses here for routes)."""

    def test_ohlc_upstream_failure_is_not_cached(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
        """A 502 from /ohlc must not poison the cache: the next call with a
        working provider succeeds."""
        from core.shared.cache import cache_clear

        cache_clear()
        fail = True

        async def _flaky(symbol: str, timeframe: str):
            if fail:
                return None, None
            return [{"time": 1, "open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1}], "yahoo"

        monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _flaky)
        monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {})
        assert client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"}).status_code == 502
        fail = False
        resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"})
        assert resp.status_code == 200
        assert resp.json()["bars"]
        cache_clear()