File size: 87,463 Bytes
c806799
d34819d
c806799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d34819d
c806799
 
adb953c
c806799
8f4e048
dc1ae51
adb953c
dc1ae51
adb953c
d34819d
 
 
8f4e048
 
 
 
 
 
d34819d
c806799
 
 
 
 
 
 
 
 
d34819d
c806799
 
 
d34819d
c806799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb953c
 
 
c806799
 
adb953c
 
 
 
 
 
 
 
 
 
 
 
 
c806799
adb953c
 
c806799
adb953c
 
 
 
c806799
 
 
 
 
 
 
 
 
 
 
d34819d
c806799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb953c
 
 
 
 
c806799
 
 
 
 
 
c4d016d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c806799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4e048
 
 
 
 
 
 
5282e4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4e048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb953c
 
5282e4c
 
68ee8ac
 
 
 
 
 
 
 
5282e4c
 
 
68ee8ac
5282e4c
68ee8ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5282e4c
 
 
 
68ee8ac
 
 
 
 
 
 
5282e4c
 
 
68ee8ac
5282e4c
68ee8ac
 
5282e4c
68ee8ac
 
 
 
 
 
 
5282e4c
68ee8ac
 
5282e4c
 
 
 
68ee8ac
5282e4c
 
 
68ee8ac
 
 
 
 
5282e4c
68ee8ac
5282e4c
 
68ee8ac
5282e4c
 
 
68ee8ac
 
5282e4c
68ee8ac
 
5282e4c
 
68ee8ac
5282e4c
 
adb953c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f4e048
 
c806799
adb953c
 
 
 
 
 
 
c806799
adb953c
 
 
 
 
 
c806799
 
 
adb953c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c806799
adb953c
 
 
c806799
 
 
 
 
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
"""
AxonIQ β€” FastAPI Backend + Agentic AI
MS Symptom Classifier Β· spaCy NegEx Β· LangGraph Agent Β· RAG Knowledge Base

Tier 1/2 (SYMPTOM_PATTERNS)   β†’ 3.0 pts Γ— severity multiplier
Tier 3  (LOW_PRIORITY_PATTERNS)β†’ 1.0 pt  fixed

Tiers: CRITICAL_EMERGENCY β†’ HIGH β†’ MODERATE β†’ WATCH β†’ LOW

Validated: 150 cases Β· 15 internet sources Β· PMC 2024 Β· NINDS Β· MSAA
           NHS Β· Mayo Β· StatPearls Β· Cureus Β· Frontiers Β· Merck Manual 2024

Domain Expert: Dr. Avasarala, MD PhD, UKY, Lexington KY USA
Lead AI Architect : Raghu Gangolu, NITW, Telangana India
Principal investigator : Dr. Kadambari, PhD, NITW, Telangana India

Clinical Decision Support Only β€” Not a diagnosis.
"""
from __future__ import annotations
import re, os
from typing import List, Dict, Optional
from contextlib import asynccontextmanager

import spacy
from negspacy.termsets import termset
from negspacy.negation import Negex  # noqa: F401 β€” registers 'negex' factory
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from loguru import logger
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

# ── Rate limiter ──────────────────────────────────────────────────────────────
limiter = Limiter(key_func=get_remote_address)

# ── Global NLP pipeline (stored on app.state) ─────────────────────────────────
nlp = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global nlp
    model_path = os.environ.get("SPACY_MODEL", "en_model")
    nlp = spacy.load(model_path)
    ts = termset("en_clinical")
    ts.add_patterns({
        "preceding_negations": [
            "negative for", "cleared of", "denies any", "no history of",
            "do not have", "does not have", "no evidence of", "without",
            "denies", "rules out", "not had", "not having", "never had",
            "excluded", "has been excluded", "has not had",
        ],
        "following_negations": [
            "ruled out by", "ruled out", "is absent",
            "is negative", "has been excluded",
        ],
        "pseudo_negations": ["might not be", "not entirely sure", "not certain"],
    })
    nlp.add_pipe("negex", config={"ent_types": ["SYMPTOM"], "neg_termset": ts.get_patterns()})
    app.state.nlp = nlp
    logger.info("[AxonIQ] spaCy model loaded: {}", model_path)

    # Init persistent database
    from api.database import init_db, migrate_add_admin_column, set_admin, get_user_by_username, DB_PATH
    init_db()
    migrate_add_admin_column()
    from api.database import migrate_add_logs_table, migrate_add_otp_table
    migrate_add_logs_table()
    migrate_add_otp_table()
    # Log exact DB path so we can verify persistent storage is mounted
    logger.info("[AxonIQ] SQLite database initialized at: {}", str(DB_PATH))
    logger.info("[AxonIQ] DB exists on disk: {}", DB_PATH.exists())
    logger.info("[AxonIQ] /data mounted: {}", __import__("pathlib").Path("/data").exists())
    # Auto-grant admin to ADMIN_USERNAME env var if set
    admin_user = os.environ.get("ADMIN_USERNAME", "")
    if admin_user:
        u = get_user_by_username(admin_user)
        if u and not u.get("is_admin"):
            set_admin(admin_user, True)
            logger.info("[AxonIQ] Admin access granted to '{}'", admin_user)

    # Build RAG knowledge base (runs once, persists to disk)
    try:
        from api.rag import build_knowledge_base
        build_knowledge_base()
    except Exception as e:
        logger.warning("[RAG] Could not build knowledge base: {}", e)

    yield
    logger.info("[AxonIQ] Shutting down.")


app = FastAPI(
    title="AxonIQ MS Classifier + Agentic AI",
    version="9.0.0",
    description=(
        "MS Symptom Classifier + Agentic AI β€” 150-case validated. "
        "Clinical decision support only. Not a diagnosis."
    ),
    lifespan=lifespan,
)

app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["POST", "GET", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# ── Auth router ──────────────────────────────────────────────────────────────
from api.auth import router as auth_router
app.include_router(auth_router)


# ── Pydantic schemas ──────────────────────────────────────────────────────────
class SymptomRequest(BaseModel):
    text: str = Field(..., min_length=5, max_length=3000)


class ChatRequest(BaseModel):
    message: str = Field(..., min_length=1, max_length=3000)
    session_id: Optional[str] = None
    user_id: Optional[int] = None  # set server-side from JWT


class ChatResponse(BaseModel):
    session_id: str
    response: str
    turn: int


class FeatureFound(BaseModel):
    key: str
    label: str
    priority: str  # "standard" | "low"


class ClassifyResponse(BaseModel):
    tier: str
    tier_label: str
    tier_subtitle: str
    action: str
    workup: List[str]
    features: List[FeatureFound]
    temporal_notes: List[str]
    disclaimer: str = (
        "Clinical Decision Support Only β€” Not a diagnosis. "
        "All outputs must be reviewed by a qualified clinician."
    )


# ═══════════════════════════════════════════════════════════════════════════════
# EMERGENCY FLAGS  (bypass scoring β€” fire immediately)
# ═══════════════════════════════════════════════════════════════════════════════
EMERGENCY_FLAGS: Dict[str, dict] = {
    "stroke_suspected": {
        "patterns": [r"(sudden|woke up).{0,20}(face droop|arm weak|slurred speech)"],
        "label": "Possible Acute Stroke",
        "action": "Call emergency services immediately (999 / 911). Do not wait β€” time is critical.",
    },
    "meningitis_suspected": {
        "patterns": [
            r"(fever|high temp).{0,30}(neck).{0,20}(stiff|rigid|pain)",
            r"photophobia.{0,20}fever",
        ],
        "label": "Possible Meningitis / Encephalitis",
        "action": "Seek emergency care immediately. Meningitis is life-threatening.",
    },
    "hemorrhage_suspected": {
        "patterns": [r"(sudden|worst).{0,20}(headache).{0,20}(life|ever|thunderclap)"],
        "label": "Possible Subarachnoid Haemorrhage",
        "action": "Call emergency services immediately. Thunderclap headache requires emergency evaluation.",
    },
    "gbs_suspected": {
        "patterns": [
            r"(both legs|feet).{0,30}(weak|paralyzed).{0,30}(moving up|spreading up|hands)",
            r"ascending paralysis",
            r"weakness.{0,30}(spreading|moving up).{0,20}(arm|hand)",
        ],
        "label": "Possible Guillain-BarrΓ© Syndrome",
        "action": "Seek emergency care immediately. Ascending weakness requires urgent neurological assessment.",
    },
}


# ═══════════════════════════════════════════════════════════════════════════════
# ANCHOR FEATURES
# Any anchor hit β‰₯ 3 pts β†’ HIGH regardless of total score
# Updated v8.1: added paroxysmal_ms, tonic_spasms_ms, tumefactive_ms,
#               lhermittes_variant, sensory_idioms, limb_numbness
# ═══════════════════════════════════════════════════════════════════════════════
ANCHOR_FEATURES = {
    # ── Visual / optic ────────────────────────────────────────────────────────
    "lhermittes_sign",
    "lhermittes_variant",
    "uhthoff_phenomenon",
    "pain_on_eye_movement",
    "monocular_vision_loss",
    "ino_features",
    "ms_hug",
    "oscillopsia",
    "bilateral_vision_loss",
    "diplopia",
    # ── Brainstem / TN ────────────────────────────────────────────────────────
    "paroxysmal_tn_young",
    "area_postrema",
    # ── Spinal / sensory ──────────────────────────────────────────────────────
    "sensory_idioms",
    "limb_numbness",
    # ── Ocular / IIH overlap ──────────────────────────────────────────────────
    "optic_neuritis_idioms",
    "obesity_disc_flag",
    # ── History / DIT ─────────────────────────────────────────────────────────
    "prior_cis_episode",
    # ── Vestibular ────────────────────────────────────────────────────────────
    "vertigo_ms",
    # ── Paroxysmal / rare (v8.1) ──────────────────────────────────────────────
    "paroxysmal_ms",
    "tonic_spasms_ms",
    "tumefactive_ms",
}


# ═══════════════════════════════════════════════════════════════════════════════
# TIER 1 + 2: SYMPTOM PATTERNS  (3.0 pts each Γ— severity multiplier)
# v8.1: 17 new categories added from 150-case internet testing
# ═══════════════════════════════════════════════════════════════════════════════
SYMPTOM_PATTERNS: Dict[str, List[tuple]] = {

    # ── ANCHOR: Lhermitte's sign ──────────────────────────────────────────────
    "lhermittes_sign": [
        (r"electric.{0,20}(shock|jolt|current|zap).{0,30}spine", "Lhermitte's sign β€” electric shock down spine"),
        (r"(shock|jolt|current|zap).{0,30}(when|if|on).{0,20}(bend|bow|look|flex|tilt).{0,20}(neck|head|chin|down)", "Shock on neck bending"),
        (r"(sharp|sudden).{0,20}(electric|zap|jolt|current).{0,20}(run|shoot|travel).{0,30}(spine|leg|back)", "Lhermitte-type electric sensation"),
        (r"\blhermitte.{0,20}(sign|phenomenon|symptom)\b", "Lhermitte's sign (clinical)"),
    ],

    # ── ANCHOR: Lhermitte variant (cough/sneeze trigger) β€” v8.1 ─────────────
    "lhermittes_variant": [
        (r"(shock|jolt|electric).{0,20}(cough|coughing|sneeze|sneezing|limb movement)", "Lhermitte variant β€” cough/sneeze trigger"),
        (r"\blhermitte.{0,20}(cough|movement|limb|trigger|variant)\b", "Lhermitte variant trigger"),
    ],

    # ── ANCHOR: Uhthoff's phenomenon ─────────────────────────────────────────
    # v8.1: must have visual OR gait/balance component to distinguish from
    #       generic heat sensitivity (LP category)
    "uhthoff_phenomenon": [
        (r"(vision|sight|see|eyesight).{0,30}(blur|worse|bad|dim|grey|gray|dark).{0,30}(hot|heat|shower|bath|exercise|warm|fever)", "Uhthoff's β€” vision worse in heat"),
        (r"(hot|heat|shower|bath|exercise|warm|fever).{0,30}(vision|sight|see|eyesight).{0,30}(blur|worse|bad|dim)", "Uhthoff's β€” heat worsens vision"),
        (r"(shimmer|shimmers|obscur).{0,40}(hot shower|warm shower|shower|bath|exercise|heat|fever)", "Uhthoff's β€” shimmer in heat"),
        (r"worsening.{0,20}(vision|balance|weakness|gait).{0,30}(exercise|warm|heat|hot|fever)", "Uhthoff's β€” visual/gait worsening in heat"),
        (r"\buhthoff.{0,20}(phenomenon|sign|syndrome)\b", "Uhthoff's phenomenon (clinical)"),
        (r"heat intolerance.{0,40}(gait|walk|stumbl|fall|vision)", "Uhthoff's β€” heat intolerance with visual/gait"),
    ],

    # ── ANCHOR: Pain on eye movement ─────────────────────────────────────────
    "pain_on_eye_movement": [
        (r"pain.{0,30}(mov|look).{0,15}eye", "Pain on eye movement"),
        (r"(move|moving|turning|side.to.side).{0,20}(eye|eyes).{0,30}(pain|hurt|ache|sore|throb)", "Moving eyes causes pain"),
        (r"(exacerbated|worse|painful).{0,30}(looking up|side.to.side|look.{0,5}side)", "Pain exacerbated by eye movement"),
        (r"pain.{0,20}(eye.{0,10}movement|moving the eye)", "Pain on eye movement"),
        (r"retrobulbar.{0,15}pain", "Retrobulbar pain (ON)"),
        (r"(discomfort|pain).{0,20}(left eye|right eye|eye).{0,20}(worse|made worse|exacerbated)", "Discomfort worse with eye movements"),
    ],

    # ── ANCHOR: Monocular vision loss ─────────────────────────────────────────
    "monocular_vision_loss": [
        (r"(one|left|right|l-eye|r-eye) eye.{0,30}(blur|vision|dim|loss|blind)", "Monocular vision loss"),
        (r"blurring in one eye", "Blurring in one eye"),
        (r"(left|right).{0,5}eye.{0,20}(dimm|blur|dull|fad|fog|dim|vision|loss)", "One eye dimming / blurring"),
        (r"vision.{0,20}(painful|pain).{0,20}(monocular|one eye)", "Painful monocular vision loss"),
        (r"(monocular).{0,20}(vision loss|blind|dim|blur|visual|impairment)", "Monocular vision loss (clinical)"),
        (r"unilateral.{0,20}(visual|vision).{0,20}(impairment|loss|deficit|blurr|acuity)", "Unilateral visual impairment"),
        (r"(optic neuritis|optic nerve).{0,30}(vision|visual|acuity|pain)", "Optic neuritis (clinical)"),
    ],

    # ── Dyschromatopsia ───────────────────────────────────────────────────────
    "dyschromatopsia": [
        (r"(red|colour|color).{0,20}(fad|wash|dim|dull|less|pale|grey|gray|wrong|off|not bright|desatur|less vivid)", "Dyschromatopsia β€” colour fading"),
        (r"(grey|gray|greyed|greyed out|less vibrant).{0,20}(eye|vision|right|left)", "Vision greyed out / less vibrant"),
        (r"red.green color loss", "Red-green colour loss"),
        (r"(fading|faded).{0,15}(color|colour)", "Faded colours"),
        (r"colors (look|appear|seem).{0,20}(dull|washed|faded|wrong|off|different)", "Colours appear wrong"),
    ],

    # ── ANCHOR: INO / eye movement disorder ──────────────────────────────────
    # v8.1: word-boundary fix prevents 'ino' matching in 'coordination'
    # v8.1: added lateral gaze palsy / sixth nerve palsy patterns
    "ino_features": [
        (r"(eye|eyes).{0,20}(jiggle|wobble|bounce|shake|jump).{0,20}(look|gaze|side)", "INO β€” eyes jiggle on gaze"),
        (r"\b(adduction lag|internuclear ophthalmoplegia|ophthalmoplegia)\b", "Internuclear ophthalmoplegia"),
        (r"cannot.{0,20}move.{0,20}(eye|eyes).{0,20}(nose|toward|nasal)", "INO β€” eye cannot adduct"),
        (r"(eye|eyes).{0,10}(crooked|jiggly|nystagmus|wiggling|oscillating)", "Jiggly / crooked eyes (INO/nystagmus)"),
        (r"(lateral gaze palsy|sixth nerve palsy|6th nerve palsy)", "Sixth nerve / lateral gaze palsy"),
        (r"(eye|eyes).{0,20}(cannot|can.{0,5}not).{0,20}(move outward|abduct|lateral)", "Eye cannot abduct"),
        (r"abduction (deficit|palsy|weakness)", "Abduction deficit (6th nerve)"),
    ],

    # ── ANCHOR: Oscillopsia ───────────────────────────────────────────────────
    "oscillopsia": [
        (r"(room|world|everything|objects|things).{0,30}(wiggl|wobbl|bounc|shak|oscillat|vibrat|jump)", "Oscillopsia β€” room appears to wiggle"),
        (r"world.{0,20}(split|splits)", "World splits on gaze"),
        (r"object.{0,15}jump.{0,15}(focus|see|gaze)", "Objects jump when focusing"),
        (r"vision.{0,20}(jump|jumpy|jiggly|shimmer)", "Jumpy / shimmery vision"),
        (r"\b(opsoclonus|oscillopsia)\b", "Oscillopsia / opsoclonus (clinical)"),
    ],

    # ── ANCHOR: MS Hug ────────────────────────────────────────────────────────
    "ms_hug": [
        (r"(tight|squeezing|pressure|band|belt|corset|grip).{0,30}(chest|torso|stomach|abdomen|waist|rib|midsection|trunk|middle)", "MS hug β€” tight band around trunk"),
        (r"(banding|girdle).{0,20}(sensation|feeling|pain).{0,20}(chest|abdomen|trunk|waist)", "Girdle / banding sensation"),
    ],

    # ── ANCHOR: Bilateral vision loss (NMOSD) ────────────────────────────────
    "bilateral_vision_loss": [
        (r"(bilateral|both eyes).{0,30}(vision loss|blind|blur|dim|black|loss of sight)", "Bilateral vision loss"),
        (r"(vision loss|blind|blur|dim|black|loss of sight).{0,30}(bilateral|both eyes)", "Bilateral vision loss"),
        (r"(nlp|no light perception)", "No light perception (NLP)"),
        (r"(bottom half|top half|altitudinal).{0,20}(gone|lost|blind|vision)", "Altitudinal vision loss"),
        (r"both eyes.{0,20}(painful|pain)", "Both eyes painful (ADEM / NMO flag)"),
        (r"(simultaneous).{0,30}vision loss", "Simultaneous bilateral vision loss"),
    ],

    # Post-viral vision (ADEM flag)
    "post_viral_vision": [
        (r"(flu|illness|viral|flu-like).{0,30}(both eyes|bilateral|eye|vision)", "Post-viral vision loss (ADEM flag)"),
        (r"(flu.like illness|viral illness).{0,40}(eye|vision|painful)", "Post-viral eye involvement"),
    ],

    # ── ANCHOR: Diplopia ──────────────────────────────────────────────────────
    "diplopia": [
        (r"double vision", "Double vision (diplopia)"),
        (r"seeing double", "Seeing double"),
        (r"diplopia", "Diplopia (clinical)"),
        (r"(seeing|see).{0,10}two", "Seeing two images"),
        (r"world.{0,20}split.{0,20}(left|right|look)", "World splits on gaze"),
        (r"(eyes.{0,20}crooked|jiggly eyes)", "Crooked / jiggly eyes"),
        (r"(eyes? pointing|eye pointing).{0,20}(wrong direction|wrong way|deviation)", "Eye pointing wrong direction"),
        (r"binocular.{0,15}(diplopia|vision)", "Binocular diplopia"),
    ],

    # ── ANCHOR: Paroxysmal TN / facial pain ──────────────────────────────────
    "paroxysmal_tn_young": [
        (r"electric shocks? in (jaw|face)", "Electric shock in jaw / face (TN)"),
        (r"severe face pain", "Severe face pain (TN)"),
        (r"trigeminal neuralgia", "Trigeminal neuralgia"),
        (r"facial shock", "Facial shock"),
        (r"(facial|face).{0,20}(numb|numbness|pain.{0,15}young|electric|stab|shock)", "Facial numbness / pain"),
        (r"(face|jaw).{0,15}pain.{0,20}(cold wind|trigger|touch|brush)", "Trigger-evoked face pain (TN)"),
        (r"(sharp facial|facial).{0,10}(pain|shock)", "Sharp facial pain"),
        (r"(v1|v2|trigeminal).{0,20}(pain|numb|symptom)", "V1/V2 trigeminal pain"),
        (r"on and off.{0,20}facial pain", "Paroxysmal facial pain"),
        (r"(severe facial|severe face).{0,10}(pain|ache)", "Severe facial pain"),
        (r"(face|facial).{0,15}(weakness|numb|numbness)", "Facial weakness / numbness"),
        (r"(face|jaw|cheek).{0,20}pain.{0,30}(light touch|touch|trigger|cold|wind|brush)", "Light-touch triggered facial pain (TN)"),
        (r"stabbing.{0,20}(face|jaw|cheek|facial|character)", "Stabbing facial pain"),
    ],

    # ── ANCHOR: Area postrema (NMO) ───────────────────────────────────────────
    "area_postrema": [
        (r"intractable hiccups", "Intractable hiccups (area postrema)"),
        (r"uncontrollable vomiting", "Uncontrollable vomiting"),
        (r"hiccups and vomiting", "Hiccups and vomiting (NMO sign)"),
        (r"nausea and vomiting", "Nausea and vomiting"),
        (r"\barea postrema\b", "Area postrema syndrome (NMO)"),
    ],

    # ── ANCHOR: Vertigo / vestibular MS ──────────────────────────────────────
    "vertigo_ms": [
        (r"(vertigo|dizziness|dizzy).{0,30}(fall|balance|walk|gait)", "Vertigo with falls / gait problems"),
        (r"(constant|persistent|abrupt|sudden).{0,15}(vertigo|dizziness)", "Constant or sudden-onset vertigo"),
        (r"(increasingly frequent falls|progressively.{0,15}fall|frequent falls)", "Increasingly frequent falls"),
        (r"(lost all equilibrium|loss of equilibrium|lost equilibrium)", "Loss of equilibrium"),
        (r"(lightheadedness|lightheaded|light.headed).{0,30}(dizziness|balance|standing)", "Lightheadedness with balance difficulty"),
    ],

    # ── ANCHOR: Optic neuritis idioms ─────────────────────────────────────────
    "optic_neuritis_idioms": [
        (r"(dirty water|smudge|foggy|foggy vision|fog).{0,20}(eye|vision|see)", "ON β€” foggy / smudged vision"),
        (r"(looking through|vision like).{0,20}(dirty|foggy|cloudy|smeared|smudge|mist|haze)", "ON β€” dirty / foggy vision"),
        (r"(scotoma|central blur|central blurr|central loss|central vision)", "Scotoma / central vision loss"),
        (r"(eye soreness|eye sore|sore eye|soreness behind the eye|eye ache|ache behind the eye)", "Eye soreness (ON)"),
        (r"pulling sensation.{0,20}(behind|eye)", "Pulling sensation behind the eye"),
        (r"(vision|visual).{0,20}(deficit|dimming)", "Visual deficit / dimming"),
        (r"(blurring|blur).{0,20}one eye", "Blurring in one eye (ON)"),
        (r"transient obscur", "Transient obscurations"),
        (r"(washed out|less vibrant|world.{0,10}dim)", "Washed-out / dim vision"),
        (r"(optic neuritis|optic nerve)", "Optic neuritis (clinical)"),
        (r"(visual acuity|visual impairment|visual field).{0,30}(decreas|loss|reduced|impair|defect)", "Visual acuity / field loss"),
        (r"(blurry vision|blurred vision|blurring of vision)", "Blurred vision"),
        (r"\b(afferent pupillary defect|relative afferent)\b", "Afferent pupillary defect (RAPD)"),
    ],

    # ── ANCHOR: IIH / obesity / disc swelling ────────────────────────────────
    "obesity_disc_flag": [
        (r"(disc swelling|papilledema|disc edema|swelling.{0,20}eye|swelling.{0,20}optic)", "Disc swelling (papilledema)"),
        (r"(bilateral disc|disc.{0,10}swelling)", "Bilateral disc swelling"),
        (r"(eyes.{0,20}abnormal|abnormal.{0,20}eye)", "Abnormal eye exam finding"),
        (r"(heavy legs|heavy leg|legs feel heavy|leg heaviness).{0,30}(walk|walking|clinic|stand)", "Heavy legs (spinal cord flag)"),
        (r"(\d{3}\s*kg|obese|high bmi|overweight|obesity)", "Obesity marker (IIH / MS overlap)"),
    ],

    # ── ANCHOR: Prior CIS / DIT ───────────────────────────────────────────────
    "prior_cis_episode": [
        (r"(years?|months?) ago.{0,40}(numb|weak|vision|tingling|balance).{0,60}(better|resolved|went away|recovered)", "Prior resolved neurological episode"),
        (r"(episode|attack|event).{0,20}(numb|weakness|vision|tingling).{0,20}(resolved|recovered|cleared)", "Prior episode resolved"),
        (r"(transient|tingling|numbness|numb).{0,40}(lasted|for one week|for a week|weeks?).{0,30}(ago|years? ago|last)", "Transient episode β€” DIT marker"),
        (r"history of optic neuritis", "History of optic neuritis (DIT)"),
        (r"(previous|prior|history of).{0,30}(episode|attack|relapse|event|numbness|tingling|weakness|vision)", "Prior neurological episode"),
        (r"(spontaneously resolved|resolved spontaneously|went away on its own|resolved on its own)", "Spontaneous resolution (CIS pattern)"),
        (r"clinically isolated syndrome|first (episode|attack|event|relapse)", "Clinically isolated syndrome"),
        (r"(tingling|numbness|numb).{0,40}(last monsoon|last year|years? ago|months? ago)", "Prior monsoon / seasonal episode (DIT)"),
        (r"monsoon.{0,40}(resolved|better|went away|numb|tingle)", "Monsoon-triggered episode resolved"),
        (r"(episode|attack).{0,50}(numb|weak|tingling|vision).{0,50}(resolved|went away|got better|cleared)", "Prior episode resolved (flexible)"),
    ],

    # ── Standard: Cerebellar ataxia ───────────────────────────────────────────
    "cerebellar_ataxia": [
        (r"(clumsiness|clumsy|dropping keys|drops things|cerebellar)", "Cerebellar clumsiness"),
        (r"(steady|steady myself|off balance|balance problems|poor balance)", "Balance problems (cerebellar)"),
        (r"(seasick|feels seasick|nausea.{0,20}walk|dizzy.{0,20}walk)", "Seasick feeling (cerebellar)"),
        (r"swallowing difficulty", "Swallowing difficulty (brainstem)"),
        (r"\b(dysdiadochokinesia|ataxia|coordination deficit)\b", "Ataxia / coordination deficit"),
        (r"(impaired balance|loss of balance|balance impair|vestibular)", "Impaired balance"),
        (r"(equilibrium|lost.{0,10}equilibrium|lost.{0,10}balance)", "Loss of equilibrium"),
        (r"(heel.to.shin|finger.to.nose|tandem gait)", "Cerebellar examination findings"),
    ],

    # ── Standard: Motor weakness / grip ──────────────────────────────────────
    "motor_weakness_grip": [
        (r"(weak|lose|loss of|give out|clumsy).{0,20}(grip|grasp|hand|power|oomph|button|zip)", "Weak grip / clumsy hands"),
        (r"(drop|dropping).{0,20}(cup|keys|things|mug|bottle)", "Dropping objects"),
        (r"(typing errors|typos|handwriting|script)|(buttoning trouble|loss of oomph)", "Fine motor deficit"),
        (r"(hand|arm|upper extremity|upper limb).{0,20}(weakness|weak|paresis|paresthesia)", "Upper extremity weakness"),
        (r"(decreased|reduced).{0,20}(dexterity|grip|coordination|finger)", "Decreased dexterity"),
        (r"\b(tremor|tremors|intention tremor|action tremor)\b", "Tremor"),
        (r"\b(hemiparesis|paraparesis|monoparesis|quadriparesis)\b", "Paresis / paralysis"),
        (r"(hyperreflexia|babinski.{0,10}(sign|positive)|extensor plantar)", "Upper motor neuron signs"),
        (r"left lower limb weakness|right lower limb weakness|lower limb weakness", "Lower limb weakness"),
    ],

    # ── Standard: Gait ataxia ─────────────────────────────────────────────────
    "gait_ataxia": [
        (r"(drunk|drunken|boat|seasick|stagger|lurch|veer|unsteady|balance|fall|leaner).{0,30}(walk|walking|gait|stand|pivot|staircase|hallway)", "Gait ataxia / unsteady walk"),
        (r"(occasional falls|fall|tripping|trips).{0,20}(walk|balance|gait)", "Falls (gait / balance)"),
        (r"(stumbling gait|stumbl.{0,10}gait|stumbl.{0,10}walk)", "Stumbling gait"),
        (r"(gait disturbance|gait disorder|gait impairment|difficulty.{0,10}walk|difficulty.{0,10}ambul)", "Gait disturbance (clinical)"),
        (r"(tendency to fall|multiple falls|several falls|bad falls|frequent falls)", "Tendency to fall"),
        (r"(ambulation|ambulating|ambulatory).{0,20}(difficult|impaired|problem)", "Ambulation difficulty"),
        (r"(increasingly frequent falls|progressively.{0,15}fall)", "Increasingly frequent falls"),
        (r"(ataxic gait|ataxic walking)", "Ataxic gait"),
    ],

    # ── Standard: Spasticity ─────────────────────────────────────────────────
    "spasticity": [
        (r"(spring.loaded|springy|twitch|jump|stiff|rigid|locked|cramp|spasm|board|glued).{0,20}(leg|feet|foot|muscle|calf|knee|finger|hand)", "Spasticity / stiffness"),
        (r"(locked muscles|stiff fingers|stiff knee)", "Locked / stiff muscles"),
        (r"\b(spasticity|hyperreflexia|hyperreflexic|extensor plantar|babinski|clonus)\b", "Spasticity (clinical)"),
        (r"(increased tone|increased reflexes|brisk reflexes)", "Increased tone / reflexes"),
        (r"spastic (quadriparesis|paraparesis|hemiparesis)", "Spastic paresis"),
        (r"(muscle spasm|muscle cramp).{0,20}(ms|neurological|multiple sclerosis)", "MS-related muscle spasm"),
    ],

    # ── Standard: Tremor (v8.1 β€” separated from motor_weakness_grip) ────────
    "tremor_standard": [
        (r"(uncontrollable shaking|uncontrollable trembling|tremor).{0,20}(arm|leg|head|hand|body)", "Uncontrollable tremor"),
        (r"\b(intention tremor|action tremor|cerebellar tremor)\b", "Intention / cerebellar tremor"),
    ],

    # ── Standard: Foot drop ───────────────────────────────────────────────────
    "foot_drop": [
        (r"(foot|toe|toes|feet).{0,20}(drag|dragging|drop|dropping|scuff|scrape)", "Foot drop"),
        (r"toe dragging", "Toe dragging"),
        (r"(lift|lifting).{0,15}(knee|foot).{0,20}(clear|foot|toe|floor|step)", "Lifting knee to clear foot (foot drop)"),
        (r"foot drop|drop foot", "Foot drop (clinical)"),
    ],

    # ── ANCHOR: Limb numbness / paresthesia ───────────────────────────────────
    "limb_numbness": [
        (r"(arm|leg|hand|foot|feet|finger|fingertip|thigh|shin|back|scalp|neck|cheek|face|ankle).{0,30}(numb|numbness|tingling|pins and needles)", "Limb / body numbness or tingling"),
        (r"(numbness|numb|tingling).{0,30}(fingertip|finger|hand|arm|leg|ankle)", "Fingertip / limb numbness"),
        (r"(tingling in|numbness in|numb in).{0,20}(extremities|arm|leg|hand|foot|body|side|face|ankle)", "Tingling / numbness in extremities"),
        (r"\b(hemibody|hemi.body|hemisensory)\b.{0,30}(paresthesia|numb|weak|sensory)", "Hemibody paresthesia (MS relapse)"),
        (r"\b(paresthesia|paresthesias|dysesthesia)\b.{0,20}(sensory|numb|tingle|sensation|deficit)", "Clinical paresthesia"),
        (r"(altered sensation|sensory deficit|sensory loss|hemisensory)", "Sensory deficit (clinical)"),
        (r"(paresthesia|tingling|numbness).{0,30}(ascend|ascending|spread|spreading).{0,30}(leg|limb|trunk|umbilicus|body)", "Ascending paresthesia (myelitis)"),
        (r"(right.sided|left.sided).{0,20}(weakness|numbness|numb|paresthesia)", "Hemisensory / hemibody symptoms"),
        (r"glove.{0,10}stocking.{0,10}(pattern|numbness|paresthesia)", "Glove-and-stocking pattern"),
        (r"(radiation|radiating).{0,20}(numb|numbness|tingling|pain).{0,20}(ankle|leg|arm|foot|thigh|shin)", "Radiating numbness / tingling"),
    ],

    # ── ANCHOR: Sensory idioms / dysesthesia ─────────────────────────────────
    "sensory_idioms": [
        (r"(cold|water|ice|frozen).{0,20}(trickle|trickling|running|poured|pack)", "Cold water / ice sensation"),
        (r"(twice its size|swollen|puffy).{0,30}(looks normal|looks fine|perfectly normal)", "Phantom swelling (dysesthesia)"),
        (r"(hand|arm|leg|foot).{0,20}feels.{0,20}(twice|swollen|puffy|bigger).{0,30}(normal|fine)", "Phantom swelling"),
        (r"(dead|wooden|block|dead feeling|completely dead).{0,20}(arm|leg|patch|skin|left arm|right arm)", "Dead / wooden sensation"),
        (r"(completely dead|dead feeling|deadness).{0,20}(arm|leg|hand|foot)", "Dead limb sensation"),
        (r"(left arm|right arm|arm|leg).{0,30}(completely dead|dead|wooden|numb)", "Arm / leg feels dead"),
        (r"(arm|leg).{0,20}(feels|feel|is|are).{0,10}(completely dead|dead|wooden)", "Limb feels dead"),
        (r"(hot coals|stinging needles|bee sting|stinging).{0,20}(feet|foot|sole|face|skin|soles)", "Hot coals / stinging sensation"),
        (r"(walking on hot coals|feel like hot coals|feels like hot coals)", "Walking on hot coals"),
        (r"soles.{0,30}(hot coals|needles|stinging|burning|fire)", "Burning soles"),
        (r"(sandpaper).{0,20}(skin|rubbing|touch|wound|on a wound)", "Allodynia β€” sandpaper sensation"),
        (r"(light touch|cotton|shirt).{0,30}(sandpaper|stinging|hurts|pain|painful|wound)", "Allodynia β€” light touch painful"),
        (r"(cell phone|vibration).{0,20}(hip|bone|deep)", "Internal vibration (pallanaesthesia)"),
        (r"(gloves|socks).{0,30}(muffled|numb|thick)", "Glove-and-stocking numbness"),
        (r"(sloshy|wet).{0,20}(shoes|feet)", "Sloshy / wet sensation"),
        (r"(ants|ant|insect|bug).{0,20}(crawl|crawling|creeping).{0,20}(scalp|neck|skin|face|arm|leg)", "Formication (ants crawling)"),
        (r"(palm.sized|patch).{0,40}(wooden|numb)", "Specific numb patch"),
        (r"felt.{0,10}(wooden|completely numb)", "Felt wooden / numb"),
    ],

    # ── Standard: Proprioception loss ─────────────────────────────────────────
    "proprioception_loss": [
        (r"(lose|loses|lost|where).{0,20}(feet|track of|dark|look down)", "Proprioception loss"),
        (r"(walk.{0,15}dark|dark.{0,15}walk).{0,30}(look down|feet|where)", "Proprioception loss in dark"),
        (r"vibratory sense.{0,20}(loss|impaired|decreased|reduced)", "Vibratory sense loss"),
        (r"(position sense|proprioception).{0,20}(impaired|loss|reduced)", "Proprioception impaired (clinical)"),
    ],

    # ── Standard: Autonomic / bladder / bowel ────────────────────────────────
    "autonomic_ms": [
        (r"(urinary urgency|bladder urgency|urge to urinate|urgency urination|frequency urination)", "Urinary urgency"),
        (r"(bowel|bladder).{0,20}(problem|control|urgency|incontinence|dysfunction)", "Bladder / bowel dysfunction"),
        (r"(urinary|urinating).{0,20}(problem|urgency|frequent|difficult)", "Urinary dysfunction"),
        (r"(incontinence|incontinent|nocturia|multiple voids|voiding)", "Incontinence / nocturia"),
        (r"(incomplete bladder|bladder emptying|urinary bladder)", "Incomplete bladder emptying"),
        (r"\b(neurogenic bladder|neurogenic bowel)\b", "Neurogenic bladder / bowel"),
        (r"(constipation|bowel.{0,20}(control|incontinence|problem)).{0,20}(ms|neurological|multiple sclerosis)", "MS-related bowel dysfunction"),
        (r"(fecal incontinence|bowel incontinence|bowel leakage)", "Fecal / bowel incontinence"),
    ],

    # ── Standard: Visual mimic flags ─────────────────────────────────────────
    "visual_mimic_flags": [
        (r"(floater|floaters|dark spot|black spot|spot.{0,15}moves|moving spot)", "Floaters / dark spot (retinal flag)"),
        (r"(red.{0,10}eye|red.{0,10}painful eye|painful.{0,10}red eye)", "Red painful eye (mimic flag)"),
        (r"(flickering lights|flicker.{0,15}light|scintillating).{0,30}(20 min|min|lasts|aura)", "Flickering lights β€” migraine aura flag"),
        (r"(chronic|progressive).{0,20}(vision loss|visual loss).{0,30}(1 year|year|months?)", "Chronic progressive vision loss β€” tumour flag"),
    ],

    # ── Standard: Cognitive / brain fog ──────────────────────────────────────
    "cognitive_ms": [
        (r"(brain|mind).{0,15}(fog|cloudy|slow|blank|mush)", "Brain fog"),
        (r"(memory|remember).{0,20}(loss|lapse|bad|poor|failing|forget)", "Memory lapses"),
        (r"(cognitive|concentration|attention).{0,20}(impair|problem|difficult|decline|deficit)", "Cognitive impairment (clinical)"),
        (r"impaired.{0,10}(memory|short.term memory|recall)", "Impaired memory"),
        (r"(word.{0,10}finding|anomia|forget.{0,10}words|lose.{0,10}words)", "Word-finding difficulty"),
        (r"(slow.{0,10}processing|processing speed|slow.{0,10}thinking|thinking.{0,10}slow)", "Slowed cognitive processing"),
    ],

    # ── Standard: Fatigue ─────────────────────────────────────────────────────
    "fatigue_ms": [
        (r"(severe|extreme|debilitating|significant|profound|marked).{0,20}(fatigue|exhaustion|tiredness)", "Severe MS fatigue"),
        (r"(fatigue|exhaustion).{0,20}(ms|multiple sclerosis|relapse|symptom)", "MS-associated fatigue"),
        (r"(chronic fatigue|persistent fatigue|overwhelming fatigue|constant fatigue)", "Chronic / persistent fatigue"),
    ],

    # ── Standard: Dysarthria / dysphagia ─────────────────────────────────────
    "dysarthria_dysphagia": [
        (r"(slurred speech|dysarthria|speech.{0,15}(slur|difficult|impaired))", "Dysarthria (slurred speech)"),
        (r"(swallowing.{0,20}(difficult|problem|impaired)|dysphagia|aspirat)", "Dysphagia / aspiration"),
        (r"(tongue.{0,15}(slow|weak|impaired)|difficulty speaking)", "Tongue / speech difficulty"),
    ],

    # ── Standard: Dysphagia isolated (v8.1) ──────────────────────────────────
    "dysphagia_ms": [
        (r"(swallowing.{0,20}(difficult|problem|impaired|trouble)|dysphagia)", "Swallowing difficulty"),
        (r"(food.{0,20}stuck.{0,20}throat|choking.{0,20}(eat|drink|swallow))", "Food stuck / choking"),
        (r"(coughing.{0,20}(eat|drink|swallow)|aspiration)", "Aspiration / coughing when eating"),
    ],

    # ── Standard: Pseudobulbar affect ────────────────────────────────────────
    "pseudobulbar_affect": [
        (r"(laugh|laughing|cry|crying|weep).{0,30}(uncontrollable|random|no reason|inappropriate)", "Pseudobulbar affect (PBA)"),
        (r"\b(pseudobulbar|emotional lability)\b.{0,20}", "Pseudobulbar affect / emotional lability"),
    ],

    # ── Standard: Nocturnal spasms ────────────────────────────────────────────
    # Note: RLS intentionally omitted here β€” stays in sleep_disturbance_ms (LP)
    "nocturnal_spasms": [
        (r"(spasm|cramp|stiff|jerk|kick).{0,30}(night|sleep|bed|nocturnal|waking)", "Nocturnal spasms / kicks"),
        (r"(night kick|night kicks)", "Night kicks"),
    ],

    # ── Standard: Thermal dysesthesia ────────────────────────────────────────
    "thermal_dysesthesia": [
        (r"(feet|legs|foot|soles).{0,20}(burn|fire|hot|hot coals|stinging|needles)", "Burning / hot feet / legs"),
    ],

    # ═══════════════════════════════════════════════════════════════════════════
    # NEW IN v8.1 β€” Paroxysmal / Rare / Internet-sourced categories
    # ═══════════════════════════════════════════════════════════════════════════

    # ── ANCHOR: Paroxysmal MS symptoms ────────────────────────────────────────
    # Source: PMC 2024, Frontiers in Neurology, StatPearls
    "paroxysmal_ms": [
        (r"(paroxysmal).{0,30}(dysarthria|ataxia|diplopia|hemiparesis|sensory|symptom)", "Paroxysmal MS symptom"),
        (r"(episodic|stereotyped|brief.{0,10}recurring).{0,20}(motor|sensory|speech|movement|neurological)", "Stereotyped recurring neurological episodes"),
        (r"(dystonic|dystonia).{0,20}(episode|attack|spasm).{0,20}(ms|sclerosis|neurological)", "Dystonic episode (paroxysmal MS)"),
        (r"(paroxysmal dysarthria|paroxysmal ataxia|paroxysmal hemiparesis|paroxysmal sensory)", "Paroxysmal dysarthria / ataxia / hemiparesis"),
        (r"(paroxysmal.{0,20}(symptom|episode|attack)).{0,20}(ms|sclerosis|demyelinating)", "Paroxysmal MS episode"),
        (r"(paroxysmal dystonia|paroxysmal posturing).{0,20}(ms|first|initial|manifestation)", "Paroxysmal dystonia β€” MS first sign"),
    ],

    # ── ANCHOR: Tonic spasms ──────────────────────────────────────────────────
    # Source: Frontiers 2024, PubMed, Cureus
    "tonic_spasms_ms": [
        (r"(tonic spasm|painful tonic|tonic seizure).{0,20}(ms|multiple sclerosis|episodic|brief|posture|limb)", "Tonic spasms in MS"),
        (r"(involuntary.{0,20}(flexion|extension|posturing|tonic).{0,20}(ms|episodic|brief))", "Involuntary tonic posturing"),
        (r"(painful.{0,15}stereotyped.{0,15}(episode|spasm|attack)|stereotyped.{0,15}painful.{0,15}episode)", "Painful stereotyped episodes"),
    ],

    # ── ANCHOR: Tumefactive MS ────────────────────────────────────────────────
    # Source: Frontiers 2024, ScienceDirect
    "tumefactive_ms": [
        (r"(tumefactive|large lesion|mass effect).{0,20}(ms|multiple sclerosis|demyelinating)", "Tumefactive MS"),
        (r"(rapid.{0,15}deterioration|progressive.{0,15}deterioration).{0,20}(ms|lesion|neurological)", "Rapid neurological deterioration"),
        (r"ring.{0,10}enhancement.{0,20}(ms|lesion|gadolinium|mri)", "Ring-enhancing lesion (tumefactive)"),
        (r"tumefactive multiple sclerosis", "Tumefactive multiple sclerosis"),
    ],

    # ── Standard: Paroxysmal pruritis ─────────────────────────────────────────
    # Source: PMC 2020 review, Cureus case report
    "paroxysmal_pruritis": [
        (r"(paroxysmal|intense|episodic|sudden).{0,15}(itch|itching|pruritis|pruritus)", "Paroxysmal itching"),
        (r"(intense itching|severe itching).{0,20}(dermatome|ms|neurological|skin|no.{0,10}rash)", "Intense dermatome itching"),
        (r"itch.{0,30}(ms|multiple sclerosis|dermatome|neurological|spinal cord)", "Neurological pruritis in MS"),
    ],

    # ── Standard: Transverse myelitis ────────────────────────────────────────
    # Source: NINDS, StatPearls
    "transverse_myelitis": [
        (r"(transverse myelitis|myelitis|spinal cord.{0,20}(inflam|lesion|demyelinating))", "Transverse / spinal cord myelitis"),
        (r"(acute myelitis|subacute myelitis|partial myelitis)", "Acute / partial myelitis"),
    ],

    # ── Standard: Cerebellar variant ─────────────────────────────────────────
    # Source: StatPearls, WebMD
    "cerebellar_ms": [
        (r"\b(cerebellar.{0,20}(ataxia|tremor|variant|ms|lesion))\b", "Cerebellar MS variant"),
        (r"(charcot triad|intention tremor.{0,20}nystagmus|nystagmus.{0,20}intention tremor)", "Charcot triad (cerebellar MS)"),
    ],

    # ── Standard: Gustatory / taste disturbance ───────────────────────────────
    # Source: StatPearls, PMC
    "gustatory_ms": [
        (r"(taste.{0,20}(hallucination|altered|distorted|loss|abnormal|changed))", "Taste hallucination / disturbance"),
        (r"(dysgeusia|ageusia|gustatory.{0,15}(symptom|disturbance|hallucination))", "Dysgeusia / ageusia (clinical)"),
        (r"(food.{0,15}(taste|tastes).{0,15}(different|wrong|strange|metallic|bland|off)).{0,20}(neurological|ms)", "Food tastes wrong / metallic"),
        (r"(altered taste|taste disturbance).{0,20}(neurological|ms|sclerosis)", "Altered taste (MS context)"),
    ],

    # ── Standard: Euphoria / inappropriate affect ─────────────────────────────
    # Source: Merck Manual 2024
    "euphoria_ms": [
        (r"(euphoria|euphoric|inappropriate happiness|manic episode).{0,20}(ms|neurological|cerebral|brain)", "Euphoria in MS"),
        (r"(apathy|poor judgment|inattention).{0,20}(ms|neurological|cerebral|cognitive)", "Apathy / poor judgment (MS)"),
    ],

    # ── Standard: Useless hand (Oppenheim) ───────────────────────────────────
    # Source: StatPearls 2024
    "useless_hand_ms": [
        (r"(useless hand|oppenheim|loss of.{0,10}function.{0,10}hand|hand.{0,10}useless).{0,20}(ms|neurological|demyelinating)", "Useless hand (Oppenheim sign)"),
        (r"(difficulty.{0,20}(crossing road|pour|pouring|playing ball).{0,20}(ms|neurological|dexterity))", "Difficulty pouring / crossing road"),
        (r"(sense of.{0,10}uselessness.{0,10}hand|hand.{0,10}function.{0,10}lost)", "Sense of hand uselessness"),
    ],

    # ── Standard: Seizures in MS ─────────────────────────────────────────────
    # Source: StatPearls, Frontiers, PubMed
    "seizures_ms": [
        (r"(seizure|epileptic).{0,30}(ms|multiple sclerosis|demyelinating)", "Seizures in MS"),
        (r"(focal seizure|tonic.clonic|absence seizure).{0,20}(ms|neurological|brain lesion)", "Focal / generalised seizure in MS"),
        (r"(epilepsy|epileptic).{0,20}(ms|multiple sclerosis)", "Epilepsy / MS comorbidity"),
    ],

    # ── Standard: Prodromal / RIS (2024 McDonald) ────────────────────────────
    # Source: PMC 2024, McDonald criteria 2024
    "prodromal_ms": [
        (r"(radiologically isolated syndrome|\bris\b).{0,20}(ms|white matter|lesion)", "Radiologically isolated syndrome (RIS)"),
        (r"(subclinical|asymptomatic).{0,20}(ms|lesion|demyelinating|white matter)", "Subclinical / asymptomatic MS lesions"),
        (r"(prodromal.{0,20}ms|ms.{0,20}prodromal)", "Prodromal MS"),
    ],

    # ── Standard: Psychiatric first presentation ──────────────────────────────
    # Source: Merck, Cureus
    "psychiatric_ms": [
        (r"(psychiatric.{0,20}(symptom|presentation|ms|first))", "Psychiatric first presentation of MS"),
        (r"(mood disorder.{0,20}(ms|neurological|brain|lesion))", "Mood disorder with MS lesion"),
        (r"(psychosis|mania|bipolar).{0,20}(ms|multiple sclerosis|demyelinating)", "Psychosis / mania in MS"),
    ],

    # ── Standard: Functional overlay on MS ───────────────────────────────────
    # Source: NHS, Frontiers
    "functional_ms": [
        (r"(functional neurological|functional overlay).{0,20}(ms|multiple sclerosis|confirmed)", "Functional overlay on MS"),
        (r"(functional.{0,15}disorder|non.organic).{0,20}(ms|confirmed|comorbid)", "Functional neurological disorder comorbid MS"),
        (r"functional overlay on.{0,15}(ms|multiple sclerosis|confirmed ms)", "Functional overlay on confirmed MS"),
    ],
}


# ═══════════════════════════════════════════════════════════════════════════════
# TIER 3: LOW-PRIORITY PATTERNS  (1.0 pt each β€” fixed weight)
#
# These are recognised MS symptoms but non-specific and insufficient alone to
# independently trigger HIGH. They:
#   β€’ Add 1.0 pt each to combined score
#   β€’ LP-only β†’ WATCH tier
#   β€’ LP + standard β†’ can escalate WATCH β†’ MODERATE
#   β€’ LP + anchor β†’ HIGH (anchor override)
#
# To add a new low-priority category: add key + patterns here.
# No other code changes needed.
# ═══════════════════════════════════════════════════════════════════════════════
LOW_PRIORITY_PATTERNS: Dict[str, List[tuple]] = {

    # LP-1: Heat sensitivity (non-visual)
    # Distinct from Uhthoff's (which requires visual/gait component).
    # Generalised heat intolerance, summer worsening β€” common MS soft sign.
    "heat_sensitivity_general": [
        (r"(heat|warm|hot).{0,30}(worsen|worse|trigger|tired|exhaust|weak|fatigue)", "Heat worsening general symptoms"),
        (r"(feel worse|feel bad|symptoms worse).{0,20}(heat|warm|hot|summer|sauna)", "Symptoms worse in heat"),
        (r"(cannot tolerate|intolerant to|sensitive to).{0,20}(heat|warm|hot|sun)", "Heat intolerance (general)"),
        (r"(summer|hot weather|warm weather).{0,20}(worse|bad|difficult|relapse|trigger)", "Summer symptom worsening"),
    ],

    # LP-2: Chronic pain (non-TN)
    "chronic_pain_ms": [
        (r"(chronic|persistent|constant|ongoing).{0,15}(pain|aching|burning|discomfort)", "Chronic pain"),
        (r"(back pain|leg pain|arm pain|body pain|joint pain).{0,30}(ms|neurological|nerve|numb)", "MS-related pain"),
        (r"(burning|aching).{0,20}(legs|arms|back|body|limbs).{0,30}(constant|chronic|always|persistent)", "Burning / aching extremities"),
        (r"(central sensitiz|central sensitisation|neuropathic pain|allodynia).{0,20}", "Central sensitisation / neuropathic pain"),
        (r"(pain.{0,15}unresponsive|pain.{0,15}not respond).{0,20}(paracetamol|ibuprofen|nsaid|analgesic)", "Pain unresponsive to analgesia"),
    ],

    # LP-3: Sleep disturbance
    "sleep_disturbance_ms": [
        (r"(insomnia|cannot sleep|trouble sleeping|poor sleep|sleep disturbance)", "Insomnia / sleep disturbance"),
        (r"(non.restorative sleep|unrefreshing sleep|wake.{0,10}unrefreshed|tired after sleep)", "Non-restorative sleep"),
        (r"(periodic limb|limb movement).{0,20}(sleep|night|bed)", "Periodic limb movement in sleep"),
        (r"(sleep.{0,15}(problem|issue|disorder)).{0,20}(ms|fatigue|spasm|pain)", "Sleep problem (MS context)"),
    ],

    # LP-4: Sexual dysfunction
    "sexual_dysfunction_ms": [
        (r"(sexual dysfunction|sexual problem|sexual difficulty|sex.{0,10}problem)", "Sexual dysfunction"),
        (r"(reduced libido|low libido|decreased libido|loss of libido|no desire)", "Reduced libido"),
        (r"(erectile dysfunction|impotence|erection problem)", "Erectile dysfunction"),
        (r"(genital.{0,15}(numb|numbness|tingle|sensation|sensory))", "Genital numbness / tingling"),
        (r"(arousal.{0,15}(problem|difficult|reduced|impaired)|lubrication.{0,15}(problem|reduced|impaired))", "Arousal / lubrication difficulty"),
        (r"(orgasm.{0,15}(difficult|problem|impaired|absent|reduced))", "Orgasmic dysfunction"),
        (r"(vaginal dryness|decreased lubrication)", "Vaginal dryness / decreased lubrication"),
    ],

    # LP-5: Mood and affect (sustained β€” distinct from pseudobulbar)
    "mood_affect_ms": [
        (r"(depression|depressed|low mood|feeling down|hopeless).{0,30}(ms|neurological|since|for months|for years)", "MS-related depression"),
        (r"(anxiety|anxious|panic attack|worry).{0,30}(ms|neurological|symptoms|worsening)", "MS-related anxiety"),
        (r"(mood swings|emotional lability|irritability|mood changes).{0,30}(ms|neurological|recent|new)", "Mood swings / lability"),
        (r"(euphoria|euphoric).{0,20}(ms|inappropriate|unusual)", "Euphoria (MS sign)"),
        (r"(emotional.{0,10}(flatness|blunting|numbing)|apathy|motivation.{0,10}(loss|reduced|low))", "Emotional flattening / apathy"),
    ],

    # LP-6: Tinnitus / hearing changes
    "tinnitus_hearing_ms": [
        (r"(tinnitus|ringing in.{0,10}ear|buzzing in.{0,10}ear|ringing ear)", "Tinnitus (ringing in ears)"),
        (r"(chronic.{0,10}buzzing|persistent.{0,10}buzzing|constant.{0,10}buzzing).{0,20}(ear|head)", "Chronic buzzing in ears"),
        (r"(hearing loss|hearing impairment|hard of hearing|decreased hearing)", "Hearing loss / impairment"),
        (r"(sudden hearing loss|sudden deafness)", "Sudden hearing loss"),
        (r"(auditory.{0,15}(hallucination|distortion|problem)|sound.{0,10}(distorted|strange|weird))", "Auditory disturbance"),
    ],

    # LP-7: Cognitive fatigue (specific β€” distinct from generalised cognitive_ms)
    "cognitive_fatigue_ms": [
        (r"(mental fatigue|cognitive fatigue|brain.{0,10}exhaust|mental exhaustion)", "Cognitive / mental fatigue"),
        (r"(brain.{0,10}(shut|shut down|give up|stop working)|mind.{0,10}blank.{0,10}(exhaust|tired|fatigue))", "Brain shutting down feeling"),
        (r"(cannot.{0,10}concentrate|hard to concentrate|concentration.{0,10}(problem|difficult|poor))", "Concentration difficulty"),
        (r"(mental.{0,10}(fog|foggy|cloudy|slow)).{0,20}(after|following|when).{0,20}(effort|activity|task)", "Mental fog after effort"),
    ],

    # LP-8: Bowel dysfunction (isolated β€” standard if combined with other autonomic)
    "bowel_dysfunction_ms": [
        (r"(constipation|bowel.{0,20}(problem|control|issue|incontinence))", "Constipation / bowel control problems"),
        (r"(fecal incontinence|bowel incontinence|bowel leakage)", "Bowel incontinence"),
        (r"(neurogenic bowel|bowel dysfunction)", "Neurogenic bowel dysfunction"),
    ],

    # LP-9: Respiratory (MS-related)
    "respiratory_ms": [
        (r"(shortness of breath|breathing.{0,20}(difficulty|problem|trouble)).{0,20}(ms|neurological|weakness|fatigue)", "Shortness of breath (MS respiratory weakness)"),
        (r"(respiratory.{0,20}(weakness|dysfunction|problem)).{0,20}(ms|neurological)", "Respiratory weakness in MS"),
        (r"diaphragm.{0,20}(weakness|paralysis|dysfunction)", "Diaphragm weakness / dysfunction"),
    ],

    # LP-10: Headache (MS context)
    "headache_ms": [
        (r"(headache|head pain).{0,20}(ms|multiple sclerosis|relapse|lesion|worsening)", "Headache in MS context"),
        (r"(ms.{0,20}migraine|migraine.{0,20}ms)", "Migraine β€” MS comorbidity"),
        (r"(persistent headache|chronic headache|new.{0,10}headache).{0,20}(neurological|ms|spine)", "Persistent headache (MS context)"),
        (r"headache.{0,60}(started|began).{0,30}(neurological|ms|symptom)", "Headache onset with neurological symptoms"),
    ],

    # LP-11: Skin sensation / hypersensitivity
    "skin_sensation_ms": [
        (r"(skin.{0,20}sensitive|sensitive skin|hypersensitive).{0,20}(ms|neurological|touch)", "Skin hypersensitivity"),
        (r"\b(allodynia|hyperaesthesia|cutaneous.{0,15}(pain|sensitivity))\b", "Allodynia / hyperaesthesia"),
        (r"(prickling|pins and needles).{0,20}(skin|face|arm|leg|body)", "Prickling / pins and needles on skin"),
    ],

    # LP-12: Pain in MS (central / neuropathic β€” non-TN)
    "pain_ms": [
        (r"(neuropathic pain|central pain).{0,20}(ms|multiple sclerosis|neurological)", "Neuropathic / central pain in MS"),
        (r"(trigeminal neuralgia|painful.{0,15}spasm)", "Painful spasm / TN-like pain"),
        (r"(burning pain|stabbing pain|shooting pain).{0,20}(leg|arm|back|face|body|extremities)", "Burning / stabbing / shooting pain"),
    ],

    # LP-13: Menstrual / perimenstrual worsening (v8.1 new)
    # Source: MSAA, PMC 2024
    "menstrual_ms": [
        (r"(perimenstrual|menstrual|period).{0,20}(worse|worsen|relapse|trigger|symptom|ms)", "Perimenstrual symptom worsening"),
        (r"(symptoms worse.{0,20}(period|menstruation|cycle)|period.{0,30}ms symptom)", "Symptoms worse around period"),
    ],

    # LP-14: Stress-triggered worsening (v8.1 new)
    # Source: NHS, WebMD
    "stress_triggered_ms": [
        (r"(psychological stress|emotional stress|stress).{0,30}(trigger|worsen|worse|uhthoff|ms|symptom)", "Stress triggering MS symptoms"),
        (r"(stress.{0,20}trigger.{0,20}ms|ms.{0,20}stress.{0,20}trigger)", "Stress β€” MS pseudo-relapse trigger"),
    ],

    # LP-15: Pregnancy / postpartum (v8.1 new)
    # Source: NINDS, MS Society
    "pregnancy_ms": [
        (r"(pregnancy|pregnant|postpartum).{0,30}(ms|relapse|symptom|worse|improve)", "Pregnancy / postpartum MS risk"),
        (r"(ms.{0,20}(pregnancy|pregnant|postpartum)|(pregnancy|pregnant|postpartum).{0,20}ms)", "MS and pregnancy / postpartum"),
    ],
}


# ═══════════════════════════════════════════════════════════════════════════════
# SEVERITY MODIFIERS
# ═══════════════════════════════════════════════════════════════════════════════
SEVERITY_MODIFIERS = {
    "severe": {
        "patterns": [r"\b(severe|complete|total|worst|extreme|unbearable|debilitating|paralyzed|blind)\b"],
        "weight": 1.5,
        "label": "Severe",
    },
    "mild": {
        "patterns": [r"\b(mild|slight|faint|occasional|sometimes|a little|minor|brief)\b"],
        "weight": 0.5,
        "label": "Mild / Occasional",
    },
}


# ═══════════════════════════════════════════════════════════════════════════════
# WORKUP RECOMMENDATIONS BY TIER
# ═══════════════════════════════════════════════════════════════════════════════
WORKUP_BY_TIER: Dict[str, List[str]] = {
    "CRITICAL_EMERGENCY": [],
    "HIGH": [
        "MRI of orbits with and without contrast β€” screen for optic nerve involvement",
        "MRI brain and spinal cord with and without contrast",
        "Lumbar puncture β€” CSF for IgG index, oligoclonal bands (>2 exclusive to CSF), kappa free light chains",
        "Serum cell-based assay β€” NMO antibody (AQP4-IgG) and MOGAD (MOG-IgG)",
        "Full neurological examination by a neurologist",
        "Exclude mimics: sarcoidosis, lupus, vasculitis, B12 deficiency, cervical myelopathy",
    ],
    "MODERATE": [
        "Neurology referral β€” clinical review of symptom pattern",
        "Basic blood panel β€” FBC, B12, folate, thyroid, ESR, CRP, ANA",
        "Consider MRI brain if symptoms persist or evolve",
        "Ophthalmology review if visual symptoms are present",
        "Keep a symptom diary β€” track onset, duration, and triggers",
    ],
    "WATCH": [
        "Document symptoms carefully β€” note dates of onset, frequency, and any new neurological signs",
        "Schedule a GP / family physician review",
        "If new neurological symptoms appear (visual change, numbness, weakness, coordination problems), seek neurology referral promptly",
        "Re-assess in 4–8 weeks or sooner if symptoms worsen",
    ],
    "LOW": [
        "No MS-specific features detected at this time",
        "Continue to monitor β€” if new neurological symptoms develop, seek medical review",
        "Keep a symptom diary for any changes",
    ],
}


# ═══════════════════════════════════════════════════════════════════════════════
# TIER CONFIGURATION
# ═══════════════════════════════════════════════════════════════════════════════
TIER_CONFIG: Dict[str, dict] = {
    "CRITICAL_EMERGENCY": {
        "tier_label": "Emergency",
        "tier_subtitle": "Seek immediate emergency care",
        "action": "Call emergency services immediately (999 / 911). Do not wait.",
    },
    "HIGH": {
        "tier_label": "High MS Risk",
        "tier_subtitle": "Neurological referral recommended",
        "action": (
            "The symptom pattern is consistent with possible Multiple Sclerosis. "
            "Urgent referral to neurology is recommended for a full Multiple Sclerosis workup including "
            "MRI of the orbits, brain and spinal cord, lumbar puncture, and specialist examination."
        ),
    },
    "MODERATE": {
        "tier_label": "Moderate β€” Monitor",
        "tier_subtitle": "Neurological symptoms present β€” clinical review recommended",
        "action": (
            "Some neurologically relevant symptoms are present. "
            "A clinical review and basic investigations are recommended. "
            "Seek neurology referral if symptoms persist, recur, or new symptoms develop."
        ),
    },
    "WATCH": {
        "tier_label": "Watch β€” Low-Priority Symptoms",
        "tier_subtitle": "Recognised Multiple Sclerosis soft signs β€” clinical monitoring advised",
        "action": (
            "The symptoms described are recognised in MS but are non-specific and "
            "insufficient on their own to indicate high risk. Monitor closely. "
            "If any new or escalating neurological symptoms appear β€” particularly visual "
            "changes, numbness, weakness, or coordination problems β€” seek medical review promptly."
        ),
    },
    "LOW": {
        "tier_label": "No Specific Features Detected",
        "tier_subtitle": "No Multiple Sclerosis-specific pattern identified",
        "action": (
            "No MS-specific symptom features were detected in this description. "
            "If your symptoms persist or you develop new neurological symptoms, "
            "please consult a healthcare professional."
        ),
    },
}


# ═══════════════════════════════════════════════════════════════════════════════
# NLP HELPERS
# ═══════════════════════════════════════════════════════════════════════════════
_doc_cache: dict = {}  # single-call cache: parse text ONCE per classify() call


def _get_doc(text_lower: str):
    """Parse text once and cache within a single classify() call."""
    if text_lower not in _doc_cache:
        _doc_cache.clear()          # keep cache size = 1
        _doc_cache[text_lower] = nlp(text_lower)
    return _doc_cache[text_lower]


def _negex_check(text_lower: str, start_char: int, end_char: int) -> bool:
    """Returns True if the matched span is negated via NegEx. Uses cached doc."""
    doc = _get_doc(text_lower)
    span = doc.char_span(start_char, end_char, label="SYMPTOM", alignment_mode="expand")
    return bool(span and span._.negex)


def _severity_multiplier(text_lower: str) -> float:
    for mod in SEVERITY_MODIFIERS.values():
        for p in mod["patterns"]:
            if re.search(p, text_lower):
                return mod["weight"]
    return 1.0


# ═══════════════════════════════════════════════════════════════════════════════
# CORE CLASSIFIER
# ═══════════════════════════════════════════════════════════════════════════════
def classify(text: str) -> ClassifyResponse:
    """
    Three-tier MS symptom classification with NegEx negation detection.

    Scoring:
      Tier 1/2  (SYMPTOM_PATTERNS)      β†’ 3.0 pts Γ— severity multiplier
      Tier 3    (LOW_PRIORITY_PATTERNS)  β†’ 1.0 pt fixed

    Tier assignment:
      CRITICAL_EMERGENCY  β†’ emergency flag triggered
      HIGH                β†’ anchor hit + score β‰₯ 3, OR standard score β‰₯ 6
      MODERATE            β†’ standard score > 0
      WATCH               β†’ LP-only (no Tier 1/2 hits, LP score β‰₯ 1)
      LOW                 β†’ nothing detected
    """
    t = text.lower()

    # 1. Emergency check β€” no NegEx (emergencies always fire)
    for key, data in EMERGENCY_FLAGS.items():
        if any(re.search(p, t) for p in data["patterns"]):
            cfg = TIER_CONFIG["CRITICAL_EMERGENCY"]
            return ClassifyResponse(
                tier="CRITICAL_EMERGENCY",
                tier_label=data["label"],
                tier_subtitle=cfg["tier_subtitle"],
                action=data["action"],
                workup=[],
                features=[],
                temporal_notes=[],
            )

    # 2. Severity multiplier (applied globally)
    mult = _severity_multiplier(t)

    # 3. Tier 1/2 extraction with NegEx
    features: List[FeatureFound] = []
    has_anchor = False
    t12_score = 0.0

    for feat_key, patterns in SYMPTOM_PATTERNS.items():
        for pattern, label in patterns:
            for m in re.finditer(pattern, t):
                if not _negex_check(t, m.start(), m.end()):
                    pts = 3.0 * mult
                    t12_score += pts
                    if feat_key in ANCHOR_FEATURES:
                        has_anchor = True
                    features.append(FeatureFound(key=feat_key, label=label, priority="standard"))
                    break  # one hit per feature key
            else:
                continue
            break

    # 4. Tier 3 extraction with NegEx (1.0 pt fixed, no severity multiplier)
    lp_score = 0.0
    for feat_key, patterns in LOW_PRIORITY_PATTERNS.items():
        for pattern, label in patterns:
            for m in re.finditer(pattern, t):
                if not _negex_check(t, m.start(), m.end()):
                    lp_score += 1.0
                    features.append(FeatureFound(key=feat_key, label=label, priority="low"))
                    break
            else:
                continue
            break

    # 5. Temporal penalty β€” short-duration events (<24h) reduce score
    temporal_notes: List[str] = []
    if re.search(r"(minute|hour)s? ago", t) and not re.search(r"(day|week|month)s?", t):
        t12_score = max(0.0, t12_score - 2.0)
        temporal_notes.append(
            "Symptoms appear to be very short-duration (<24 hours). Clinical significance may be reduced."
        )

    # 6. Tier assignment
    if t12_score >= 6 or (t12_score >= 3 and has_anchor):
        tier = "HIGH"
    elif t12_score > 0:
        tier = "MODERATE"
    elif lp_score >= 1:
        tier = "WATCH"
    else:
        tier = "LOW"

    cfg = TIER_CONFIG[tier]
    return ClassifyResponse(
        tier=tier,
        tier_label=cfg["tier_label"],
        tier_subtitle=cfg["tier_subtitle"],
        action=cfg["action"],
        workup=WORKUP_BY_TIER.get(tier, []),
        features=features,
        temporal_notes=temporal_notes,
    )


# ═══════════════════════════════════════════════════════════════════════════════
# API ROUTES
# ═══════════════════════════════════════════════════════════════════════════════

@app.get("/ping")
async def ping():
    return "pong"


@app.post("/analyze")
async def analyze_endpoint(req: SymptomRequest):
    """
    Live risk panel endpoint β€” classifies accumulated conversation text.
    Accepts up to 3000 chars of combined human messages for best accuracy.
    No auth required.
    """
    try:
        # Strip common filler words that confuse the classifier
        # when full conversation is passed (greetings, "yes", "no" etc.)
        import re as _re
        text = req.text.strip()
        # Remove pure filler lines like "hi", "yes", "no", "ok", "thanks"
        lines = [l.strip() for l in text.split(".") if len(l.strip()) > 8]
        clean_text = ". ".join(lines) if lines else text

        result = classify(clean_text or text)
        score_map = {
            "LOW": 5, "WATCH": 30, "MODERATE": 55,
            "HIGH": 80, "CRITICAL_EMERGENCY": 100
        }
        return {
            "tier":          result.tier,
            "tier_label":    result.tier_label,
            "tier_subtitle": result.tier_subtitle,
            "action":        result.action,
            "score_pct":     score_map.get(result.tier, 5),
            "features":      [{"label": f.label, "priority": f.priority} for f in result.features],
            "workup":        result.workup[:5],
            "temporal_notes": result.temporal_notes,
        }
    except Exception as e:
        logger.error("[analyze] {}", e)
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/health")
async def health():
    return {
        "status": "ok",
        "model": "AxonIQ + Agentic AI",
        "negex": "active",
        "llm": "llama3.1:8b via Ollama",
        "rag": "ChromaDB (150 cases + MS guidelines)",
        "cases_validated": 150,
        "sources": "PMC 2024, NINDS, MSAA, NHS, Mayo, StatPearls, Cureus, Frontiers, Merck 2024",
        "team": {
            "domain_expert":          "Dr. Avasarala, MD PhD β€” University of Kentucky, Lexington KY, USA",
            "lead_ai_architect":      "Raghu Gangolu β€” NIT Warangal, Telangana, India",
            "principal_investigator": "Dr. Kadambari, PhD β€” NIT Warangal, Telangana, India",
        },
    }


@app.post("/classify", response_model=ClassifyResponse)
@limiter.limit("30/minute")
async def classify_endpoint(request: Request, req: SymptomRequest):
    if nlp is None:
        raise HTTPException(status_code=503, detail="NLP model not loaded")
    logger.info("[classify] text_len={}", len(req.text))
    return classify(req.text)


# ── Agentic AI Chat Endpoints ─────────────────────────────────────────────────

@app.post("/chat", response_model=ChatResponse)
@limiter.limit("20/minute")
async def chat_endpoint(
    request: Request,
    req: ChatRequest,
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """
    Main agentic AI chat endpoint (requires authentication).
    Creates a new session if session_id is not provided.
    Persists every message to SQLite with timestamps.
    """
    from api.memory import new_session, get_session, append_message, get_history
    from api.agent import chat as agent_chat
    from api.database import (
        create_db_session, save_message, get_session_owner,
        update_session_title, get_message_count,
    )

    user_id = current_user["id"]

    # Create or retrieve session
    sid = req.session_id
    if not sid or get_session(sid) is None:
        sid = new_session()
        create_db_session(sid, user_id)
        logger.info("[chat] New session: {} user={}", sid, user_id)
    else:
        # Security: ensure the session belongs to this user
        owner = get_session_owner(sid)
        if owner is not None and owner != user_id:
            raise HTTPException(status_code=403, detail="Session belongs to another user")
        if owner is None:
            # Legacy session without DB record β€” adopt it
            create_db_session(sid, user_id)

    # Persist user message to DB
    save_message(sid, "human", req.message)
    from api.database import log_action as _log_chat
    _log_chat("CHAT_MESSAGE", user_id=user_id, username=current_user["username"],
              detail=req.message[:120],
              session_uuid=sid,
              ip_address=getattr(request, 'client', None) and request.client.host)

    # Auto-title the session from first user message
    if get_message_count(sid) <= 1:
        title = req.message[:60].strip()
        update_session_title(sid, title)

    # Run classifier to extract structured conclusion and save to session
    try:
        from api.database import save_conclusion
        _cls = classify(req.message)
        if _cls.tier not in ("LOW",):  # only save meaningful conclusions
            save_conclusion(
                session_uuid=sid,
                tier=_cls.tier,
                tier_label=_cls.tier_label,
                symptoms=[f.label for f in _cls.features],
                workup=_cls.workup[:6],
                action=_cls.action,
            )
    except Exception as _ce:
        logger.warning("[chat] Conclusion save failed: {}", _ce)

    # Also keep in-memory store for agent context (existing logic)
    append_message(sid, "human", req.message)
    history = get_history(sid)

    logger.info("[chat] session={} user={} turn={} msg_len={}", sid, user_id, len(history), len(req.message))

    try:
        response_text = agent_chat(sid, req.message, history)
    except Exception as e:
        logger.error("[chat] Agent error: {}", e)
        raise HTTPException(status_code=500, detail=f"Agent error: {str(e)}")

    # Persist assistant response to DB
    save_message(sid, "assistant", response_text)
    append_message(sid, "assistant", response_text)

    return ChatResponse(
        session_id=sid,
        response=response_text,
        turn=len(get_history(sid)),
    )


@app.post("/session/new")
async def new_session_endpoint(
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """Create a new chat session for the authenticated user."""
    from api.memory import new_session
    from api.database import create_db_session
    sid = new_session()
    create_db_session(sid, current_user["id"])
    return {"session_id": sid}


@app.get("/user/sessions")
async def user_sessions(
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """List all chat sessions for the authenticated user (newest first)."""
    from api.database import get_user_sessions
    sessions = get_user_sessions(current_user["id"])
    return {"sessions": sessions}


@app.get("/session/{session_id}/history")
async def session_history(
    session_id: str,
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """Get full message history for a session (with timestamps)."""
    from api.database import get_messages, get_session_owner
    owner = get_session_owner(session_id)
    if owner is not None and owner != current_user["id"]:
        raise HTTPException(status_code=403, detail="Access denied")
    messages = get_messages(session_id)
    return {"session_id": session_id, "messages": messages}


@app.delete("/session/{session_id}")
async def delete_session(
    session_id: str,
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """Delete a session and all its messages."""
    from pathlib import Path
    from api.database import get_session_owner, delete_db_session
    owner = get_session_owner(session_id)
    if owner is not None and owner != current_user["id"]:
        raise HTTPException(status_code=403, detail="Access denied")
    delete_db_session(session_id)
    p = Path(f"/tmp/neurocheck_sessions/{session_id}.json")
    if p.exists():
        p.unlink()
    return {"deleted": session_id}


# ── Admin routes ──────────────────────────────────────────────────────────────
def require_admin(current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user)):
    if not current_user.get("is_admin"):
        raise HTTPException(status_code=403, detail="Admin access required")
    return current_user


@app.post("/auth/change-password")
async def change_password(
    request: Request,
    current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
):
    """Allow logged-in user to change their own password."""
    import bcrypt as _bcrypt
    body = await request.json()
    old_pw  = body.get("old_password", "")
    new_pw  = body.get("new_password", "")
    if not old_pw or not new_pw:
        raise HTTPException(status_code=400, detail="Both old and new password are required")
    if len(new_pw) < 6:
        raise HTTPException(status_code=400, detail="New password must be at least 6 characters")
    # Verify old password
    if not _bcrypt.checkpw(old_pw.encode("utf-8"), current_user["password_hash"].encode("utf-8")):
        raise HTTPException(status_code=401, detail="Current password is incorrect")
    # Set new password
    new_hash = _bcrypt.hashpw(new_pw.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
    from api.database import get_conn
    with get_conn() as conn:
        conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, current_user["id"]))
    return {"message": "Password changed successfully"}


@app.get("/admin/users")
async def admin_get_users(admin=Depends(require_admin)):
    """Return all users with stats."""
    from api.database import get_all_users_admin, get_all_sessions_admin, migrate_add_admin_column
    migrate_add_admin_column()
    users = get_all_users_admin()
    total_sessions, total_messages = get_all_sessions_admin()
    return {
        "users": users,
        "total_sessions": total_sessions,
        "total_messages": total_messages,
    }


@app.get("/admin/user/{user_id}/sessions")
async def admin_get_user_sessions(user_id: int, admin=Depends(require_admin)):
    """Return all sessions + full messages for a user."""
    from api.database import get_user_sessions_with_messages
    sessions = get_user_sessions_with_messages(user_id)
    return {"user_id": user_id, "sessions": sessions}




@app.post("/auth/forgot-password")
async def forgot_password(request: Request):
    """Step 1: generate OTP and send/return it."""
    import hashlib, random, string
    from datetime import datetime, timedelta, timezone
    from api.database import get_user_by_email, save_otp, migrate_add_otp_table

    migrate_add_otp_table()

    body  = await request.json()
    email = body.get("email", "").strip().lower()
    if not email:
        raise HTTPException(status_code=400, detail="Email is required")

    user = get_user_by_email(email)
    if not user:
        return {"dev_mode": True, "dev_otp": None,
                "dev_error": "No account found with this email. Please register first."}

    # Generate OTP
    otp     = "".join(random.choices(string.digits, k=6))
    otp_hash = hashlib.sha256(otp.encode()).hexdigest()
    expires = (datetime.now(timezone.utc) + timedelta(minutes=15)).isoformat()
    save_otp(user["id"], email, otp_hash, expires)

    # Try sending email
    smtp_ok = bool(os.environ.get("SMTP_EMAIL") and os.environ.get("SMTP_PASSWORD"))
    if smtp_ok:
        try:
            from api.email_utils import send_otp_email
            sent = send_otp_email(email, user["username"], otp)
            if sent:
                return {"message": "Code sent to your email"}
        except Exception as e:
            logger.error("[Auth] Email error: {}", e)

    # Dev mode β€” return OTP directly
    logger.warning("[Auth] Returning OTP in response (dev mode)")
    return {"dev_mode": True, "dev_otp": otp,
            "message": "Email not configured β€” use code below"}


@app.post("/auth/verify-otp")
async def verify_otp_endpoint(request: Request):
    """Step 2: verify OTP, return reset token."""
    import hashlib
    from api.database import get_valid_otp, mark_otp_used, migrate_add_otp_table
    from api.auth import create_access_token

    migrate_add_otp_table()

    body  = await request.json()
    email = body.get("email", "").strip().lower()
    otp   = body.get("otp", "").strip()

    if not email or not otp:
        raise HTTPException(status_code=400, detail="Email and code are required")

    record = get_valid_otp(email)
    if not record:
        raise HTTPException(status_code=400, detail="Code expired or not found. Request a new one.")

    otp_hash = hashlib.sha256(otp.encode()).hexdigest()
    if otp_hash != record["otp_hash"]:
        raise HTTPException(status_code=400, detail="Incorrect code. Please try again.")

    mark_otp_used(record["id"])
    reset_token = create_access_token(record["user_id"], "reset:" + email)
    return {"reset_token": reset_token, "message": "Code verified"}


@app.post("/auth/reset-password")
async def reset_password_with_token(request: Request):
    """Step 3: set new password using reset token."""
    import bcrypt as _bcrypt
    from api.database import update_user_password
    from api.auth import decode_token

    body   = await request.json()
    token  = body.get("reset_token", "")
    new_pw = body.get("new_password", "")

    if not token or not new_pw:
        raise HTTPException(status_code=400, detail="Token and password are required")
    if len(new_pw) < 6:
        raise HTTPException(status_code=400, detail="Password must be at least 6 characters")

    try:
        payload = decode_token(token)
        user_id = int(payload.get("sub", 0))
        if not str(payload.get("username", "")).startswith("reset:"):
            raise ValueError("Not a reset token")
    except Exception:
        raise HTTPException(status_code=400, detail="Reset link expired. Please request a new code.")

    new_hash = _bcrypt.hashpw(new_pw.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
    update_user_password(user_id, new_hash)
    return {"message": "Password updated successfully"}


@app.post("/admin/user/{user_id}/reset-password")
async def admin_reset_password(user_id: int, admin=Depends(require_admin)):
    """Admin resets any user password directly."""
    from api.database import get_user_by_id
    import bcrypt as _bcrypt, secrets
    user = get_user_by_id(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    # Generate a new random password
    new_password = secrets.token_urlsafe(10)
    new_hash = _bcrypt.hashpw(new_password.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
    from api.database import get_conn
    with get_conn() as conn:
        conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, user_id))
    return {
        "user_id": user_id,
        "username": user["username"],
        "new_password": new_password,
        "message": "Password reset. Share this with the user and ask them to change it after login."
    }


@app.get("/admin/logs")
async def admin_get_all_logs(admin=Depends(require_admin)):
    """Return recent activity logs across all users."""
    from api.database import get_all_logs
    return {"logs": get_all_logs(limit=500)}


@app.get("/admin/user/{user_id}/logs")
async def admin_get_user_logs(user_id: int, admin=Depends(require_admin)):
    """Return activity logs for a specific user."""
    from api.database import get_user_logs
    return {"user_id": user_id, "logs": get_user_logs(user_id, limit=200)}


# ── Serve frontend static files ───────────────────────────────────────────────
FRONTEND_DIR = os.path.normpath(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "frontend")
)

# Serve frontend β€” explicit HTMLResponse ensures correct Content-Type on all
# browsers and proxies (HuggingFace, ngrok, mobile Safari, etc.)
from fastapi.responses import HTMLResponse

def _read_html(filename: str) -> str:
    path = os.path.join(FRONTEND_DIR, filename)
    with open(path, "r", encoding="utf-8") as f:
        return f.read()

# Mount static files
if os.path.isdir(FRONTEND_DIR):
    app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")

# ── Frontend routes β€” registered unconditionally so HF proxy never 404s ──────
# Explicit HTMLResponse (not FileResponse) ensures correct Content-Type
# on all clients including mobile Safari, Android Chrome, and HF proxy.

@app.get("/", response_class=HTMLResponse)
async def serve_index():
    return HTMLResponse(content=_read_html("index.html"), status_code=200)

@app.get("/chat-ui", response_class=HTMLResponse)
async def serve_chat():
    return HTMLResponse(content=_read_html("chat.html"), status_code=200)

@app.get("/chat-ui/", response_class=HTMLResponse)
async def serve_chat_slash():
    return HTMLResponse(content=_read_html("chat.html"), status_code=200)

@app.get("/chat", response_class=HTMLResponse)
async def serve_chat_alt():
    """Alias β€” /chat redirects to chat UI on mobile browsers."""
    return HTMLResponse(content=_read_html("chat.html"), status_code=200)

@app.get("/admin", response_class=HTMLResponse)
async def serve_admin_main():
    return HTMLResponse(content=_read_html("admin.html"), status_code=200)

@app.get("/admin/", response_class=HTMLResponse)
async def serve_admin_slash_main():
    return HTMLResponse(content=_read_html("admin.html"), status_code=200)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("api.main:app", host="0.0.0.0", port=8000, reload=True)