File size: 39,551 Bytes
260aff8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  USLaP โ€” Universal Scientific Laws and Principles v2.0      โ•‘
โ•‘  ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู                              โ•‘
โ•‘                                                              โ•‘
โ•‘  SINGLE MASTER CONTROL: USLAP_LATTICE.xlsx                   โ•‘
โ•‘  Edit the XLSX โ†’ this file reads it automatically.           โ•‘
โ•‘  One file to edit. One file to run.                          โ•‘
โ•‘                                                              โ•‘
โ•‘  ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ โ€” Response Algorithm                   โ•‘
โ•‘  Step 0: Terminology Scan (ููŽุญู’ุต ุงู„ู…ูุตู’ุทูŽู„ูŽุญูŽุงุช)               โ•‘
โ•‘  Step 1: Ibn Sฤซnฤ FIRST (ุงุจู† ุณูŠู†ุง ุฃูˆู‘ู„ุงู‹)                    โ•‘
โ•‘  Step 2: Al-Khwฤrizmฤซ Method (ุงู„ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ)                  โ•‘
โ•‘  Step 3: Tools & Applications (ุฃูŽุฏูŽูˆูŽุงุช)                      โ•‘
โ•‘  Step 4: Output (ุงู„ู…ูุฎู’ุฑูŽุฌูŽุงุช)                                 โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Usage:
  python3 uslap.py                      # Interactive menu
  python3 uslap.py --scan "text"        # Quick scan
  python3 uslap.py --process "query"    # Run Response Algorithm
  python3 uslap.py --export-json        # Export all data as JSON
  python3 uslap.py --info               # Show master control status

Requires: pip install openpyxl
Master control: Place USLAP_LATTICE.xlsx in same directory as this file.
"""

import json, re, sys, os
from pathlib import Path

# ============================================================
# MASTER CONTROL LOADER
# ============================================================

MASTER_FILE = "USLAP_LATTICE.xlsx"

def find_master():
    """Find USLAP_LATTICE.xlsx โ€” same dir as script, or current dir."""
    script_dir = Path(__file__).parent
    candidates = [
        script_dir / MASTER_FILE,
        Path.cwd() / MASTER_FILE,
        Path.home() / MASTER_FILE,
    ]
    for p in candidates:
        if p.exists():
            return p
    return None

def load_master(path):
    """Load all data from USLAP_LATTICE.xlsx master control."""
    try:
        import openpyxl
    except ImportError:
        print("ERROR: openpyxl required. Run: pip install openpyxl")
        sys.exit(1)

    wb = openpyxl.load_workbook(path, data_only=True)
    data = {
        "path": str(path),
        "modified": os.path.getmtime(path),
        "terms": [],
        "rejected": [],
        "sciences": [],
        "evidence": [],
        "applications": [],
        "meta": [],
        "two_systems": [],
        "deep_dive": [],
        "iqra_moments": [],
    }

    # ALL TERMS sheet
    if "All Terms" in wb.sheetnames:
        ws = wb["All Terms"]
        for r in range(2, ws.max_row + 1):
            term = ws.cell(r, 1).value
            if not term:
                continue
            data["terms"].append({
                "term": str(term).strip(),
                "status": str(ws.cell(r, 2).value or "").strip(),
                "domain_q": str(ws.cell(r, 3).value or "").strip(),
                "domain_t": str(ws.cell(r, 4).value or "").strip(),
                "replacement": str(ws.cell(r, 5).value or "").strip(),
                "root": str(ws.cell(r, 6).value or "").strip(),
                "ref": str(ws.cell(r, 7).value or "").strip(),
                "contamination": str(ws.cell(r, 8).value or "").strip(),
            })

    # REJECTED sheet (has etymology/confession detail)
    if "Rejected" in wb.sheetnames:
        ws = wb["Rejected"]
        for r in range(2, ws.max_row + 1):
            term = ws.cell(r, 1).value
            if not term:
                continue
            data["rejected"].append({
                "term": str(term).strip(),
                "etymology": str(ws.cell(r, 2).value or "").strip(),
                "domain": str(ws.cell(r, 3).value or "").strip(),
                "replacement": str(ws.cell(r, 4).value or "").strip(),
                "root": str(ws.cell(r, 5).value or "").strip(),
                "ref": str(ws.cell(r, 6).value or "").strip(),
            })

    # 111 SCIENCES sheet
    if "111 Sciences" in wb.sheetnames:
        ws = wb["111 Sciences"]
        for r in range(2, ws.max_row + 1):
            sid = ws.cell(r, 1).value
            if not sid:
                continue
            data["sciences"].append({
                "id": int(sid) if str(sid).isdigit() else 0,
                "root": str(ws.cell(r, 2).value or "").strip(),
                "meaning": str(ws.cell(r, 3).value or "").strip(),
                "verse": str(ws.cell(r, 4).value or "").strip(),
                "name_ar": str(ws.cell(r, 5).value or "").strip(),
                "name_t": str(ws.cell(r, 6).value or "").strip(),
            })

    # EVIDENCE sheet
    if "Evidence" in wb.sheetnames:
        ws = wb["Evidence"]
        for r in range(3, ws.max_row + 1):  # Skip header rows
            ev = ws.cell(r, 1).value
            if not ev:
                continue
            data["evidence"].append({
                "evidence": str(ev).strip(),
                "type": str(ws.cell(r, 2).value or "").strip(),
                "domain": str(ws.cell(r, 3).value or "").strip(),
            })

    # APPLICATIONS sheet
    if "Applications" in wb.sheetnames:
        ws = wb["Applications"]
        for r in range(2, ws.max_row + 1):
            app = ws.cell(r, 1).value
            if not app:
                continue
            data["applications"].append({
                "application": str(app).strip(),
                "domain": str(ws.cell(r, 2).value or "").strip(),
            })

    # META FAQ sheet
    if "Meta FAQ" in wb.sheetnames:
        ws = wb["Meta FAQ"]
        for r in range(2, ws.max_row + 1):
            q = ws.cell(r, 1).value
            if not q:
                continue
            data["meta"].append({
                "question": str(q).strip(),
                "domain": str(ws.cell(r, 2).value or "").strip(),
            })

    # TWO SYSTEMS sheet
    if "Two Systems" in wb.sheetnames:
        ws = wb["Two Systems"]
        for r in range(3, ws.max_row + 1):
            dim = ws.cell(r, 1).value
            if not dim:
                continue
            data["two_systems"].append({
                "dimension": str(dim).strip(),
                "moloch": str(ws.cell(r, 2).value or "").strip(),
                "quran": str(ws.cell(r, 3).value or "").strip(),
            })

    # DEEP DIVE sheet
    if "Deep Dive" in wb.sheetnames:
        ws = wb["Deep Dive"]
        for r in range(3, ws.max_row + 1):
            chain = ws.cell(r, 1).value
            if not chain:
                continue
            data["deep_dive"].append({
                "chain": str(chain).strip(),
                "crime": str(ws.cell(r, 2).value or "").strip(),
                "evidence": str(ws.cell(r, 3).value or "").strip(),
                "pre_trace": str(ws.cell(r, 4).value or "").strip(),
                "sources": str(ws.cell(r, 5).value or "").strip(),
                "quran_warning": str(ws.cell(r, 6).value or "").strip(),
            })

    # IQRA MOMENTS sheet
    if "IQRA Moments" in wb.sheetnames:
        ws = wb["IQRA Moments"]
        for r in range(3, ws.max_row + 1):
            num = ws.cell(r, 1).value
            if not num:
                continue
            data["iqra_moments"].append({
                "number": int(num) if str(num).isdigit() else 0,
                "target_lie": str(ws.cell(r, 2).value or "").strip(),
                "kill_shot": str(ws.cell(r, 3).value or "").strip(),
                "time": str(ws.cell(r, 4).value or "").strip(),
            })

    wb.close()
    return data


# ============================================================
# FOUR-SOURCE LATTICE (hardcoded โ€” this is the protocol itself)
# ============================================================

FOUR_SOURCES = [
    {"n": 1, "ar": "ุงู„ู‚ูุฑู’ุขู†", "t": "al-Qur'ฤn", "role": "Root + Meaning. Is it Qur'anic Arabic? FAIL โ†’ Deep Trace โ†’ Confession."},
    {"n": 2, "ar": "ุงู„ุญูŽุฏููŠุซ", "t": "al-แธคadฤซth", "role": "Prophetic confirmation. Sunnah confirms, explains, applies."},
    {"n": 3, "ar": "ุงู„ุนูู„ู’ู… ุงู„ูˆุณุทุงู†ูŠู‘", "t": "al-สฟIlm al-Waแนฃแนญฤnฤซ", "role": "Ibn Sฤซnฤ FIRST (framework), then al-Khwฤrizmฤซ (method). ุฃูู…ูŽู‘ุฉู‹ ูˆูŽุณูŽุทู‹ุง scholars."},
    {"n": 4, "ar": "ุนูู„ูŽู…ูŽุงุก ุฅูุถูŽุงูููŠูู‘ูˆู†", "t": "สฟUlamฤสพ Iแธฤfiyyลซn", "role": "Additional scholars. Subject to ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู + Qur'anic terminology verification."},
]

CONTAM_HIERARCHY = [
    {"level": 1, "name": "PRE-civilizational", "desc": "Parasite 'elite' vocabulary BEFORE host civilization. 100% criminal."},
    {"level": 2, "name": "Persian", "desc": "Most dangerous active contaminator. Corrupts Arabic + Turkic."},
    {"level": 3, "name": "Jahilian / corrupted Arabic", "desc": "Arabic-script wrapping Greek/PRE- contamination."},
    {"level": 4, "name": "Greek / Latin", "desc": "Surface HOST wrappers carrying PRE- vocabulary."},
]

RESPONSE_ALGORITHM = [
    {"step": 0, "ar": "ููŽุญู’ุต ุงู„ู…ูุตู’ุทูŽู„ูŽุญูŽุงุช", "en": "Terminology Scan", "mandatory": True,
     "action": "Scan ALL terms through Source 1. Replace contamination before proceeding.",
     "anti": "NEVER skip. NEVER use contaminated terms even casually."},
    {"step": 1, "ar": "ุงุจู† ุณูŠู†ุง ุฃูˆู‘ู„ุงู‹", "en": "Ibn Sฤซnฤ FIRST", "mandatory": True,
     "action": "Apply ุงู„ู‚ุงู†ูˆู† ููŠ ุงู„ุทุจ framework BEFORE any practical advice.",
     "subs": ["SYSTEM: What is the ู‚ูŽูˆู’ุณ (bow/system)?", "WARP: Longitudinal chain?",
              "WEFT: Lateral connections?", "BIAS: Where does pressure create change?",
              "ุตูŽู„ูŽุงุฉ DIAGNOSTIC: Do prayer positions test this?"],
     "anti": "NEVER jump to tools before this. #1 contamination trap."},
    {"step": 2, "ar": "ุงู„ุฎูŽูˆุงุฑูุฒู’ู…ููŠูŽู‘ุฉ", "en": "Al-Khwฤrizmฤซ Method", "mandatory": True,
     "action": "Define structured method: MEASURE โ†’ SEQUENCE โ†’ DECISION โ†’ VERIFY.",
     "anti": "NEVER give unstructured advice."},
    {"step": 3, "ar": "ุฃูŽุฏูŽูˆูŽุงุช", "en": "Tools & Applications", "mandatory": False,
     "action": "Practical interventions. Source 4. ONLY after Steps 0-2.",
     "anti": "Tools SERVE the framework."},
    {"step": 4, "ar": "ุงู„ู…ูุฎู’ุฑูŽุฌูŽุงุช", "en": "Output", "mandatory": True,
     "action": "Deliver what user asked for. ALL USLaP-compliant.",
     "anti": "NEVER deliver with contaminated terminology."},
]

# ============================================================
# CONTAMINATION SCANNER โ€” reads from master control
# ============================================================

class ContaminationScanner:
    """Scans text using the master control term database."""

    def __init__(self, master_data):
        self.terms = master_data["terms"]
        self.rejected = master_data["rejected"]
        self._build_index()

    # Hardcoded single-word scanning terms (common contamination)
    # These get OVERRIDDEN by XLSX data if present
    SCAN_TERMS = {
        "medical": {"repl": "ุงู„ุทูู‘ุจู‘ / al-แนฌibb (Return to Purity)", "ct": "Greek/Latin", "pre": "PRE-Latin *med- โ†’ Medea (child-killer)"},
        "medicine": {"repl": "ุงู„ุทูู‘ุจู‘ / al-แนฌibb", "ct": "Greek/Latin", "pre": "PRE-Latin *med- โ†’ Medea โ†’ Medici"},
        "surgery": {"repl": "ุงู„ุฌูุฑูŽุงุญูŽุฉ / al-Jirฤแธฅah (root ุฌ ุฑ ุญ, Q5:4)", "ct": "Greek/Latin", "pre": "Greek ฯ‡ฮตฮนฯฮฟฯ…ฯฮณฮฏฮฑ โ†’ PRE-Greek"},
        "surgical": {"repl": "ุฌูุฑูŽุงุญููŠู‘ / Jirฤแธฅฤซ", "ct": "Greek/Latin", "pre": "Greek ฯ‡ฮตฮนฯฮฟฯ…ฯฮณฮฏฮฑ"},
        "pharmaceutical": {"repl": "ุงู„ุตูŽู‘ูŠู’ุฏูŽู„ูŽุฉ / al-แนขaydalah", "ct": "Greek/Latin", "pre": "ฯ†ฮฑฯฮผฮฑฮบฮตฮฏฮฑ โ†’ PRE-Greek *pharmak- = POISON RITUAL"},
        "pharmacy": {"repl": "ุงู„ุตูŽู‘ูŠู’ุฏูŽู„ููŠูŽู‘ุฉ", "ct": "Greek/Latin", "pre": "ฯ†ฮฑฯฮผฮฑฮบฮตฮฏฮฑ โ†’ poison ritual"},
        "robot": {"repl": "ู…ูŽุตู’ู†ููˆุน / Maแนฃnลซสฟ (Q20:39 ุตูู†ู’ุนูŽ ุงู„ู„ูŽู‘ู‡ู)", "ct": "European", "pre": "Czech robota = SLAVERY"},
        "anatomy": {"repl": "ุนูู„ู’ู… ุงู„ุจูู†ู’ูŠูŽุฉ / สฟIlm al-Binyah", "ct": "Greek/Latin", "pre": "แผ€ฮฝฮฑฯ„ฮฟฮผฮฎ โ†’ cutting corpses"},
        "biology": {"repl": "ุนูู„ู’ู… ุงู„ุญูŽูŠูŽุงุฉ / สฟIlm al-แธคayฤh", "ct": "Greek/Latin", "pre": "Greek ฮฒฮฏฮฟฯ‚+ฮปฯŒฮณฮฟฯ‚"},
        "physics": {"repl": "ุนูู„ู’ู… ุงู„ุทูŽู‘ุจููŠุนูŽุฉ / สฟIlm al-แนฌabฤซสฟah", "ct": "Greek/Latin", "pre": "Greek ฯ†ฯฯƒฮนฯ‚"},
        "chemistry": {"repl": "ุนูู„ู’ู… ุงู„ุชูŽู‘ุญู’ูˆููŠู„ / สฟIlm al-Taแธฅwฤซl", "ct": "Greek/Latin", "pre": "ฯ‡ฮทฮผฮตฮฏฮฑ โ†’ dark transmutation"},
        "geometry": {"repl": "ุนูู„ู’ู… ุงู„ู…ูุณูŽุงุญูŽุฉ", "ct": "Greek/Latin", "pre": "ฮณฮตฯ‰ฮผฮตฯ„ฯฮฏฮฑ โ†’ land seizure"},
        "therapy": {"repl": "ุนูู„ูŽุงุฌ / สฟIlฤj", "ct": "Greek/Latin", "pre": "ฮธฮตฯฮฑฯ€ฮตฮฏฮฑ โ†’ ritual servitude"},
        "diagnosis": {"repl": "ุชูŽู‚ู’ูŠููŠู… / Taqyฤซm", "ct": "Greek/Latin", "pre": "Greek ฮดฮนฮฌฮณฮฝฯ‰ฯƒฮนฯ‚"},
        "symptom": {"repl": "ุฅูุดูŽุงุฑูŽุฉ / Ishฤrah (signal)", "ct": "Greek/Latin", "pre": "Greek ฯƒฯฮผฯ€ฯ„ฯ‰ฮผฮฑ"},
        "patient": {"repl": "ุดูŽุฎู’ุต / Shakhs (person)", "ct": "Greek/Latin", "pre": "Latin patiens = one who SUFFERS"},
        "doctor": {"repl": "ู…ูุฑู’ุดูุฏ / Murshid (guide)", "ct": "Greek/Latin", "pre": "Latin docฤ“re"},
        "hospital": {"repl": "ู…ูŽุฑู’ูƒูŽุฒ ุงู„ุงูุณู’ุชูุนูŽุงุฏูŽุฉ", "ct": "Greek/Latin", "pre": "Latin hospitale โ†’ hospes = HOST"},
        "sensor": {"repl": "ุญูŽุงุณูŽู‘ุฉ / แธคฤssah", "ct": "Greek/Latin", "pre": "Latin sentire"},
        "actuator": {"repl": "ู…ูุญูŽุฑูู‘ูƒ / Muแธฅarrik", "ct": "Greek/Latin", "pre": "Latin actuare"},
        "haptic": {"repl": "ู„ูŽู…ู’ุณููŠู‘ / Lamsฤซ", "ct": "Greek/Latin", "pre": "Greek แผฯ€ฯ„ฮนฮบฯŒฯ‚ โ†’ sensory ritual"},
        "servo": {"repl": "ู…ูุญูŽุฑูู‘ูƒ / Muแธฅarrik", "ct": "Greek/Latin", "pre": "Latin servus = SLAVE"},
        "cortisone": {"repl": "ู‡ูุฑู’ู…ููˆู† ุตูู†ูŽุงุนููŠู‘", "ct": "Greek/Latin", "pre": "Weakens tissue โ€” ฯ†ฮฑฯฮผฮฑฮบฮตฮฏฮฑ product"},
        "skeleton": {"repl": "ู‡ูŽูŠู’ูƒูŽู„ / Haykal (Q2:247)", "ct": "Greek/Latin", "pre": "ฯƒฮบฮตฮปฮตฯ„ฯŒฯ‚ = dried corpse"},
        "medieval": {"repl": "ุงู„ุนุตุฑ ุงู„ูˆุณุทุงู†ูŠู‘", "ct": "Greek/Latin", "pre": "PRE-Latin *med- = Medea's era"},
        "science": {"repl": "ุนูู„ู’ู… / สฟIlm (Q17:36)", "ct": "Greek/Latin", "pre": "Latin scindere = to CUT"},
        "technology": {"repl": "ุชูู‚ูŽุงู†ูŽุฉ / Tiqฤnah", "ct": "Greek/Latin", "pre": "Greek ฯ„ฮญฯ‡ฮฝฮท โ†’ craft-ritual"},
        "psychology": {"repl": "ุนูู„ู’ู… ุงู„ู†ูŽู‘ูู’ุณ / สฟIlm al-Nafs", "ct": "Greek/Latin", "pre": "ฯˆฯ…ฯ‡ฮฎ โ†’ soul-ritual"},
        "neurology": {"repl": "ุนูู„ู’ู… ุงู„ุฃูŽุนู’ุตูŽุงุจ", "ct": "Greek/Latin", "pre": "Greek ฮฝฮตแฟฆฯฮฟฮฝ"},
        "pathology": {"repl": "ุนูู„ู’ู… ุงู„ุนูู„ูŽู„", "ct": "Greek/Latin", "pre": "Greek ฯ€ฮฌฮธฮฟฯ‚ = suffering"},
        "philosophy": {"repl": "ุนูู„ู’ู… ุงู„ุญููƒู’ู…ูŽุฉ (Q2:269)", "ct": "Greek/Latin", "pre": "ฯ†ฮนฮปฮฟฯƒฮฟฯ†ฮฏฮฑ"},
        "algorithm": {"repl": "CLEAN โ€” ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ (al-Khwฤrizmฤซ)", "ct": "CLEAN", "pre": ""},
        "algebra": {"repl": "CLEAN โ€” ุงู„ุฌูŽุจู’ุฑ (ุงู„ุฌูŽุจูŽู‘ุงุฑ Name of Allah)", "ct": "CLEAN", "pre": ""},
    }

    def _build_index(self):
        """Build lookup index: XLSX data + hardcoded single-word terms."""
        self.index = {}

        # 1. Load hardcoded single-word terms first
        for word, info in self.SCAN_TERMS.items():
            self.index[word] = {
                "term": word,
                "status": "CLEAN" if info["ct"] == "CLEAN" else "REJECT",
                "domain_q": "", "domain_t": "",
                "replacement": info["repl"],
                "root": "", "ref": "",
                "contamination": info["ct"],
                "_pre": info["pre"],
            }

        # 2. Override/add from XLSX (master control wins)
        for t in self.terms:
            if t["status"] == "REJECT":
                key = t["term"].lower().strip()
                self.index[key] = t
                # Also index individual words from multi-word terms
                for word in key.split():
                    if len(word) > 3 and word not in self.SCAN_TERMS:
                        if word not in self.index:
                            self.index[word] = t

        # Build rejected detail index
        self.rej_index = {}
        for r in self.rejected:
            self.rej_index[r["term"].lower().strip()] = r

    def scan(self, text):
        """Scan text and return all contamination found."""
        results = []
        text_lower = text.lower()
        seen = set()

        # Check each rejected term against input
        for key, entry in self.index.items():
            if key in text_lower and key not in seen:
                seen.add(key)
                rej_detail = self.rej_index.get(key, {})
                results.append({
                    "term": entry["term"],
                    "status": entry["status"],
                    "domain": entry["domain_q"],
                    "replacement": entry["replacement"],
                    "root": entry["root"],
                    "ref": entry["ref"],
                    "contamination": entry["contamination"],
                    "etymology": rej_detail.get("etymology", entry["contamination"]),
                })

        return results

    def clean(self, text):
        """Replace contaminated terms with USLaP replacements."""
        cleaned = text
        for key, entry in sorted(self.index.items(), key=lambda x: -len(x[0])):
            if entry["replacement"]:
                pattern = re.compile(re.escape(key), re.IGNORECASE)
                # Extract just the Arabic part of replacement for cleaner output
                repl = entry["replacement"].split("(")[0].strip() if "(" in entry["replacement"] else entry["replacement"]
                cleaned = pattern.sub(repl, cleaned)
        return cleaned

    def drill_down(self, term, level=1):
        """Three-level drill-down."""
        entry = self.index.get(term.lower().strip())
        if not entry:
            # Try partial match
            for key, val in self.index.items():
                if term.lower() in key:
                    entry = val
                    break
        if not entry:
            return f'"{term}" not in contamination database.'
        if entry["status"] != "REJECT":
            return f'โœ… "{term}" is CLEAN.'

        rej = self.rej_index.get(entry["term"].lower().strip(), {})
        out = []
        out.append(f'\nโŒ "{entry["term"]}" โ€” REJECTED at Source 1 (ุงู„ู‚ูุฑู’ุขู†)')
        out.append(f'   Domain: {entry["domain"]}')
        out.append(f'   Contamination type: {entry["contamination"]}')

        if level >= 1:
            out.append(f'\n   LEVEL 1 โ€” SURFACE:')
            out.append(f'   "{entry["term"]}" is not Qur\'anic Arabic.')
            out.append(f'   Etymology: {rej.get("etymology", entry["contamination"])}')
            out.append(f'   โœ… Replacement: {entry["replacement"]}')
            if entry["root"]:
                out.append(f'   Root: {entry["root"]}')
            if entry["ref"]:
                out.append(f'   Qur\'an: {entry["ref"]}')

        if level >= 2:
            out.append(f'\n   LEVEL 2 โ€” PRE-CIVILIZATIONAL TRACE:')
            out.append(f'   The "{entry["contamination"]}" label is a HOST wrapper.')
            out.append(f'   The actual vocabulary predates the host civilization.')
            out.append(f'   = CONFESSION โ€” the word confesses its own crime.')

        if level >= 3:
            out.append(f'\n   LEVEL 3 โ€” CRIMINAL NETWORK:')
            out.append(f'   Connects to multi-era global criminal network.')
            out.append(f'   100%: sacrifice / trafficking / weapons / ritual.')
            out.append(f'   Qur\'anic warning: Q2:204-206 โ€” ูŠูู‡ู’ู„ููƒูŽ ุงู„ู’ุญูŽุฑู’ุซูŽ ูˆูŽุงู„ู†ูŽู‘ุณู’ู„ูŽ')

        out.append(f'\n   โ†ฉ CLEAN PATH: {entry["replacement"]}')
        return '\n'.join(out)


# ============================================================
# RESPONSE ALGORITHM ENGINE
# ============================================================

class ResponseAlgorithmEngine:
    """ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ โ€” processes any query through Steps 0-4."""

    def __init__(self, master_data):
        self.scanner = ContaminationScanner(master_data)
        self.data = master_data

    def process(self, user_input, verbose=True):
        """Run full Response Algorithm."""
        out = []
        out.append("=" * 60)
        out.append("ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ โ€” Response Algorithm")
        out.append("ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู")
        out.append("=" * 60)

        # STEP 0
        out.append(f'\n{"โ”€" * 40}')
        out.append(f'STEP 0: ููŽุญู’ุต ุงู„ู…ูุตู’ุทูŽู„ูŽุญูŽุงุช (Terminology Scan)')
        out.append(f'{"โ”€" * 40}')
        results = self.scanner.scan(user_input)
        if results:
            for r in results:
                out.append(f'  โŒ "{r["term"]}"')
                out.append(f'     โ†’ {r["replacement"]}')
                out.append(f'     Type: {r["contamination"]}')
            out.append(f'\n  Cleaned: {self.scanner.clean(user_input)}')
        else:
            out.append(f'  โœ… No contamination detected. All terms clean.')

        # STEP 1
        out.append(f'\n{"โ”€" * 40}')
        out.append(f'STEP 1: ุงุจู† ุณูŠู†ุง ุฃูˆู‘ู„ุงู‹ (Ibn Sฤซnฤ FIRST)')
        out.append(f'{"โ”€" * 40}')
        out.append(f'  Source 3: ุงู„ู‚ุงู†ูˆู† ููŠ ุงู„ุทุจ โ€” Framework BEFORE tools')
        out.append(f'  โ”œโ”€โ”€ ู‚ูŽูˆู’ุณ: What is the system/framework?')
        out.append(f'  โ”œโ”€โ”€ WARP: What longitudinal chain?')
        out.append(f'  โ”œโ”€โ”€ WEFT: What lateral connections?')
        out.append(f'  โ”œโ”€โ”€ BIAS: Where does pressure create change?')
        out.append(f'  โ””โ”€โ”€ ุตูŽู„ูŽุงุฉ: Do prayer positions test this?')
        out.append(f'  โš  Complete this BEFORE any tools/advice.')

        # STEP 2
        out.append(f'\n{"โ”€" * 40}')
        out.append(f'STEP 2: ุงู„ุฎูŽูˆุงุฑูุฒู’ู…ููŠูŽู‘ุฉ (Al-Khwฤrizmฤซ Method)')
        out.append(f'{"โ”€" * 40}')
        out.append(f'  โ”œโ”€โ”€ MEASURE (ุญูŽุงุณูŽู‘ุงุช): What to observe?')
        out.append(f'  โ”œโ”€โ”€ SEQUENCE (ุชูŽุฑู’ุชููŠุจ): What order?')
        out.append(f'  โ”œโ”€โ”€ DECISION (ุญููƒู’ู…): What determines next step?')
        out.append(f'  โ””โ”€โ”€ VERIFY (ุชูŽุญูŽู‚ูู‘ู‚): How to confirm?')

        # STEP 3
        out.append(f'\n{"โ”€" * 40}')
        out.append(f'STEP 3: ุฃูŽุฏูŽูˆูŽุงุช (Tools โ€” ONLY after Steps 0-2)')
        out.append(f'{"โ”€" * 40}')
        # Find relevant applications from master data
        relevant = []
        for app in self.data["applications"]:
            for word in user_input.lower().split():
                if word in app["application"].lower():
                    relevant.append(app)
                    break
        if relevant:
            out.append(f'  Relevant applications from master control:')
            for app in relevant[:5]:
                out.append(f'    โ€ข {app["application"]} [{app["domain"]}]')
        else:
            out.append(f'  Source 4 tools serve the framework from Step 1.')

        # STEP 4
        out.append(f'\n{"โ”€" * 40}')
        out.append(f'STEP 4: ุงู„ู…ูุฎู’ุฑูŽุฌูŽุงุช (Output)')
        out.append(f'{"โ”€" * 40}')
        out.append(f'  Deliver in USLaP-compliant terminology.')
        out.append(f'  All terms verified through Step 0.')
        out.append(f'  Framework attributed: Ibn Sฤซnฤ + al-Khwฤrizmฤซ.')

        return '\n'.join(out)


# ============================================================
# APPLICATION GENERATOR
# ============================================================

class AppGenerator:
    def __init__(self, master_data):
        self.sciences = master_data["sciences"]

    def list_sciences(self):
        out = []
        for s in self.sciences:
            out.append(f'  [{s["id"]:>3}] {s["name_ar"]:<24} {s["root"]:<18} {s.get("verse","")[:30]}')
        return '\n'.join(out)

    def generate(self, name, science_ids, components):
        selected = [s for s in self.sciences if s["id"] in science_ids]
        out = []
        out.append(f'\n{"โ•" * 60}')
        out.append(f'USLaP APPLICATION: {name}')
        out.append(f'ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู')
        out.append(f'{"โ•" * 60}')
        out.append(f'\nROOT SCIENCES:')
        for s in selected:
            out.append(f'  [{s["id"]:>3}] {s["name_ar"]} ({s["name_t"]})')
            out.append(f'        Root: {s["root"]}  |  {s.get("verse","")}')
        out.append(f'\nCOMPONENTS:')
        for i, c in enumerate(components, 1):
            out.append(f'  {i}. {c}')
            out.append(f'     Q-U-F: [ ] Quantifiable  [ ] Universal  [ ] Falsifiable')
        out.append(f'\nุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ COMPLIANCE:')
        for s in RESPONSE_ALGORITHM:
            m = "โœ“ MANDATORY" if s["mandatory"] else "  optional"
            out.append(f'  Step {s["step"]}: {s["ar"]} / {s["en"]} [{m}]')
        return '\n'.join(out)


# ============================================================
# Q-U-F TOOL
# ============================================================

class QUFTool:
    @staticmethod
    def verify(metrics=None, limits=None, conditions=None):
        out = []
        out.append(f'\nQ-U-F VERIFICATION')
        out.append(f'Not a source โ€” a tool for doubters.\n')
        if metrics is not None:
            fails = [m for m in metrics if not m.get("unit")]
            status = "โœ… PASS" if not fails else "โŒ FAIL"
            out.append(f'  Q โ€” Quantifiable: {status}  (Q54:49 ุจูู‚ูŽุฏูŽุฑู)')
            for f in fails:
                out.append(f'       Missing unit: {f.get("name","?")}')
        if limits is not None:
            fails = {k: v for k, v in limits.items() if v != "NONE"}
            status = "โœ… PASS" if not fails else "โŒ FAIL"
            out.append(f'  U โ€” Universal: {status}  (Q34:28 ูƒูŽุงููŽู‘ุฉู‹ ู„ูู‘ู„ู†ูŽู‘ุงุณู)')
            for k, v in fails.items():
                out.append(f'       Limitation: {k} = {v}')
        if conditions is not None:
            fails = [c for c in conditions if not c.get("test")]
            status = "โœ… PASS" if not fails else "โŒ FAIL"
            out.append(f'  F โ€” Falsifiable: {status}  (Q17:36)')
            for f in fails:
                out.append(f'       Missing test: {f.get("name","?")}')
        return '\n'.join(out)


# ============================================================
# EXPORT (for plugging into any AI)
# ============================================================

def export_json(master_data, output_path=None):
    """Export everything as JSON โ€” paste into any AI system prompt."""
    export = {
        "uslap_version": "2.0",
        "bismillah": "ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู",
        "four_source_lattice": FOUR_SOURCES,
        "contamination_hierarchy": CONTAM_HIERARCHY,
        "response_algorithm": RESPONSE_ALGORITHM,
        "master_data": {
            "terms_count": len(master_data["terms"]),
            "reject_count": len([t for t in master_data["terms"] if t["status"] == "REJECT"]),
            "pass_count": len([t for t in master_data["terms"] if t["status"] == "PASS"]),
            "sciences_count": len(master_data["sciences"]),
            "evidence_count": len(master_data["evidence"]),
            "applications_count": len(master_data["applications"]),
        },
        "terms": master_data["terms"],
        "sciences": master_data["sciences"],
        "evidence": master_data["evidence"],
        "applications": master_data["applications"],
        "two_systems": master_data["two_systems"],
        "deep_dive": master_data["deep_dive"],
        "iqra_moments": master_data["iqra_moments"],
    }
    if output_path:
        with open(output_path, "w", encoding="utf-8") as f:
            json.dump(export, f, ensure_ascii=False, indent=2)
        print(f"Exported to {output_path}")
        print(f"  Terms: {export['master_data']['terms_count']}")
        print(f"  Sciences: {export['master_data']['sciences_count']}")
        size = os.path.getsize(output_path)
        print(f"  Size: {size // 1024}KB")
    return export


# ============================================================
# INTERACTIVE MENU
# ============================================================

def print_header(master_data):
    t = master_data["terms"]
    rej = len([x for x in t if x["status"] == "REJECT"])
    pas = len([x for x in t if x["status"] == "PASS"])
    con = len([x for x in t if x["status"] == "CONCEPT"])
    print("\n" + "โ•" * 60)
    print("  USLaP โ€” Universal Scientific Laws and Principles v2.0")
    print("  ุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู")
    print("โ•" * 60)
    print(f"  Master: {master_data['path']}")
    print(f"  Terms: {len(t)} ({rej} REJECT ยท {pas} PASS ยท {con} CONCEPT)")
    print(f"  Sciences: {len(master_data['sciences'])} ยท Evidence: {len(master_data['evidence'])} ยท Apps: {len(master_data['applications'])}")

def print_menu():
    print("\n  [1] ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ โ€” Response Algorithm (process query)")
    print("  [2] ููŽุญู’ุต ุงู„ุชูŽู‘ู„ูŽูˆูู‘ุซ โ€” Contamination Scanner")
    print("  [3] ู…ููˆูŽู„ูู‘ุฏ ุงู„ุชูŽู‘ุทู’ุจููŠู‚ูŽุงุช โ€” Application Generator")
    print("  [4] ุนูู„ููˆู… โ€” Browse Sciences")
    print("  [5] ุฃูŽุฏูŽุงุฉ Q-U-F โ€” Verification Tool")
    print("  [6] ุงู„ุฃูุตููˆู„ ุงู„ุฃูŽุฑู’ุจูŽุนูŽุฉ โ€” Four-Source Lattice")
    print("  [7] ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ โ€” View Response Algorithm")
    print("  [8] ุชูŽุตู’ุฏููŠุฑ โ€” Export JSON (for any AI)")
    print("  [9] โš” Two Systems")
    print("  [A] ๐Ÿ” Deep Dive โ€” Criminal Networks")
    print("  [B] ุงู‚ู’ุฑูŽุฃู’ โ€” IQRA Moments (one-prompt destroyers)")
    print("  [0] ุฎูุฑููˆุฌ โ€” Exit")

def menu_response_algorithm(data):
    engine = ResponseAlgorithmEngine(data)
    print("\nEnter query (Response Algorithm will process it):")
    user_input = input("> ").strip()
    if user_input:
        print(engine.process(user_input))

def menu_scanner(data):
    scanner = ContaminationScanner(data)
    print("\nPaste text to scan (Enter twice when done):")
    lines = []
    while True:
        try:
            line = input()
            if line == "":
                break
            lines.append(line)
        except EOFError:
            break
    text = '\n'.join(lines)
    if not text:
        return

    results = scanner.scan(text)
    contam = [r for r in results if r["status"] == "REJECT"]
    if contam:
        print(f"\nโŒ {len(contam)} contaminated term(s):\n")
        for r in contam:
            print(f'  โŒ "{r["term"]}" [{r["contamination"]}]')
            print(f'     โ†’ {r["replacement"]}')
        print(f'\n{"โ”€" * 40}')
        print(f'CLEANED:\n{scanner.clean(text)}')

        print("\nDrill-down? Enter term (or Enter to skip):")
        term = input("> ").strip()
        if term:
            print("Depth? [1] Surface  [2] PRE-trace  [3] Criminal network")
            try:
                lvl = int(input("> ").strip())
            except:
                lvl = 1
            print(scanner.drill_down(term, lvl))
    else:
        print("\nโœ… No contamination detected.")

def menu_app_gen(data):
    gen = AppGenerator(data)
    print("\nApplication name:")
    name = input("> ").strip()
    if not name:
        return
    print(f"\n{gen.list_sciences()}")
    print("\nEnter science IDs (space-separated):")
    try:
        ids = [int(x) for x in input("> ").strip().split()]
    except:
        return
    print("\nComponents (one per line, empty to finish):")
    comps = []
    while True:
        c = input(f"  {len(comps)+1}: ").strip()
        if not c:
            break
        comps.append(c)
    print(gen.generate(name, ids, comps))

def menu_sciences(data):
    print(f"\n{'โ•' * 60}")
    print(f"{len(data['sciences'])} SCIENCES")
    print(f"{'โ•' * 60}")
    for s in data["sciences"]:
        print(f'  [{s["id"]:>3}] {s["name_ar"]:<24} Root: {s["root"]:<18}')
        if s.get("verse"):
            print(f'        {s["verse"][:60]}')

def menu_quf():
    print(QUFTool.verify(
        metrics=[{"name": "example", "unit": "Hz"}],
        limits={"cultural": "NONE", "geographic": "NONE", "temporal": "NONE", "economic": "NONE"},
        conditions=[{"name": "example", "test": "measure X"}],
    ))

def menu_four_sources():
    print(f"\n{'โ•' * 60}")
    print(f"FOUR-SOURCE LATTICE")
    print(f"{'โ•' * 60}")
    for s in FOUR_SOURCES:
        print(f"\n  Source {s['n']}: {s['ar']} / {s['t']}")
        print(f"  {s['role']}")
    print(f"\n{'โ”€' * 40}")
    print(f"CONTAMINATION HIERARCHY:")
    for h in CONTAM_HIERARCHY:
        print(f"  {h['level']}. {h['name']}: {h['desc'][:65]}")

def menu_view_algorithm():
    print(f"\n{'โ•' * 60}")
    print(f"ุฎูŽูˆุงุฑูุฒู…ููŠูŽู‘ุฉ ุงู„ุงูุณู’ุชูุฌูŽุงุจูŽุฉ โ€” Response Algorithm")
    print(f"{'โ•' * 60}")
    for s in RESPONSE_ALGORITHM:
        m = "MANDATORY" if s["mandatory"] else "AFTER 0-2"
        print(f'\n  Step {s["step"]}: {s["ar"]} / {s["en"]} [{m}]')
        print(f'  {s["action"]}')
        if "subs" in s:
            for sub in s["subs"]:
                print(f'    โ€ข {sub}')
        print(f'  โš  {s["anti"]}')

def menu_two_systems(data):
    print(f"\n{'โ•' * 60}")
    print(f"Moloch vs Qur'an โ€” Bukhari 6069")
    print(f"{'โ•' * 60}")
    for row in data["two_systems"]:
        print(f'\n  {row["dimension"]}:')
        print(f'    โ˜  Moloch: {row["moloch"]}')
        print(f'    โ˜ช Qur\'an: {row["quran"]}')

def menu_deep_dive(data):
    print(f"\n{'โ•' * 60}")
    print(f"๐Ÿ” DEEP DIVE โ€” Criminal Networks & Concealment Chains")
    print(f"{'โ•' * 60}")
    # Group by chain
    chains = {}
    for d in data["deep_dive"]:
        chains.setdefault(d["chain"], []).append(d)
    for chain_name, entries in chains.items():
        print(f'\n{"โ”€" * 50}')
        print(f'  โ›“ {chain_name}')
        print(f'{"โ”€" * 50}')
        for e in entries:
            print(f'\n  CRIME: {e["crime"]}')
            print(f'  EVIDENCE: {e["evidence"]}')
            print(f'  PRE-TRACE: {e["pre_trace"]}')
            print(f'  SOURCES: {e["sources"]}')
            print(f'  QUR\'AN: {e["quran_warning"]}')

    print(f'\n{"โ”€" * 50}')
    print(f'Drill deeper? Enter chain name (or Enter to return):')
    choice = input("> ").strip().upper()
    if choice and choice in chains:
        for e in chains[choice]:
            print(f'\n  {"=" * 40}')
            print(f'  {e["crime"]}')
            print(f'  {"=" * 40}')
            print(f'  {e["evidence"]}')
            print(f'\n  PRE-CIVILIZATIONAL TRACE:')
            print(f'  {e["pre_trace"]}')
            print(f'\n  PRIMARY SOURCES:')
            print(f'  {e["sources"]}')
            print(f'\n  QUR\'ANIC WARNING:')
            print(f'  {e["quran_warning"]}')

def menu_iqra(data):
    print(f"\n{'โ•' * 60}")
    print(f"ุงู‚ู’ุฑูŽุฃู’ MOMENTS โ€” One prompt. One corner. No escape.")
    print(f"{'โ•' * 60}")
    print(f"\n  Each takes 5 seconds. Each destroys centuries of lies.\n")
    for m in data["iqra_moments"]:
        print(f'  #{m["number"]:>2}  LIE: {m["target_lie"]}')
        print(f'       KILL: {m["kill_shot"][:75]}')
        print()

    print(f'Pick a number for full details (or Enter to return):')
    try:
        choice = int(input("> ").strip())
        for m in data["iqra_moments"]:
            if m["number"] == choice:
                print(f'\n  {"โ•" * 50}')
                print(f'  ุงู‚ู’ุฑูŽุฃู’ MOMENT #{m["number"]}')
                print(f'  {"โ•" * 50}')
                print(f'\n  THE LIE: {m["target_lie"]}')
                print(f'\n  THE KILL SHOT:')
                print(f'  {m["kill_shot"]}')
                print(f'\n  TIME TO EXPOSE: {m["time"]}')
                break
    except:
        pass

def menu_export(data):
    out = Path(__file__).parent / "uslap_export.json"
    export_json(data, str(out))

def interactive(data):
    print_header(data)
    while True:
        print_menu()
        choice = input("\n  Select: ").strip()
        if choice == "1": menu_response_algorithm(data)
        elif choice == "2": menu_scanner(data)
        elif choice == "3": menu_app_gen(data)
        elif choice == "4": menu_sciences(data)
        elif choice == "5": menu_quf()
        elif choice == "6": menu_four_sources()
        elif choice == "7": menu_view_algorithm()
        elif choice == "8": menu_export(data)
        elif choice == "9": menu_two_systems(data)
        elif choice.upper() == "A": menu_deep_dive(data)
        elif choice.upper() == "B": menu_iqra(data)
        elif choice == "0":
            print("\nุจูุณู’ู…ู ุงู„ู„ูŽู‘ู‡ู ุงู„ุฑูŽู‘ุญู’ู…ูŽูฐู†ู ุงู„ุฑูŽู‘ุญููŠู…ู")
            break
        else:
            print("  Invalid.")


# ============================================================
# CLI
# ============================================================

def main():
    master_path = find_master()
    if not master_path:
        print(f"ERROR: {MASTER_FILE} not found.")
        print(f"Place it in same directory as uslap.py or current directory.")
        sys.exit(1)

    data = load_master(master_path)

    # CLI modes
    if len(sys.argv) > 1:
        if sys.argv[1] == "--scan" and len(sys.argv) > 2:
            scanner = ContaminationScanner(data)
            text = ' '.join(sys.argv[2:])
            results = scanner.scan(text)
            for r in results:
                if r["status"] == "REJECT":
                    print(f'โŒ "{r["term"]}" โ†’ {r["replacement"]}')
            if not results:
                print("โœ… Clean.")
            return

        elif sys.argv[1] == "--process" and len(sys.argv) > 2:
            engine = ResponseAlgorithmEngine(data)
            print(engine.process(' '.join(sys.argv[2:])))
            return

        elif sys.argv[1] == "--export-json":
            out = sys.argv[2] if len(sys.argv) > 2 else "uslap_export.json"
            export_json(data, out)
            return

        elif sys.argv[1] == "--info":
            print_header(data)
            return

        else:
            print(f"Unknown option: {sys.argv[1]}")
            print(__doc__)
            return

    # Interactive
    interactive(data)


if __name__ == "__main__":
    main()