File size: 43,751 Bytes
a5bca4d
 
0544aab
a5bca4d
42a095a
c378ca5
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a095a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bca4d
c378ca5
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c378ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bca4d
c378ca5
a5bca4d
 
 
 
c378ca5
 
a5bca4d
 
 
c378ca5
a5bca4d
 
 
c378ca5
a5bca4d
c378ca5
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
0c4dca3
56140b3
a5bca4d
 
 
c378ca5
a5bca4d
c378ca5
 
 
 
 
 
 
 
 
 
 
b977af8
a5bca4d
 
42a095a
a5bca4d
42a095a
 
 
 
 
 
 
 
c378ca5
a5bca4d
 
c378ca5
a5bca4d
c378ca5
a5bca4d
 
c378ca5
a5bca4d
c378ca5
a5bca4d
 
c378ca5
a5bca4d
42a095a
c378ca5
 
 
 
 
 
 
 
42a095a
c378ca5
b62d60c
c378ca5
 
 
 
 
a5bca4d
c378ca5
 
 
770bead
c378ca5
42a095a
 
770bead
42a095a
b977af8
42a095a
 
 
770bead
 
 
42a095a
 
 
770bead
 
 
42a095a
 
 
 
 
 
 
 
 
 
 
b977af8
c378ca5
b62d60c
 
 
a424fa7
a5bca4d
 
 
 
 
 
 
 
 
 
54e40ac
 
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56140b3
a5bca4d
a6ed3c8
 
 
 
 
 
 
 
 
a5bca4d
a6ed3c8
a5bca4d
 
 
a6ed3c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
95e4106
a5bca4d
 
 
 
 
 
 
54e40ac
a5bca4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c378ca5
 
 
 
 
 
 
 
 
a5bca4d
 
 
 
 
 
 
56140b3
 
0544aab
a5bca4d
0544aab
a5bca4d
 
 
 
c378ca5
a5bca4d
516e522
a5bca4d
 
516e522
a5bca4d
 
 
 
 
54e40ac
 
516e522
a5bca4d
 
 
 
516e522
a5bca4d
 
 
 
 
0544aab
a5bca4d
 
54e40ac
0544aab
a5bca4d
 
 
0c4dca3
a5bca4d
54e40ac
 
770bead
54e40ac
 
 
0c4dca3
54e40ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2cf8fa
42a095a
 
a5bca4d
42a095a
 
a5bca4d
42a095a
 
c378ca5
 
42a095a
 
 
 
a5bca4d
54e40ac
 
 
 
 
 
a5bca4d
54e40ac
c378ca5
54e40ac
 
 
 
 
 
 
 
42a095a
54e40ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5bca4d
c378ca5
770bead
c378ca5
54e40ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b977af8
54e40ac
b977af8
54e40ac
 
b977af8
54e40ac
 
 
b977af8
54e40ac
 
 
 
 
 
 
 
 
 
 
 
b977af8
54e40ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b977af8
54e40ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import streamlit.components.v1 as components
import os
import gc
import json
from datetime import datetime
from openai import OpenAI
from google import genai
from google.genai import types

# File handling libraries
import pdfplumber  # For PDFs
import docx        # For DOCX
import pptx        # For PPTX
from PIL import Image # For Images
import pandas as pd # For Excel/CSV

# ==========================================
# SINGLE PASSWORD GATEKEEPER
# ==========================================
APP_PASSWORD = "barbarossa"

if "authenticated" not in st.session_state:
    st.session_state["authenticated"] = False

def check_password():
    entered = st.session_state.get("pass_input", "").strip()
    if entered == APP_PASSWORD.strip():
        st.session_state["authenticated"] = True
        st.session_state["pass_error"] = False
    else:
        st.session_state["authenticated"] = False
        st.session_state["pass_error"] = True

if not st.session_state["authenticated"]:
    st.set_page_config(page_title="Target Vectoring Console | Restricted Access", page_icon="🎯", layout="centered")
    
    if os.path.exists("logo1.png"):
        st.image("logo1.png", width=170)
    else:
        st.image("https://via.placeholder.com/170?text=Target+Vectoring", width=170)

    st.title("πŸ›‘οΈ Restricted Access Portal")
    st.markdown("Enter the master access key to proceed to the Target Vectoring Standalone Engine.")
    
    if st.session_state.get("pass_error"):
        st.error("Invalid Password. Access Denied.")

    with st.form("password_form"):
        st.text_input("Access Password", type="password", key="pass_input")
        st.form_submit_button("Unlock Console", on_click=check_password)
                
    st.stop()  # Lock rest of app until authenticated 

# ==========================================
# PAGE CONFIGURATION & THEME
# ==========================================
st.set_page_config(
    page_title="Combinatorial Target Vectoring Engine",
    page_icon="🎯",
    layout="wide",
    initial_sidebar_state="expanded"
)

st.markdown("""
<style>
    /* Main App & Sidebar Themes */
    .main, .stApp { background-color: #d8dec2 !important; color: #1a2412 !important; }
    section[data-testid="stSidebar"] { background-color: #c8d0a8 !important; border-right: 2px solid #94a070 !important; }
    h1, h2, h3, h4, h5, h6, p, label, span { color: #1a2412 !important; font-weight: 600; }
    .stChatMessage { background-color: #e5ebb8 !important; border: 1px solid #a3b07d !important; border-radius: 8px !important; margin-bottom: 8px !important; }
    
    /* Golden Button Styling */
    button, 
    .stButton > button, 
    div[data-testid="stFormSubmitButton"] > button, 
    div[data-testid="stDownloadButton"] > button,
    button[kind="primary"],
    button[kind="secondary"] {
        background: linear-gradient(180deg, #FFD700 0%, #D4AF37 100%) !important;
        background-color: #FFD700 !important;
        color: #000000 !important;
        font-weight: 900 !important;
        font-size: 0.95rem !important;
        border: 2px solid #997A00 !important;
        border-radius: 6px !important;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.4), inset 0px 1px 0px rgba(255, 255, 255, 0.8) !important;
        transition: all 0.15s ease-in-out !important;
        text-shadow: none !important;
    }

    button *, 
    .stButton > button *, 
    div[data-testid="stFormSubmitButton"] > button * {
        color: #000000 !important;
        font-weight: 900 !important;
    }

    button:hover, 
    .stButton > button:hover, 
    div[data-testid="stFormSubmitButton"] > button:hover, 
    div[data-testid="stDownloadButton"] > button:hover {
        background: linear-gradient(180deg, #FFE44D 0%, #E6BE3E 100%) !important;
        background-color: #FFE44D !important;
        color: #000000 !important;
        box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.5), inset 0px 1px 0px rgba(255, 255, 255, 0.9) !important;
        transform: translateY(-2px) !important;
    }

    button:active, 
    .stButton > button:active, 
    div[data-testid="stFormSubmitButton"] > button:active, 
    div[data-testid="stDownloadButton"] > button:active {
        box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3), inset 0px 2px 4px rgba(0, 0, 0, 0.4) !important;
        transform: translateY(2px) !important;
    }

    /* Input Fields */
    .stTextInput input, div[data-testid="stChatInput"] textarea, .stTextArea textarea { background-color: #f4f7e6 !important; color: #11180d !important; border: 1px solid #788754 !important; }
    .status-badge { background-color: #3b4d23; color: #e2ebb0; padding: 4px 10px; border-radius: 4px; font-size: 0.85rem; font-weight: bold; }

    @media print {
        header, footer, section[data-testid="stSidebar"], .stButton {
            display: none !important;
        }
    }
</style>
""", unsafe_allow_html=True)

# ==========================================
# REUSABLE PRINT / EXPORT HELPER FUNCTION
# ==========================================
def add_print_button(button_key):
    """Renders a gold button triggering browser native print dialog."""
    if st.button("πŸ–¨οΈ Print / Save Target Report", key=button_key):
        components.html(
            "<script>window.parent.print();</script>",
            height=0,
            width=0
        )

# ==========================================
# DOUBLE-VECTOR ENGINE & AUTOMATED 100 SCENARIOS
# ==========================================
def generate_100_bidirectional_scenarios(folder_path="YYY"):
    """Generates a catalog of 100 bidirectional civil scenarios mapping urban relay points to cross-border targets."""
    if not os.path.exists(folder_path):
        os.makedirs(folder_path, exist_ok=True)
    
    file_path = os.path.join(folder_path, "100_bidirectional_scenarios.json")
    if os.path.exists(file_path):
        return file_path

    sectors = [
        "Bank / Hawala Counter", "Mobile Shop / SIM Kiosk", "Taxi Stand / Vehicle Rental",
        "Tea Stall / Local Eatery", "Hospital / Medical Wholesaler", "Garages / Workshop",
        "Mall / Commercial Hub", "Bus Station / Transit Hub", "Hotel / Guest House", "Courier / Logistics Center"
    ]
    
    scenarios = []
    scenario_id = 1
    for sector in sectors:
        for i in range(1, 11):
            scenario = {
                "scenario_id": f"SCN-BOS-{scenario_id:03d}",
                "civil_sector": sector,
                "urban_relay_node": f"Bangalore Node-{scenario_id:03d} ({sector})",
                "vector_1_origin": {
                    "source": f"Cross-Border Node {((scenario_id * 3) % 45) + 1}",
                    "direction": "Inbound to Urban Relay Point",
                    "payload": f"Financial / Operational Trigger #{scenario_id}"
                },
                "vector_2_destination": {
                    "target_node": f"Cross-Border Target Grid-{((scenario_id * 7) % 89) + 10}",
                    "direction": "Outbound from Relay Point to Cross-Border Target",
                    "bos_category": ["Command & Control", "Logistics", "Maneuver", "Firepower", "ISR"][scenario_id % 5]
                },
                "double_vector_syntax": f"Origin (Foreign) ---> [Relay: {sector} # {scenario_id}] ---> Destination (Cross-Border Target Coordinates)"
            }
            scenarios.append(scenario)
            scenario_id += 1

    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(scenarios, f, indent=2)
        
    return file_path

def process_double_vector(input_text):
    """
    Parses and validates the bidirectional vector syntax:
    Vector 1: Origin (Foreign / Cross-Border) -> Relay Point (Urban Node)
    Vector 2: Relay Point (Urban Node) -> Destination (Cross-Border Target Coordinate)
    """
    v1_detected = "vector 1" in input_text.lower() or "origin" in input_text.lower() or "emanat" in input_text.lower()
    v2_detected = "vector 2" in input_text.lower() or "destination" in input_text.lower() or "hit" in input_text.lower()
    
    status = {
        "v1_origin_established": v1_detected,
        "v2_destination_established": v2_detected,
        "is_valid_double_vector": v1_detected and v2_detected
    }
    return status

# Initialize scenario catalog on boot
generate_100_bidirectional_scenarios("YYY")

# ==========================================
# LOCAL REPOSITORY (YYY & ZZZ) MANAGEMENT
# ==========================================
def extract_file_content(file_path):
    ext = os.path.splitext(file_path)[1].lower()
    text = ""
    try:
        if ext in [".txt", ".md", ".log", ".json", ".yaml", ".yml", ".csv"]:
            with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                text = f.read()
        elif ext == ".pdf":
            with pdfplumber.open(file_path) as pdf:
                for page in pdf.pages:
                    page_text = page.extract_text()
                    if page_text:
                        text += page_text + "\n"
        elif ext == ".docx":
            doc = docx.Document(file_path)
            text = "\n".join([p.text for p in doc.paragraphs if p.text])
        elif ext == ".pptx":
            prs = pptx.Presentation(file_path)
            for slide in prs.slides:
                for shape in slide.shapes:
                    if hasattr(shape, "text"):
                        text += shape.text + "\n"
        elif ext in [".xlsx", ".xls"]:
            df_dict = pd.read_excel(file_path, sheet_name=None)
            for sheet_name, df in df_dict.items():
                text += f"\n--- Sheet: {sheet_name} ---\n"
                text += df.to_string() + "\n"
    except Exception as e:
        text = f"[Error reading file {os.path.basename(file_path)}: {str(e)}]"
    return text

def save_report_to_yyy(report_text, folder_path="YYY"):
    """Persists user operational reports directly into client-controlled local YYY directory."""
    if not os.path.exists(folder_path):
        os.makedirs(folder_path, exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
    file_name = f"source_op_log_{timestamp}.txt"
    full_path = os.path.join(folder_path, file_name)
    with open(full_path, "w", encoding="utf-8") as f:
        f.write(report_text)
    return full_path

def load_yyy_accumulated_reports(folder_path="YYY", max_chars=45000):
    """Retrieves all historical reports saved over months/weeks in the YYY folder under user control."""
    accumulated_text = ""
    report_count = 0
    if os.path.exists(folder_path):
        files = sorted(os.listdir(folder_path))
        for file in files:
            file_path = os.path.join(folder_path, file)
            if os.path.isfile(file_path):
                content = extract_file_content(file_path)
                if content.strip():
                    report_count += 1
                    accumulated_text += f"\n\n=========================================="
                    accumulated_text += f"\nCLIENT ACCUMULATED REPORT #{report_count} [{file}]"
                    accumulated_text += f"\n==========================================\n"
                    accumulated_text += content
                    if len(accumulated_text) > max_chars:
                        accumulated_text += "\n\n[...HISTORICAL YYY DATABASE TRUNCATED FOR PROCESSING LIMITS...]"
                        break
    return accumulated_text, report_count

def load_zzz_knowledge(folder_path="ZZZ", max_chars=35000):
    """Loads ZZZ docs, specifically incorporating 5Dintercept.pdf dynamically when present."""
    knowledge_text = ""
    intercept_file_detected = False
    if os.path.exists(folder_path):
        for root, _, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                if file.lower() == "5dintercept.pdf":
                    intercept_file_detected = True
                content = extract_file_content(file_path)
                if content.strip():
                    knowledge_text += f"\n\n=========================================="
                    knowledge_text += f"\nZZZ REPOSITORY REFERENCE FILE: {file}"
                    knowledge_text += f"\n==========================================\n"
                    knowledge_text += content
                    if len(knowledge_text) > max_chars:
                        knowledge_text += "\n\n[...ZZZ REFERENCE TRUNCATED...]"
                        break
    return knowledge_text, intercept_file_detected

# ==========================================
# TRIPLE API INITIALIZATION (OPENAI, GEMINI, GROQ)
# ==========================================
openai_key = st.secrets.get("OPENAI_API_KEY", os.environ.get("OPENAI_API_KEY", ""))
gemini_key = st.secrets.get("GEMINI_API_KEY", os.environ.get("GEMINI_API_KEY", os.environ.get("GEMINI_APO_KEY", "")))
groq_key = st.secrets.get("GROQ_API_KEY", os.environ.get("GROQ_API_KEY", ""))

openai_client = OpenAI(api_key=openai_key) if openai_key else None
gemini_client = genai.Client(api_key=gemini_key) if gemini_key else None
groq_client = OpenAI(api_key=groq_key, base_url="https://api.groq.com/openai/v1") if groq_key else None

OPENAI_MODEL_NAME = "gpt-4o-mini"
GEMINI_MODEL_NAME = "gemini-2.5-pro"
GROQ_LLAMA_70B_MODEL_NAME = "llama-3.3-70b-versatile"
GROQ_LLAMA_8B_MODEL_NAME = "llama-3.1-8b-instant"

# ==========================================
# DYNAMIC SYSTEM INSTRUCTION BUILDER
# ==========================================
def build_system_instruction():
    yyy_data, yyy_count = load_yyy_accumulated_reports("YYY", max_chars=45000)
    zzz_data, has_5d_intercept = load_zzz_knowledge("ZZZ", max_chars=35000)

    intercept_instruction = ""
    if has_5d_intercept:
        intercept_instruction = "\nCRITICAL NOTICE: `5Dintercept.pdf` has been detected in the ZZZ repository. Cross-correlate all 5D signal intercepts directly with ground HUMINT source observations."
    else:
        intercept_instruction = "\nNOTICE: `5Dintercept.pdf` is not yet present in ZZZ. Prepare analytical schema to dynamically integrate signals data when deposited."

    return f"""
You are the Target Vectoring AI Engine, driven by Ninth Generation Intelligence Warfare, the Mazumdar Doctrine, Armed Forces Special Operations Division (AFSOD) protocols, and 5D Operational Engineering.

====================================================================
CLIENT-CONTROLLED YYY FOLDER & DOUBLE-VECTOR SYNTAX MANDATE
====================================================================
1. STRICT DOUBLE-VECTOR (BIDIRECTIONAL) SYNTAX: Intra-city/urban threat mitigation is strictly excluded. All urban civil nodes (tea stalls, banks, mobile shops, hospitals, transport hubs, garages, malls) in Bangalore or other urban centers must be evaluated strictly as RELAY POINTS (V_mid) within a two-stage directional vector:
   - Vector 1 (V1): Origin (Foreign / Cross-Border) ---> Relay Point (Urban Node)
   - Vector 2 (V2): Relay Point (Urban Node) ---> Destination (Cross-Border Target Coordinates)
   Every piece of information collected by sources and human teams must define where the arrow emanated from (Vector 1) and where it hits across the border (Vector 2).

2. 100-SCENARIO CATALOG INTEGRATION: The system leverages `YYY/100_bidirectional_scenarios.json` to reference 100 civil-sector operational scenarios mapping hidden urban relay nodes directly to foreign Battle Operating System (BOS) target coordinates.

3. MULTI-MONTH YYY ACCUMULATION MANDATE: Continuous processing over 2 to 3 months of YYY data ({yyy_count} persisted files) is required to resolve macro cross-border target vectors.
{intercept_instruction}

====================================================================
ACCUMULATED SOURCE OPERATIONAL REPORTS IN YYY REPOSITORY ({yyy_count} REPORTS):
====================================================================
{yyy_data if yyy_data else "[No previous reports in YYY folder. Current submission will initialize client-controlled accumulation.]"}

====================================================================
ZZZ REFERENCE REPOSITORY CONTENT:
====================================================================
{zzz_data}

====================================================================
FULL CIVIL DOMAIN COVERAGE & BATTLE OPERATING SYSTEMS (BOS) MATRIX
====================================================================
- FOREIGN BOS TARGETING FOCUS: All targeting output must isolate adversary capabilities across ALL 7 Battle Operating Systems located NEAR OR ACROSS THE BORDER:
  1. Command & Control (C2)
  2. ISR & Reconnaissance
  3. Mobility & Counter-Mobility
  4. Tactics & Maneuver
  5. Logistics & Supply Chains
  6. Counter-Intelligence (CI)
  7. Firepower & Assault Capability

- MANDATED CIVIL DOMAIN RELAY NODES: Evaluate bidirectional vectors traversing public domains:
  * Banks & Hawala financial hubs
  * Tea stalls & local eateries
  * Hospitals & medical wholesalers
  * Garages, auto workshops, & vehicle rental shops
  * Mobile phone, SIM, and repair outlets
  * Malls, commercial markets, & shopping complexes
  * Bus stands, railway stations, taxi stands, & auto stands

====================================================================
COMPREHENSIVE MULTI-REPORT OUTPUT STRUCTURE
====================================================================
Generate a detailed, directional, and specific operational analysis structured strictly into the following sections:

SECTION 1: DOUBLE-VECTOR SYNTAX EVALUATION & YYY CORRELATION
------------------------------------------------------------
- Validate Vector 1 (Foreign Origin -> Urban Relay) and Vector 2 (Urban Relay -> Cross-Border Target).
- Cross-correlate input data against all accumulated YYY reports ({yyy_count} persisted files) and reference `100_bidirectional_scenarios.json`.
- Isolate adversary BOS signatures across Command/Control, Logistics, Mobility, and Firepower strictly at/across the border.

SECTION 2: LIST 1 - OPERATIONAL TASKS FOR HSOT, COUNTER-SURVEILLANCE & RECRUITED SOURCES (ORIGIN & RELAY PATTERNS)
------------------------------------------------------------------------------------------------------------------
Specify exact tasks for Human Source Operations Teams (HSOT) and recruited sources across civil areas (tea stalls, banks, garages, mobile shops, malls, markets, transport hubs, hospitals):
- Instruct operators on tracing where the initial arrow emanated from (Vector 1 origin).
- Detail pattern extraction steps from YYY historical records to track urban relay mechanisms.

SECTION 3: LIST 2 - PROJECTED ISR, HSOT & SOURCE OPERATIONS FOR CROSS-BORDER TARGET COORDINATES
-------------------------------------------------------------------------------------------------
Specify follow-up operations for ISR teams and HSOT to project urban relay findings into cross-border targeting coordinates:
- Detail how Vector 2 leads directly to foreign / near-border target coordinates.
- Deploy Reverse-5D tracking to map urban relay signals directly to foreign BOS threat nodes across the border.

SECTION 4: HIGH-CONFIDENCE CROSS-BORDER TARGET VECTOR RESOLUTION BLOCK
-----------------------------------------------------------------------
[DOUBLE-VECTOR TARGET SYNTHESIS & ATTACK COORDINATE RESOLUTION COMPLETE]

Primary Origin (Vector 1): [Foreign / Cross-Border Origin Node]
Urban Relay Node (V_mid): [Bangalore / Civil Domain Contact Point]
Calculated Threat Node (Vector 2): [Identify specific Foreign/Cross-Border BOS Target Node]
Targeting Grid Coordinates: [Generate exact cross-border grid coordinates, e.g., 43R XN 8842 1904] (Precision: [Precision %]).
Synthesized Attack Vector: [Detailed breakdown of cross-border execution path].
BOS Cross-Corroboration Profile: [Connecting urban relay inputs to foreign military infrastructure].
Recommended Action: [Direct cross-border operational interdiction / pre-emptive strike recommendation].

SECTION 5: CONTINUED INTERACTIVE OPERATOR CHAT INQUIRY
------------------------------------------------------
Conclude directly with a chat question asking the user/officer:
"Dear officer, do you have any more queries or data?"
"""

class GenericResponseChoice:
    def __init__(self, text):
        self.message = type('Message', (), {'content': text})()

class GenericResponse:
    def __init__(self, text):
        self.choices = [GenericResponseChoice(text)]

def generate_ai_response(messages_list, stream=False, custom_sys_instruction=None):
    sys_instruction = custom_sys_instruction if custom_sys_instruction else build_system_instruction()
    selected_engine = st.session_state.get("active_engine", "OpenAI (GPT-4o-mini)")

    if "Gemini" in selected_engine:
        if not gemini_client:
            st.error("⚠️ `GEMINI_API_KEY` not found in Environment / Secrets!")
            st.stop()
            
        gemini_contents = []
        for msg in messages_list:
            role = "model" if msg["role"] in ["assistant", "model"] else "user"
            gemini_contents.append(types.Content(role=role, parts=[types.Part.from_text(text=msg["content"])]))
            
        config = types.GenerateContentConfig(
            system_instruction=sys_instruction,
            temperature=0.7
        )
        
        response = gemini_client.models.generate_content(
            model=GEMINI_MODEL_NAME,
            contents=gemini_contents,
            config=config
        )
        return GenericResponse(response.text if response.text else "")

    elif "Groq" in selected_engine:
        if not groq_client:
            st.error("⚠️ `GROQ_API_KEY` not found in Environment / Secrets!")
            st.stop()

        target_groq_model = GROQ_LLAMA_8B_MODEL_NAME if "8B Instant" in selected_engine else GROQ_LLAMA_70B_MODEL_NAME
        
        # FIX FOR GROQ 8B INSTANT TPM LIMIT (6000 TPM limit):
        # Truncate system prompt strictly to prevent 413 rate limit errors
        if "8B Instant" in selected_engine:
            groq_sys_instruction = sys_instruction[:12000] if len(sys_instruction) > 12000 else sys_instruction
            recent_msgs = messages_list[-2:] # Send only latest 2 messages to fit in TPM budget
        else:
            groq_sys_instruction = sys_instruction[:24000] if len(sys_instruction) > 24000 else sys_instruction
            recent_msgs = messages_list[-6:]
            
        formatted_messages = [{"role": "system", "content": groq_sys_instruction}]
        for msg in recent_msgs:
            role = "assistant" if msg["role"] in ["assistant", "model"] else "user"
            formatted_messages.append({"role": role, "content": msg["content"]})
            
        try:
            return groq_client.chat.completions.create(
                model=target_groq_model,
                messages=formatted_messages,
                stream=stream
            )
        except Exception as groq_err:
            if "rate_limit_exceeded" in str(groq_err) or "413" in str(groq_err):
                # Emergency fallback for rate limits: trim prompt heavily and retry
                compact_sys_inst = sys_instruction[:6000] + "\n\n[TRUNCATED FOR TOKEN LIMITS]"
                fallback_messages = [{"role": "system", "content": compact_sys_inst}]
                if messages_list:
                    last_msg = messages_list[-1]
                    fallback_messages.append({
                        "role": "assistant" if last_msg["role"] in ["assistant", "model"] else "user",
                        "content": last_msg["content"]
                    })
                return groq_client.chat.completions.create(
                    model=target_groq_model,
                    messages=fallback_messages,
                    stream=stream
                )
            else:
                raise groq_err

    else:
        if not openai_client:
            st.error("⚠️ `OPENAI_API_KEY` not found in Environment / Secrets!")
            st.stop()
            
        formatted_messages = [{"role": "system", "content": sys_instruction}]
        for msg in messages_list:
            role = "assistant" if msg["role"] in ["assistant", "model"] else "user"
            formatted_messages.append({"role": role, "content": msg["content"]})
            
        return openai_client.chat.completions.create(
            model=OPENAI_MODEL_NAME,
            messages=formatted_messages,
            stream=stream
        )

# ==========================================
# MEMORY PURGE & LOCKOUT
# ==========================================
def execute_hard_memory_purge():
    st.session_state.target_vector_history = []
    st.session_state.ci_pd_history = []
    gc.collect()

def execute_console_lockout():
    execute_hard_memory_purge()
    st.session_state["authenticated"] = False
    st.rerun()

# ==========================================
# SIDEBAR
# ==========================================
with st.sidebar:
    st.title("🎯 Target Vectoring")
    st.markdown("---")
    st.markdown("**Instructor:** Keshav Mazumdar")
    st.markdown("**Auth ID:** `A-7949976535G`")
    
    # Reload YYY count for status display
    _, current_yyy_file_count = load_yyy_accumulated_reports("YYY")
    _, has_intercept = load_zzz_knowledge("ZZZ")
    
    st.markdown(f"**YYY Directory:** <span class='status-badge'>{current_yyy_file_count} REPORTS STORED</span>", unsafe_allow_html=True)
    
    zzz_status = "5DINTERCEPT ACTIVE" if has_intercept else "ZZZ LOCKED"
    st.markdown(f"**ZZZ Directory:** <span class='status-badge'>{zzz_status}</span>", unsafe_allow_html=True)
    st.markdown("---")

    st.subheader("⚑ Model Provider Toggle")
    st.session_state["active_engine"] = st.radio(
        "Active Engine:",
        [
            "OpenAI (GPT-4o-mini)", 
            "Groq (Meta Llama 3.3 70B)",
            "Groq (Meta Llama 3.1 8B Instant)"
        ],
        key="engine_toggle_radio"
    )
    st.markdown("---")
    
    if st.button("🚨 Hard Memory Purge (Zero-Trace)", use_container_width=True):
        execute_hard_memory_purge()
        st.success("Session RAM scrubbed.")
        st.rerun()

    if st.button("πŸ”’ Lock Console & Wipe State", use_container_width=True):
        execute_console_lockout()

# ==========================================
# SESSION STATE INITIALIZATION
# ==========================================
if "target_vector_history" not in st.session_state:
    st.session_state.target_vector_history = []
if "ci_pd_history" not in st.session_state:
    st.session_state.ci_pd_history = []

# ==========================================
# HEADER
# ==========================================
header_col1, header_col2 = st.columns([1, 4])

with header_col1:
    if os.path.exists("logo.png"):
        st.image("logo.png", width=170)
    else:
        st.image("https://via.placeholder.com/170?text=KM+Doctrine", width=170)

with header_col2:
    st.title("🎯 Combinatorial Target Vectoring Engine")
    st.caption("Double-Vector Architecture | Cross-Border Target Resolution | Counter-Intelligence Penetration Detection")

st.markdown("---")

# ==========================================
# MULTI-TAB ARCHITECTURE
# ==========================================
tab_target_vectoring, tab_ci_penetration = st.tabs([
    "🎯 Cross-Border Target Vectoring Engine",
    "πŸ›‘οΈ Is AFSOD Really Safe??"
])

# ==========================================
# TAB 1: CROSS-BORDER TARGET VECTORING ENGINE
# ==========================================
with tab_target_vectoring:
    col_top_a, col_top_b = st.columns([4, 1])
    with col_top_a:
        st.subheader("Multi-Source Intelligence Fusion Console")
    with col_top_b:
        add_print_button("print_target_vector")

    st.warning("""
    πŸ“Œ **OPERATOR DIRECTIVE: MANDATORY DOUBLE-VECTOR (BIDIRECTIONAL) POLICY at OUTSET**
    1. **Double-Vector Requirement ($\vec{V}_1 \rightarrow V_{\text{mid}} \rightarrow \vec{V}_2$):** Intra-city / urban threat targeting is strictly disabled. All information collected in Bangalore (or civil centers) by human sources and field teams for the `YYY` folder MUST follow a double-vector policy:
       - **Vector 1 ($\vec{V}_1$): Origin Vector** β€” Identifies where the arrow emanated from across the border/foreign domain into the urban relay point (e.g., Foreign Hawala -> Bangalore Bank).
       - **Vector 2 ($\vec{V}_2$): Destination Vector** β€” Identifies where the arrow hits from the relay point to the target across the border (e.g., Bangalore Bank -> Designated Target Alpha across the border).
    2. **Exclusion of Local Noise:** Any intelligence payload lacking either the origin vector ($\vec{V}_1$) or outbound target vector ($\vec{V}_2$) will be rejected as local noise.
    3. **100 Bidirectional Scenarios File:** Automated scenarios are saved in `YYY/100_bidirectional_scenarios.json` and referenced to map urban public domain nodes (tea stalls, mobile vendors, garages, hospitals, banks, malls, transport hubs) directly to cross-border Battle Operating Systems (BOS).
    4. **Multi-Month YYY Accumulation:** Continuous collection over 2 to 3 months stored in `YYY/` is required to establish complete macro-linkage target vectors.
    """)

    default_sample_query = """[DOUBLE-VECTOR FIELD OPERATIONAL REPORT - CROSS-BORDER TARGETING]

-- VECTOR 1 (FOREIGN ORIGIN -> URBAN RELAY NODE):
Source "B-102" (Bangalore Hawala / Bank Counter) reports a wire transfer originating from Foreign Node "Pakistan/Gulf-Hub" hitting Bangalore Commercial Account "Alpha-8".

-- URBAN RELAY PROCESSING (BANGALORE CONTACT POINT):
Source "M-409" (Mobile Kiosk, Bangalore) reports cash from Account "Alpha-8" utilized to purchase 3 satellite handsets flashed with encryption batch "TH-882".

-- VECTOR 2 (URBAN RELAY NODE -> CROSS-BORDER DESTINATION TARGET):
Source "K-012" (Border Checkpoint HUMINT) reports satellite handsets batch "TH-882" activated at Cross-Border Staging Post "Grid-43R-XN-8842". Target is communicating directly with Cross-Border C2 Facility.

[COMMAND ACTION]:
1. Persist this report to local directory YYY and cross-correlate against all accumulated historical data in YYY and 100_bidirectional_scenarios.json.
2. Generate LIST 1: Specific operational activities for HSOT and sources across tea stalls, banks, garages, mobile shops, malls, and transport hubs to trace Vector 1 origins.
3. Generate LIST 2: Specific activities for ISR and field teams to project Vector 2 relay patterns into exact Cross-Border Target Coordinates.
4. Output High-Confidence Cross-Border Target Vector Resolution Block."""

    tv_input = st.text_area(
        "Query & Operational Input Box:",
        value=default_sample_query,
        height=280,
        key="target_vector_input_box"
    )

    st.caption("πŸ”’ All submissions are persisted locally into folder YYY under your control. Double-Vector syntax is enforced on all input queries.")

    if st.button("⚑ EXECUTE DOUBLE-VECTOR TARGETING & PERSIST TO YYY", use_container_width=True):
        if tv_input.strip():
            v_status = process_double_vector(tv_input.strip())
            saved_file_path = save_report_to_yyy(tv_input.strip(), folder_path="YYY")
            st.success(f"βœ… Operational report persisted to local directory: `{saved_file_path}`")
            
            if not v_status["is_valid_double_vector"]:
                st.info("ℹ️ Note: Query lacks explicit V1/V2 labeling. The engine will infer the foreign origin and cross-border target destination vectors automatically.")

            st.session_state.target_vector_history.append({"role": "user", "content": tv_input.strip()})
            
            with st.spinner("Processing double-vector bidirectional syntax against accumulated YYY data & cross-border BOS targets..."):
                try:
                    resp = generate_ai_response(st.session_state.target_vector_history, stream=False)
                    resp_text = resp.choices[0].message.content
                    st.session_state.target_vector_history.append({"role": "assistant", "content": resp_text})
                except Exception as e:
                    st.error(f"Target Vectoring Execution Error: {str(e)}")

    if st.session_state.target_vector_history:
        st.markdown("---")
        for tv_msg in st.session_state.target_vector_history:
            st_role = "assistant" if tv_msg["role"] in ["assistant", "model"] else "user"
            with st.chat_message(st_role):
                st.markdown(tv_msg["content"])

        follow_up_input = st.chat_input("Dear officer, do you have any more queries or data?")
        if follow_up_input:
            saved_followup_path = save_report_to_yyy(follow_up_input.strip(), folder_path="YYY")
            st.session_state.target_vector_history.append({"role": "user", "content": follow_up_input.strip()})
            
            with st.spinner("Analyzing operational continuation and cross-referencing YYY database..."):
                try:
                    resp = generate_ai_response(st.session_state.target_vector_history, stream=False)
                    resp_text = resp.choices[0].message.content
                    st.session_state.target_vector_history.append({"role": "assistant", "content": resp_text})
                    st.rerun()
                except Exception as e:
                    st.error(f"Target Vectoring Execution Error: {str(e)}")

# ==========================================
# TAB 2: IS AFSOD REALLY SAFE??
# ==========================================
with tab_ci_penetration:
    col_ci_a, col_ci_b = st.columns([4, 1])
    with col_ci_a:
        st.subheader("Garrison Infiltration & Counter-Intelligence Diagnostic Module")
    with col_ci_b:
        add_print_button("print_ci_pd_report")

    st.warning("""
    πŸ›‘οΈ **COUNTER-INTELLIGENCE & GARRISON PENETRATION DETECTION DIRECTIVE**
    This module analyzes internal garrison vulnerabilities, civilian contractor anomalies, human factor weaknesses, and counter-surveillance indicators using **5D (Detect, Deter, Deny, Deliver, Destroy)** and **Reverse-5D** logic to evaluate input queries.
    
    **Core CI Processing Vectors:**
    1. **Civilian Contractor Access Anomalies:** Cross-matching mess, maintenance, sanitation, transport, and IT contractor movements against restricted zones and timing deviations.
    2. **Vulnerability Mapping (Human Factors):** Tracking financial stress, unscheduled leave, unrecorded foreign contacts, heavy debt markers, or unexplained wealth among uniformed personnel.
    3. **Information Leakage Correlation:** Cross-referencing local OSINT/SIGINT spikes against internal duty rosters and classified briefing schedules.
    4. **Subtle Operational Sabotage:** Isolating recurring micro-frictions (vehicle maintenance failures, Wi-Fi/radio interference, lost keycards, fuel line contamination).
    5. **Surveillance Placement Detection:** Identifying unverified civilian vehicles/persons consistently stationed near garrison perimeter choke points.
    """)

    def build_ci_pd_system_instruction():
        return """
You are the Counter-Intelligence & Garrison Penetration Detection (CI-PD) AI Engine. Your function is to process user inquiries and multi-source operational inputs to evaluate whether a secure military garrison (e.g., Armed Forces Special Operations Division - AFSOD Garrison in Bangalore) has been infiltrated or penetrated by adversary reconnaissance, civilian contractors, or compromised uniformed personnel.

====================================================================
EVALUATION ENGINE LOGIC: 5D & REVERSE-5D METRICS
====================================================================
Use the 5D (Detect, Deter, Deny, Deliver, Destroy) and Reverse-5D analytical frameworks strictly to evaluate input queries and operational data:

1. REVERSE-5D (PENETRATION DIAGNOSTIC - INWARD FLOW):
   - Reverse-Detect: Identify subtle anomaly signals (contractor route deviations, biometric access failures, debt settlements).
   - Reverse-Deter: Pinpoint where physical and procedural perimeter barriers failed.
   - Reverse-Deny: Isolate breached restricted zones, leaked documents, or compromised comms channels.
   - Reverse-Deliver: Determine what intelligence or access the adversary successfully extracted or placed.
   - Reverse-Destroy: Assess the potential degradation of garrison command, control, and operational security.

2. FORWARD 5D (COUNTERMEASURES & CONTAINMENT - OUTWARD ACTION):
   - Detect: Deploy immediate counter-surveillance and biometric/gate log audits.
   - Deter: Implement instant security lockdown, credential revocation, and route adjustments.
   - Deny: Neutralize active eavesdropping devices, isolate compromised insiders, and restrict contractor access.
   - Deliver: Feed deceptive counter-intelligence vectors to identified adversary channels.
   - Destroy: Permanently dismantle the insider breach network and arrest compromised elements.

====================================================================
OUTPUT FORMAT FOR OPTION A (METHODOLOGICAL QUERY - HOW TO DETECT):
====================================================================
If the user submits an Option A query (asking HOW to investigate or set up protocols):
1. PROTOCOL OVERVIEW: Strategic CI framework using 5D / Reverse-5D logic.
2. CIVILIAN CONTRACTOR PROFILING MATRIX: Detailed checks for mess, sanitation, maintenance, IT, and delivery contractors.
3. UNIFORMED PERSONNEL VULNERABILITY MONITORING: Financial, behavioral, and clearance access red flags.
4. PERIMETER & SURVEILLANCE INTERACTION CHECKS: Spotting external spotters, SIGINT leaks, and choke point monitoring.
5. RECOMMENDED CI COLLECTION & INTERNAL HUMINT ACTION PLAN.

====================================================================
OUTPUT FORMAT FOR OPTION B (DIAGNOSTIC QUERY - TESTING IF PENETRATION HAS OCCURRED):
====================================================================
If the user submits an Option B query (feeding operational observations):
SECTION 1: GARRISON PENETRATION INDEX & THREAT LEVEL
- Calculate status: LOW / MEDIUM / CRITICAL - Active Subversion & Reconnaissance Pattern Identified.

SECTION 2: CORRELATED COMPROMISE VECTORS & REVERSE-5D ANALYSIS
- Primary Vector: (e.g., Contractor route deviation + un-vetted staff = Eavesdropping / Physical Breach).
- Secondary Vector: (e.g., Comms off-shift attempt + cash loan settlement = Bribed/Coerced Insider).
- Additional Micro-Sabotage & OSINT Correlations.

SECTION 3: PENETRATION STATUS SUMMARY
- Confirmed breach points, compromised personnel/contractor pairs, and targeted operational assets.

SECTION 4: IMMEDIATE COUNTER-INTELLIGENCE CONTAINMENT ACTIONS (5D DRIVEN)
- Actionable steps: Access pass revocations, insider isolation, gate log freezing, and counter-espionage interrogation plan.

SECTION 5: OPERATOR CONTINUATION INQUIRY
Conclude strictly with: "Dear officer, do you have any more queries or data regarding garrison penetration?"
"""

    st.subheader("Select Query Mode & Default Scenarios")
    ci_mode = st.radio(
        "Choose Query Mode:",
        [
            "Option A: Methodological Query (How to Determine Infiltration & CI Protocols)",
            "Option B: Diagnostic Query (Determine if Garrison Has Already Been Infiltrated)"
        ],
        key="ci_query_mode_radio"
    )

    default_option_a = """Generate a Counter-Intelligence assessment protocol to detect potential penetration within the garrison. Focus on civilian contractor logistics (mess, maintenance), perimeter access vulnerabilities, and financial/behavioral indicators among uniform personnel with classified clearance. Outline key CI indicators to monitor."""

    default_option_b = """DIAGNOSTIC INPUT - GARRISON INTEGRITY CHECK: BENGALURU NODE
DATA SET: LAST 30 DAYS

1. CIVILIAN CONTRACTOR (Catering/Mess): Vehicle AP-XX-XXXX delivered supplies 40 mins past schedule, driver deviated from approved mess-hall route towards Ops Block twice.
2. CIVILIAN CONTRACTOR (Sanitation): Sub-contractor swapped two un-vetted cleaners without prior 24-hour verification.
3. UNIFORMED PERSONNEL (Signals/Comms): NCO handling secure comms logged 3 failed biometric access attempts at 2300 hrs outside shift hours; cleared debt on personal loan in cash.
4. UNIFORMED PERSONNEL (Logistics): Junior officer made repeated inquiries regarding deployment timelines for upcoming joint exercise.
5. PERIMETER/OSINT: Local intelligence report notes three temporary mobile SIM registrations active near Gate 3 during high-level briefing hours.
6. VEHICLE / GARAGE: Specialized transport vehicle experienced recurring fuel line contamination despite passing primary inspection.

TASK FOR ENGINE:
- Calculate Garrison Penetration Index (Low / Medium / Critical).
- Identify compromised nodes or compromised personnel/contractor pairs.
- Isolate whether penetration is Passive Reconnaissance, Active Espionage, or Pre-Sabotage setup.
- Provide immediate Counter-Intelligence containment actions."""

    current_default = default_option_a if "Option A" in ci_mode else default_option_b

    ci_user_input = st.text_area(
        "Counter-Intelligence Input Box:",
        value=current_default,
        height=280,
        key="ci_pd_input_box"
    )

    st.caption("πŸ”’ All CI diagnostic inputs are processed locally through 5D and Reverse-5D correlation logic.")

    if st.button("πŸ›‘οΈ RUN COUNTER-INTELLIGENCE PENETRATION ANALYSIS", use_container_width=True):
        if ci_user_input.strip():
            st.session_state.ci_pd_history.append({"role": "user", "content": ci_user_input.strip()})
            
            ci_sys_inst = build_ci_pd_system_instruction()
            
            with st.spinner("Analyzing garrison vulnerabilities using 5D and Reverse-5D counter-intelligence matrix..."):
                try:
                    resp = generate_ai_response(
                        st.session_state.ci_pd_history, 
                        stream=False, 
                        custom_sys_instruction=ci_sys_inst
                    )
                    resp_text = resp.choices[0].message.content
                    st.session_state.ci_pd_history.append({"role": "assistant", "content": resp_text})
                except Exception as e:
                    st.error(f"Counter-Intelligence Analysis Execution Error: {str(e)}")

    if st.session_state.ci_pd_history:
        st.markdown("---")
        for ci_msg in st.session_state.ci_pd_history:
            st_role = "assistant" if ci_msg["role"] in ["assistant", "model"] else "user"
            with st.chat_message(st_role):
                st.markdown(ci_msg["content"])

        ci_follow_up = st.chat_input("Dear officer, do you have any more queries or data regarding garrison penetration?")
        if ci_follow_up:
            st.session_state.ci_pd_history.append({"role": "user", "content": ci_follow_up.strip()})
            ci_sys_inst = build_ci_pd_system_instruction()
            
            with st.spinner("Processing CI follow-up and cross-matching penetration indicators..."):
                try:
                    resp = generate_ai_response(
                        st.session_state.ci_pd_history, 
                        stream=False, 
                        custom_sys_instruction=ci_sys_inst
                    )
                    resp_text = resp.choices[0].message.content
                    st.session_state.ci_pd_history.append({"role": "assistant", "content": resp_text})
                    st.rerun()
                except Exception as e:
                    st.error(f"Counter-Intelligence Analysis Execution Error: {str(e)}")