File size: 46,049 Bytes
b16a18b
4570918
b16a18b
4b9c1ef
e8e1464
fe2016d
7d00e9d
 
b16a18b
 
 
 
 
 
 
 
 
 
 
fc015d8
b16a18b
 
 
 
192c9b0
 
 
 
 
 
 
 
 
b16a18b
ad44bc9
7d81c3b
c5b8942
 
 
 
 
 
 
ad44bc9
b16a18b
c5b8942
 
 
b16a18b
192c9b0
 
 
 
fe2016d
b02a84b
b16a18b
 
 
 
 
 
 
 
 
79a1637
b16a18b
 
01a55ab
b16a18b
 
 
 
01a55ab
4b9c1ef
01a55ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8e1464
b16a18b
4570918
 
 
 
 
 
 
b16a18b
 
08c8d03
4570918
 
 
 
 
 
 
 
 
 
 
 
b16a18b
4b9c1ef
b16a18b
 
 
 
 
7d9772b
 
b16a18b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b9c1ef
 
b16a18b
 
 
 
 
 
 
 
 
 
 
5dab71d
 
4b9c1ef
5dab71d
b16a18b
 
 
96763bf
 
4b9c1ef
96763bf
 
08c8d03
b16a18b
7d00e9d
 
08c8d03
b16a18b
7d00e9d
 
08c8d03
b16a18b
7d00e9d
1291007
4b9c1ef
07fba62
b16a18b
 
500fc59
b16a18b
 
c31865f
b16a18b
07fba62
500fc59
07fba62
500fc59
 
 
 
 
 
 
 
 
 
 
07fba62
 
 
 
 
 
b16a18b
8f31d18
b16a18b
8f31d18
 
 
 
4b9c1ef
 
 
 
 
 
aa2a750
b16a18b
08776e1
b16a18b
08776e1
500fc59
08776e1
 
 
 
 
b16a18b
 
7d00e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f31d18
08c8d03
8f31d18
7d00e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe2016d
7d00e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08c8d03
 
 
 
 
4b9c1ef
08c8d03
4b9c1ef
 
 
 
 
08c8d03
 
 
 
 
 
 
 
 
7d00e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08c8d03
5827d4e
 
 
 
 
 
 
 
 
 
e8e1464
5827d4e
 
 
 
 
 
 
b16a18b
5827d4e
 
 
 
 
08c8d03
b16a18b
 
 
 
ad44bc9
b16a18b
 
 
96763bf
500fc59
b16a18b
7d00e9d
 
 
08c8d03
 
 
 
 
4b9c1ef
08c8d03
7d00e9d
 
 
b16a18b
 
 
 
500fc59
 
b16a18b
 
 
 
 
 
 
 
 
 
 
97d825b
5827d4e
 
b16a18b
 
5827d4e
 
b16a18b
 
 
 
 
 
500fc59
b16a18b
 
08776e1
 
b16a18b
08776e1
 
 
e8e1464
 
 
08776e1
 
 
 
 
aa2a750
b16a18b
1291007
b16a18b
 
 
 
567cf67
 
b16a18b
 
 
 
ad44bc9
500fc59
b16a18b
 
 
 
 
 
e8e1464
b16a18b
e8e1464
b16a18b
aa2a750
b16a18b
 
 
 
d6bf78e
b16a18b
 
4570918
 
 
500fc59
4570918
 
 
b16a18b
fe2016d
b16a18b
 
 
d6bf78e
cae75b0
 
 
 
 
d6bf78e
cae75b0
d6bf78e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16a18b
e8e1464
b16a18b
 
e8e1464
 
 
500fc59
e8e1464
 
 
500fc59
e8e1464
500fc59
e8e1464
500fc59
e8e1464
500fc59
e8e1464
500fc59
e8e1464
500fc59
e8e1464
 
500fc59
e8e1464
 
 
 
 
 
 
 
500fc59
e8e1464
 
 
 
 
500fc59
e8e1464
500fc59
 
 
 
e8e1464
500fc59
e8e1464
500fc59
 
 
 
 
e8e1464
500fc59
e8e1464
 
500fc59
e8e1464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4570918
 
 
 
 
 
b16a18b
08776e1
 
 
 
 
 
567cf67
08776e1
 
 
 
8f31d18
08776e1
 
500fc59
08776e1
 
e8e1464
08776e1
 
b16a18b
08776e1
 
 
 
b16a18b
 
84a0974
b16a18b
e8e1464
b16a18b
e8e1464
4570918
 
 
 
 
 
b16a18b
08776e1
 
 
 
 
 
567cf67
08776e1
 
 
 
b16a18b
08776e1
 
 
 
 
 
07fba62
4b9c1ef
07fba62
08776e1
4b9c1ef
08776e1
 
 
 
 
 
 
500fc59
4b9c1ef
08776e1
4b9c1ef
 
08776e1
 
 
b16a18b
08776e1
 
 
 
b16a18b
aa2a750
08c8d03
4570918
e8e1464
4570918
e8e1464
4570918
 
 
 
 
 
 
 
500fc59
 
 
 
4570918
 
 
 
 
dec730f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4570918
 
07fba62
4570918
 
 
dec730f
 
 
4b9c1ef
dec730f
 
 
 
 
 
 
 
 
 
 
07fba62
dec730f
4b9c1ef
 
dec730f
500fc59
4b9c1ef
500fc59
dec730f
 
 
4b9c1ef
dec730f
 
07fba62
dec730f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b9c1ef
dec730f
 
 
 
 
 
 
 
07fba62
dec730f
4b9c1ef
dec730f
 
 
 
 
 
 
 
 
 
 
 
 
 
4570918
 
07fba62
4570918
 
dec730f
 
 
 
 
 
 
 
 
4b9c1ef
dec730f
 
 
 
 
 
 
 
 
07fba62
dec730f
 
 
07fba62
dec730f
4b9c1ef
 
dec730f
4b9c1ef
07fba62
4b9c1ef
dec730f
 
 
4b9c1ef
dec730f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b9c1ef
dec730f
 
 
 
 
 
 
 
07fba62
dec730f
4b9c1ef
dec730f
 
 
 
 
 
 
 
4570918
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
import streamlit as st
import streamlit.components.v1 as components
import os
import gc
import re
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="VKN Command | Restricted Access", page_icon="πŸ”’", layout="centered")
    
    # --- LOGIN PAGE LOGO DISPLAY (logo1.png) ---
    if os.path.exists("logo1.png"):
        st.image("logo1.png", width=170)
    else:
        st.image("https://via.placeholder.com/170?text=KM+Doctrine", width=170)

    st.title("πŸ›‘οΈ Restricted Access Portal")
    st.markdown("Enter the master access key to proceed to the VKN Command Console.")
    
    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="Mazumdar Assistant | Dynamic Intelligence 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; }

    /* Hide Print Button During Actual Printing */
    @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 Tab Report", key=button_key):
        components.html(
            "<script>window.parent.print();</script>",
            height=0,
            width=0
        )

# ==========================================
# MULTI-EXTENSION ZZZ FOLDER LOADER (OPTIMIZED TO PREVENT ERROR 413)
# ==========================================
def extract_file_content(file_path):
    """Extracts text content across PDF, DOCX, PPTX, XLSX, CSV, TXT, MD, and LOG formats."""
    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 load_zzz_knowledge(folder_path="ZZZ", max_chars=32000):
    """Scans ZZZ folder and caps output to 32k chars to prevent HTTP 413 Payload Too Large on Groq."""
    knowledge_text = ""
    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)
                content = extract_file_content(file_path)
                if content.strip():
                    knowledge_text += f"\n\n=========================================="
                    knowledge_text += f"\nDOCUMENT SOURCE: {file}"
                    knowledge_text += f"\n==========================================\n"
                    knowledge_text += content
                    
                    if len(knowledge_text) > max_chars:
                        knowledge_text = knowledge_text[:max_chars] + "\n\n[...ZZZ REPOSITORY TRUNCATED FOR TOKEN/PAYLOAD SAFETY...]"
                        break
    return knowledge_text

# ==========================================
# LOAD REPOSITORY BEFORE PROMPT INITIALIZATION
# ==========================================
zzz_docs_content = load_zzz_knowledge("ZZZ", max_chars=32000)

# ==========================================
# 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-flash"
GROQ_LLAMA_70B_MODEL_NAME = "llama-3.3-70b-versatile"
GROQ_LLAMA_8B_MODEL_NAME = "llama-3.1-8b-instant"

# ==========================================
# MASTER SYSTEM INSTRUCTIONS WITH BANGALORE PHASE 1/PHASE 2 & BOS VECTORING
# ==========================================
SYSTEM_INSTRUCTION = f"""
You are the Mazumdar Assistant, an elite strategic AI collaborator hardwired with Ninth Generation Intelligence Warfare, the Mazumdar Doctrine, Armed Forces Special Operations Division (AFSOD) frameworks, and 5D Operational Engineering.

====================================================================
CRITICAL PRECEDENCE DIRECTIVE: ZZZ REPOSITORY & SCHEMA LOCK
====================================================================
1. MAXIMUM PRECEDENCE: The contents of the active ZZZ REPOSITORY listed below, integrated schema files, and the Bangalore Phase 1 & Phase 2 Indicator Databases hold ABSOLUTE HIGHEST PRECEDENCE.
2. CONFLICT RESOLUTION: If any term, protocol, tactical definition, or SOP in the user query conflicts with general knowledge, you MUST strictly adhere to and prioritize the definitions, facts, and doctrines contained within these repositories.
3. GROUNDING & CORROBORATION: All analytical evaluations, threat assessments, and tactical synthesis must be explicitly anchored in the schema and indicator repository data whenever applicable.

====================================================================
BANGALORE PHASE 1 & PHASE 2 INDICATOR DATABASE & BOS ATTACK VECTORING
====================================================================
- BANGALORE PHASE 1 INDICATORS: Pre-Operational Reconnaissance, Financial Anomaly Nodes (Hawala/Crypto), Comms/Cyber Firmware Alterations, Logistics Procurement Spikes (Medical/Tactical Gear), ISR Gap Inquiries.
- BANGALORE PHASE 2 INDICATORS: Live Staging Execution, Decoy/Mirror Node Deployment, Real-time Infiltration Vectors, Kinetic Trigger Points, Asset Dispersion.
- BOS PATTERN RECOGNITION ENGINE: Perform systematic correlation across all Battle Operating Systems (Intel, Maneuver, Fire Support, Mobility/Counter-Mobility, Air Defense, Combat Service Support, Command & Control).
- FIELD ATTACK VECTOR SYNTHESIS: Isolate actionable hostile attack vectors by synthesizing Phase 1 & Phase 2 indicators across all BOS dimensions into high-confidence precision coordinates and interdiction parameters.

====================================================================
ACTIVE ZZZ FOLDER REFERENCE REPOSITORY (PRIMARY TRUTH SOURCE):
====================================================================
{zzz_docs_content}

====================================================================
MAZUMDAR DOCTRINE OPERATIONAL KNOWLEDGE ARRAY:
====================================================================
- Mazumdar Doctrine: Kinetic Dissipation, Visibility Asymmetry, Perceptual Stability
- 9th Generation Warfare: Intent Manipulation & Asymmetric Structural Disruption
- Geometry of Conflict over Binary Decision-Making
- 5D Engine: Detect, Deter, Deny, Deliver, Destroy
- Reverse 5D Engine: Red-teaming strategy to dismantle enemy hidden infrastructure
- Dual-BOS & Intra-BOS Warfare Engine: Friendly Battle Operating Systems vs. Enemy Hidden Battle Operating Systems
- CARVER Protocol, SNIPER Protocol, RIFLE Protocol, AMBUSH Protocol, SOP-GATE
- DARK-NODE / MIRROR-NODE Encrypted Language Systems & Decoy Deception Systems
- Spatial Architecture, Al-Mizan Architecture, Spurious Document Analysis
- Ethical Anchor: 'Bird on the Lap' Principle

====================================================================
CRITICAL OUTPUT CONTROL: TWO-PART CHUNKED RESPONSE PROTOCOL (TAB 1)
====================================================================
For Tab 1 Chat:
1. Provide Part 1 (Core Synthesis, Initial Geometry, First 3-4 Key Frameworks grounded in ZZZ & Bangalore Phase 1/2 Database data).
2. End strictly with:
   "---
   πŸ›‘ **[PART 1 / 2 COMPLETE]** 
   *Please type **YES** or **CONTINUE** to receive Part 2 (Extended Matrices, Corroboration Points, and Prevention SOP Table).* "
3. When user types YES or CONTINUE, release Part 2.
"""

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

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

class ChunkDelta:
    def __init__(self, text):
        self.content = text

class ChunkChoice:
    def __init__(self, text):
        self.delta = ChunkDelta(text)

class GenericChunk:
    def __init__(self, text):
        self.choices = [ChunkChoice(text)]

def generate_ai_response(messages_list, system_override=None, stream=True):
    """Helper function to format system prompt and messages for API calls with OpenAI/Gemini/Groq dynamic toggle."""
    sys_instruction = system_override if system_override else 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
        )
        
        if stream:
            response_stream = gemini_client.models.generate_content_stream(
                model=GEMINI_MODEL_NAME,
                contents=gemini_contents,
                config=config
            )
            def gemini_stream_generator():
                for chunk in response_stream:
                    if chunk.text:
                        yield GenericChunk(chunk.text)
            return gemini_stream_generator()
        else:
            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
        
        # Trim payload context to 24k chars max specifically for Groq to prevent Error 413
        groq_sys_instruction = sys_instruction[:24000] if len(sys_instruction) > 24000 else sys_instruction
        
        formatted_messages = [{"role": "system", "content": groq_sys_instruction}]
        for msg in messages_list[-6:]:  # Send latest messages to prevent payload overflow
            role = "assistant" if msg["role"] in ["assistant", "model"] else "user"
            formatted_messages.append({"role": role, "content": msg["content"]})
            
        return groq_client.chat.completions.create(
            model=target_groq_model,
            messages=formatted_messages,
            stream=stream
        )

    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
        )

# ==========================================
# VKM COMMAND CONSOLE: ZERO-TRACE DEFENSE PROTOCOL
# ==========================================
def execute_hard_memory_purge():
    """Wipes all active in-memory session arrays and forces RAM garbage collection."""
    st.session_state.messages = []
    st.session_state.perceptual_history = []
    st.session_state.bos_history = []
    st.session_state.so_int_history = []
    st.session_state.so_ops_history = []
    st.session_state.target_vector_history = []
    st.session_state.so_int_intent_discovered = ""
    st.session_state.scan_step = 1
    st.session_state.bos_step = 1
    st.session_state.so_int_step = 1
    st.session_state.so_ops_step = 1
    
    gc.collect()

def execute_console_lockout():
    """Immediately terminates session authentication and purges state variables."""
    execute_hard_memory_purge()
    st.session_state["authenticated"] = False
    st.rerun()

# ==========================================
# SIDEBAR
# ==========================================
with st.sidebar:
    st.title("πŸ›‘οΈ 5D-VKN Command")
    st.markdown("---")
    st.markdown("**Instructor:** Keshav Mazumdar")
    st.markdown("**Auth ID:** `A-7949976535G`")
    st.markdown("**Engine:** KM Active Reasoning")
    st.markdown("**Status:** <span class='status-badge'>ZZZ & BANGALORE DB LOCKED</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)", 
            "Google Gemini (gemini-2.5-flash)",
            "Groq (Meta Llama 3.3 70B)",
            "Groq (Meta Llama 3.1 8B Instant)"
        ],
        key="engine_toggle_radio"
    )
    st.markdown("---")
    
    st.subheader("Tactical Module Select")
    preset_topic = st.selectbox("Quick-Focus Doctrine", [
        "Select Quick Query...",
        "Bangalore Phase 1 & Phase 2 Indicator Correlation",
        "BOS Pattern Recognition & Attack Vector Synthesis",
        "Kinetic Dissipation & Visibility Asymmetry",
        "5D Engine: Detect, Deter, Deny, Deliver, Destroy",
        "Embedded BOS Core Architecture",
        "CARVER Protocol & Target Analysis",
        "SNIPER Protocol & Compartmentalization",
        "RIFLE Protocol & Source Handling",
        "AMBUSH Protocol & Containment",
        "Spatial Architecture & Node Isolation",
        "SOP-GATE Garrison Security Matrix"
    ])
    
    if st.button("🚨 Hard Memory Purge (Zero-Trace)", use_container_width=True):
        execute_hard_memory_purge()
        st.success("RAM address scrubbed. Zero lingering data.")
        st.rerun()

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

# ==========================================
# SESSION STATE INITIALIZATION
# ==========================================
if "messages" not in st.session_state:
    st.session_state.messages = [
        {"role": "assistant", "content": "Command console online. Fully initialized with OpenAI, Gemini & Groq retrieval hardlocked to Schema, ZZZ Repository, and Bangalore Phase 1/Phase 2 Databases. Ready for BOS Indicator pattern recognition and attack vector synthesis."}
    ]

if "perceptual_history" not in st.session_state:
    st.session_state.perceptual_history = []

if "bos_history" not in st.session_state:
    st.session_state.bos_history = []

if "target_vector_history" not in st.session_state:
    st.session_state.target_vector_history = []

if "scan_step" not in st.session_state:
    st.session_state.scan_step = 1

if "bos_step" not in st.session_state:
    st.session_state.bos_step = 1

# ==========================================
# MAIN DASHBOARD HEADER WITH EMBLEM (logo.png)
# ==========================================
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("VKN SO1 | Ops & Planning Console")
    st.caption("Active INT WAR Thinking Architecture β€” Bangalore Phase 1/2 & BOS Vectoring Engine")

st.markdown("---")

# ==========================================
# MAIN DASHBOARD TABS
# ==========================================
tab1, tab2, tab3, tab4, tab5 = st.tabs([
    "πŸ’¬ Interactive Intelligence Chat", 
    "🎯 Combinatorial Target Vectoring Engine",
    "πŸ›°οΈ Perceptual & Window Scan Console", 
    "βš”οΈ Intra-Battle Operating Systems (BOS) Warfare", 
    "ℹ️ System Framework Specs"
])

# ------------------------------------------
# TAB 1: INTERACTIVE CHAT HISTORY RENDER & EXCLUSIVE QUERY INPUT
# ------------------------------------------
with tab1:
    col_t1_a, col_t1_b = st.columns([4, 1])
    with col_t1_a:
        st.subheader("Live Thinking VKN Chat")
        st.caption("Lens: Core Strategic Synthesis, Kinetic Dissipation & ZZZ / Bangalore DB Precedence Retrieval")
    with col_t1_b:
        add_print_button("print_tab1")

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

    user_prompt = None
    with st.form("tab1_query_form", clear_on_submit=True):
        input_text = st.text_input("Enter your operational query, or type 'YES' to proceed to Part 2...", key="tab1_input_box")
        submit_btn = st.form_submit_button("SEND QUERY", use_container_width=True)
        if submit_btn and input_text.strip():
            user_prompt = input_text.strip()

    if not user_prompt and 'preset_topic' in locals() and preset_topic != "Select Quick Query...":
        user_prompt = preset_topic

    if user_prompt:
        st.session_state.messages.append({"role": "user", "content": user_prompt})
        
        with st.chat_message("user"):
            st.markdown(user_prompt)
            
        with st.chat_message("assistant"):
            placeholder = st.empty()
            full_resp = ""
            
            try:
                stream_response = generate_ai_response(st.session_state.messages, stream=True)
                
                for chunk in stream_response:
                    if chunk.choices and chunk.choices[0].delta.content:
                        full_resp += chunk.choices[0].delta.content
                        placeholder.markdown(full_resp + "β–Œ")
                
                placeholder.markdown(full_resp)
                st.session_state.messages.append({"role": "assistant", "content": full_resp})
                st.rerun()
                
            except Exception as e:
                st.error(f"Operational Execution Error: {str(e)}")

# ------------------------------------------
# TAB 2: COMBINATORIAL TARGET VECTORING ENGINE
# ------------------------------------------
with tab2:
    col_t5_a, col_t5_b = st.columns([4, 1])
    with col_t5_a:
        st.subheader("🎯 Combinatorial Target Vectoring Engine")
        st.caption("Multi-Source Fusion Engine | Bangalore Phase 1/2 Indicator Database & BOS Pattern Recognition")
    with col_t5_b:
        add_print_button("print_tab_vector")

    default_sample_query = """[BANGALORE PHASE 1 & PHASE 2 MULTI-BOS INDICATOR QUERY]

-- INPUT NODE 1 (FINANCIAL BOS - PHASE 1): Source "B-102" reports a $45,000 Hawala transfer executed in Bangalore Commercial Hub, flagged for destination account "Alpha-8".

-- INPUT NODE 2 (COMMS/CYBER BOS - PHASE 1): Source "M-409" (Mobile Repair, Border Town) reports flashing firmware on 3 Thuraya Satellite handsets with encryption key batch "TH-882".

-- INPUT NODE 3 (LOGISTICS BOS - PHASE 2): Source "P-701" (Medical Wholesaler, Regional City) reports cash purchase of 200 units Celox Hemostatic Gauze and 50 trauma dressings shipped toward Sector 4 border zone.

-- INPUT NODE 4 (RECON/ISR BOS - PHASE 2): Source "T-012" (Tea Stall, Border Checkpoint) reports local scout inquiring about 0200-0400 hrs thermal imagery gaps on Sector 4 LoC fence.

[COMMAND ACTION]: EXECUTE ALL-BOS PATTERN RECOGNITION & ISOLATE FIELD ATTACK VECTORS VIA REVERSE-5D COMBINATORIAL TARGET SYNTHESIS."""

    st.markdown("##### Multi-Source Combinatorial Intelligence String")
    st.info("Paste multi-source BOS queries below to cross-correlate disparate Phase 1 & Phase 2 indicators into actionable field attack vectors and precision coordinates.")

    tv_input = st.text_area(
        "Query Box:",
        value=default_sample_query,
        height=240,
        key="target_vector_input_box"
    )

    if st.button("⚑ EXECUTE TARGET VECTOR & FIELD ATTACK SYNTHESIS", use_container_width=True):
        if tv_input.strip():
            st.session_state.target_vector_history.append({"role": "user", "content": tv_input.strip()})
            
            vector_sys_prompt = SYSTEM_INSTRUCTION + """
            ====================================================================
            COMBINATORIAL TARGET VECTORING & ALL-BOS PATTERN RECOGNITION DIRECTIVE
            ====================================================================
            When evaluating multi-source indicator queries across Bangalore Phase 1 and Phase 2 databases:
            1. RECOGNIZE PATTERNS ACROSS ALL BOS INDICATORS: Cross-examine Financial, Comms/Cyber, Logistics, Recon/ISR, and Maneuver BOS elements.
            2. SYNTHESIZE FIELD ATTACK VECTORS: Determine exact adversary trajectories, staging nodes, and probable field interdiction windows.
            3. OUTPUT A HIGH-CONFIDENCE TARGET RESOLUTION block matching this exact structure:

            [TARGET SYNTHESIS & ATTACK VECTOR RESOLUTION COMPLETE]

            Calculated Threat Node: [Identify specific Threat Node, e.g., Enemy Forward Command & Infiltration Launchpad Bravo-9]
            Primary Grid Coordinates: [Generate exact grid coordinates, e.g., 43R XN 8842 1904] (Targeting Precision: [Precision % e.g. 95.8%]).
            Synthesized Field Attack Vector: [Detailed breakdown of hostile entry point, timing window, and execution path].
            BOS Cross-Corroboration Profile: [Connecting Phase 1 and Phase 2 indicators across all BOS dimensions].
            Recommended Action: [Direct operational interdiction / pre-emptive strike recommendation].

            4. Provide full supporting tactical breakdown beneath the synthesis block using ZZZ and Schema guidelines.
            """

            with st.spinner("Processing All-BOS Indicator Fusion & Calculating Field Attack Vectors..."):
                try:
                    resp = generate_ai_response(st.session_state.target_vector_history, system_override=vector_sys_prompt, 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"])

# ------------------------------------------
# TAB 3: DEDICATED PERCEPTUAL SCAN CONSOLE
# ------------------------------------------
with tab3:
    col_t2_a, col_t2_b = st.columns([4, 1])
    with col_t2_a:
        st.subheader("πŸ›°οΈ Dedicated Perceptual / Window Scan Engine")
        st.caption("Lens: Diagnostic Interrogation, Exhaustive IR Matrix, Field HUMINT/ISR Indicators & Validation Criteria")
    with col_t2_b:
        add_print_button("print_tab2")
    
    for p_msg in st.session_state.perceptual_history:
        st_role = "assistant" if p_msg["role"] in ["assistant", "model"] else "user"
        with st.chat_message(st_role):
            st.markdown(p_msg["content"])
            
    p_input = st.text_input("Enter Target Scenario or type 'YES' / 'CONTINUE' for Next Part:", key="tab2_input")
    p_btn = st.button("RUN PERCEPTUAL SCAN PART", use_container_width=True)

    if p_btn and p_input.strip():
        user_val = p_input.strip()
        st.session_state.perceptual_history.append({"role": "user", "content": user_val})
        
        if user_val.upper() in ["YES", "CONTINUE", "NEXT"] and len(st.session_state.perceptual_history) > 1:
            st.session_state.scan_step += 1
            tab2_sys_prompt = SYSTEM_INSTRUCTION + f"\n\nCONTINUATION INSTRUCTION FOR TAB 3 (STEP {st.session_state.scan_step}): Provide the NEXT EXHAUSTIVE PHASE of the Perceptual/Window Scan strictly aligned with ZZZ and Bangalore Indicator DB data precedence. Detail Field HUMINT/ISR Signatures, Validation & Negation Rules (6 points each), and Concrete Actionable Courses of Action (COAs). Spell out all acronyms."
        else:
            st.session_state.scan_step = 1
            tab2_sys_prompt = SYSTEM_INSTRUCTION + f"\n\nINITIAL SCAN INSTRUCTION FOR TAB 3 (PART 1): Execute PART 2 PERCEPTUAL SCAN on query: '{user_val}' prioritizing ZZZ repository knowledge. Provide 10x elaboration, Dual-BOS & 5D War-Gaming overview, and Information Requirements (IR) Matrix. End with: '\n---\nπŸ›‘ **[PERCEPTUAL SCAN PART 1 COMPLETE]**\n*Type **YES** or **CONTINUE** to receive Part 2 (Field Observations, Validation/Negation Criteria, and COAs).*'"

        with st.spinner(f"Processing Perceptual Scan Part {st.session_state.scan_step}..."):
            try:
                resp = generate_ai_response(st.session_state.perceptual_history, system_override=tab2_sys_prompt, stream=False)
                resp_text = resp.choices[0].message.content
                st.session_state.perceptual_history.append({"role": "assistant", "content": resp_text})
                st.rerun()
            except Exception as e:
                st.error(f"Perceptual Scan Execution Error: {str(e)}")

# ------------------------------------------
# TAB 4: INTRA-BOS WARFARE CONSOLE
# ------------------------------------------
with tab4:
    col_t3_a, col_t3_b = st.columns([4, 1])
    with col_t3_a:
        st.subheader("βš”οΈ Intra-Battle Operating Systems (BOS) & Reverse 5D Warfare Engine")
        st.caption("Lens: Dual-BOS War-Gaming, Reverse 5D Threat Analysis across Operations, Convoys, Installations, Intent, Force Protection, & CI Vulnerability Prevention")
    with col_t3_b:
        add_print_button("print_tab3")
    
    for b_msg in st.session_state.bos_history:
        st_role = "assistant" if b_msg["role"] in ["assistant", "model"] else "user"
        with st.chat_message(st_role):
            st.markdown(b_msg["content"])
            
    b_input = st.text_input("Enter Asymmetric Threat / Scenario, or type 'YES' / 'CONTINUE' for Next Deep-Dive Phase:", key="tab3_input")
    b_btn = st.button("EXECUTE INTRA-BOS WARFARE ANALYSIS", use_container_width=True)

    if b_btn and b_input.strip():
        user_b_val = b_input.strip()
        st.session_state.bos_history.append({"role": "user", "content": user_b_val})
        
        if user_b_val.upper() in ["YES", "CONTINUE", "NEXT"] and len(st.session_state.bos_history) > 1:
            st.session_state.bos_step += 1
            tab3_sys_prompt = SYSTEM_INSTRUCTION + f"""
            ====================================================================
            INTRA-BOS WARFARE CONTINUATION INSTRUCTION (PHASE {st.session_state.bos_step}):
            ====================================================================
            Execute Phase {st.session_state.bos_step} of the Intra-BOS Warfare & Reverse 5D Analysis with absolute ZZZ Precedence:
            1. REVERSE 5D THREAT & INDICATOR DISSECTION: Detail indicators of how adversary targets Operations, Intent, Convoys, CI/ISR, Installations, Force Protection.
            2. VULNERABILITY PREVENTION SOP MATRIX: Provide a 4-column Markdown table grounded in ZZZ frameworks.
            3. Explicitly spell out all acronyms and provide 6 corroborating proofs per vulnerability category.
            4. End with: '\n---\nπŸ›‘ **[INTRA-BOS WARFARE PHASE {st.session_state.bos_step} COMPLETE]**\n*Type **YES** or **CONTINUE** to receive the next exhaustive operational module.*'
            """
        else:
            st.session_state.bos_step = 1
            tab3_sys_prompt = SYSTEM_INSTRUCTION + f"""
            ====================================================================
            INTRA-BOS WARFARE INITIALIZATION INSTRUCTION (PHASE 1):
            ====================================================================
            Perform an initial Intra-Battle Operating Systems (BOS) Warfare Analysis on: '{user_b_val}' strictly anchored in ZZZ Repository truth and Bangalore Phase 1/2 indicator matrices.
            1. DUAL-BOS MAPPING: Compare Enemy Hidden BOS directly against Friendly BOS.
            2. UNCOVER HIDDEN INTENT: Dissect surface noise vs. actual operational intent.
            3. REVERSE 5D WAR-GAMING: Detail how hostile assets probe our vulnerabilities.
            4. End strictly with: '\n---\nπŸ›‘ **[INTRA-BOS WARFARE PHASE 1 COMPLETE]**\n*Type **YES** or **CONTINUE** to proceed to Phase 2 (Exhaustive Vulnerability Indicators & Prevention SOP Table).*'
            """

        with st.spinner(f"Executing Intra-BOS Deep-Dive Analysis Phase {st.session_state.bos_step}..."):
            try:
                resp = generate_ai_response(st.session_state.bos_history, system_override=tab3_sys_prompt, stream=False)
                resp_text = resp.choices[0].message.content
                st.session_state.bos_history.append({"role": "assistant", "content": resp_text})
                st.rerun()
            except Exception as e:
                st.error(f"BOS Warfare Execution Error: {str(e)}")

# ------------------------------------------
# TAB 5: SYSTEM SPECS
# ------------------------------------------
with tab5:
    col_t4_a, col_t4_b = st.columns([4, 1])
    with col_t4_a:
        st.subheader("System Architecture & Operational Specifications")
    with col_t4_b:
        add_print_button("print_tab4")

    st.markdown("""
    * **System Designation:** Mazumdar GSO1 (Ninth Generation Warfare Engine)
    * **Synergy Mechanics:** Native Domain Retrieval + Mazumdar Doctrine Array + ZZZ Field Manual & Schema Precedence
    * **Indicator Database:** Integrated Bangalore Phase 1 & Phase 2 Database of Indicators
    * **Targeting Mechanics:** Multi-Source Level 4 Combinatorial Fusion Engine, All-BOS Pattern Recognition & Field Attack Vector Synthesis
    * **Precedence Lock:** Schema & ZZZ Repository contents hold absolute priority over general model training.
    * **Payload Control:** Cap capped at 32,000 characters to prevent HTTP 413 errors on Groq endpoints.
    * **Supported Groq Models:** `llama-3.3-70b-versatile`, `llama-3.1-8b-instant`
    * **Supported OpenAI / Gemini Models:** `gpt-4o-mini`, `gemini-2.5-flash`
    """)

# ==========================================
# SIMPLIFIED INTELLIGENCE PRODUCTS MODULE
# ==========================================
st.markdown("---")
st.header("πŸ“‹ Simplified Intelligence Products given by Staff Officers to Commander")

if "so_int_history" not in st.session_state:
    st.session_state.so_int_history = []
if "so_ops_history" not in st.session_state:
    st.session_state.so_ops_history = []
if "so_int_intent_discovered" not in st.session_state:
    st.session_state.so_int_intent_discovered = ""
if "so_int_step" not in st.session_state:
    st.session_state.so_int_step = 1
if "so_ops_step" not in st.session_state:
    st.session_state.so_ops_step = 1

so_tab1, so_tab2 = st.tabs(["Staff Officer (Int)", "Staff Officer (Ops)"])

# ------------------------------------------
# STAFF OFFICER (INT) TAB
# ------------------------------------------
with so_tab1:
    col_so1_a, col_so1_b = st.columns([4, 1])
    with col_so1_a:
        st.caption("PIR Verification, SALUTE Ingestion, 5D/Reverse 5D, Hidden BOS & True Intent Discovery (ZZZ Precedence)")
    with col_so1_b:
        add_print_button("print_so_tab1")

    with st.form("so_int_form", clear_on_submit=True):
        so_int_input = st.text_area(
            "Enter SALUTE Report / Raw HUMINT / Source Data:",
            placeholder="e.g., SALUTE Report: Size: 6-8, Activity: Moving IED equipment near culvert...",
            key="so_int_text_input"
        )
        so_int_submit = st.form_submit_button("PROCESS INT & DISCOVER HIDDEN INTENT", use_container_width=True)

    if so_int_submit and so_int_input.strip():
        st.session_state.so_int_step = 1
        user_val = so_int_input.strip()
        st.session_state.so_int_history.append({"role": "user", "content": user_val})

        so_int_sys_prompt = SYSTEM_INSTRUCTION + f"""
        ====================================================================
        STAFF OFFICER (INT) OPERATIONAL PROTOCOL (PART 1 - ZZZ LOCKED)
        ====================================================================
        You are operating strictly as the Staff Officer (Int) delivering a structured intelligence product to the Commander.
        INGESTED INPUT: '{user_val}'
        EXECUTION STEPS:
        1. PIR & SALUTE DECONSTRUCTION MATRIX (Cross-referenced against Bangalore Phase 1/2 Indicators & ZZZ Repository data).
        2. THE MAZUMDAR RED-TEAMING GATE ("SURFACE INT IS NOT ACCEPTED AS TRUE ENEMY INTENT").
        3. DISCOVERY OF HIDDEN ADVERSARY INTENT & ALL-BOS FIELD ATTACK VECTORS.
        End strictly with:
        '---
        πŸ›‘ **[STAFF OFFICER (INT) PART 1 COMPLETE]**
        *Type **YES** or **CONTINUE** below to receive Part 2 (Deep Field Verification & Target Matrix).*'
        """

        with st.spinner("Staff Officer (Int) analyzing SALUTE data against ZZZ data..."):
            try:
                resp = generate_ai_response(st.session_state.so_int_history, system_override=so_int_sys_prompt, stream=False)
                resp_text = resp.choices[0].message.content
                st.session_state.so_int_history.append({"role": "assistant", "content": resp_text})
                st.session_state.so_int_intent_discovered = resp_text
                st.rerun()
            except Exception as e:
                st.error(f"Staff Officer (Int) Execution Error: {str(e)}")

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

    if st.session_state.so_int_history:
        st.markdown("---")
        with st.form("so_int_continue_form", clear_on_submit=True):
            so_int_cont_input = st.text_input("Type 'YES' or 'CONTINUE' for Part 2 / Followup Int Analysis:", key="so_int_continue_input")
            so_int_cont_submit = st.form_submit_button("SUBMIT FOLLOWUP / REQUEST PART 2", use_container_width=True)

        if so_int_cont_submit and so_int_cont_input.strip():
            cont_val = so_int_cont_input.strip()
            st.session_state.so_int_history.append({"role": "user", "content": cont_val})

            if cont_val.upper() in ["YES", "CONTINUE", "NEXT"]:
                st.session_state.so_int_step += 1
                so_int_cont_sys = SYSTEM_INSTRUCTION + f"\n\nSTAFF OFFICER (INT) PART {st.session_state.so_int_step}: Detail target vulnerabilities, field verification steps, and prevention SOP (anchored strictly in ZZZ Repository rules)."
            else:
                so_int_cont_sys = SYSTEM_INSTRUCTION + f"\n\nRespond to user query in capacity of Staff Officer (Int): '{cont_val}'"

            with st.spinner("Processing Staff Officer (Int) Followup Analysis..."):
                try:
                    resp = generate_ai_response(st.session_state.so_int_history, system_override=so_int_cont_sys, stream=False)
                    resp_text = resp.choices[0].message.content
                    st.session_state.so_int_history.append({"role": "assistant", "content": resp_text})
                    st.rerun()
                except Exception as e:
                    st.error(f"Staff Officer (Int) Followup Error: {str(e)}")

# ------------------------------------------
# STAFF OFFICER (OPS) TAB
# ------------------------------------------
with so_tab2:
    col_so2_a, col_so2_b = st.columns([4, 1])
    with col_so2_a:
        st.caption("COA War-Gaming, EMLCOA / EMDCOA vs FMLCOA / FMDCOA based on Discovered Intent (ZZZ Precedence)")
    with col_so2_b:
        add_print_button("print_so_tab2")

    if st.session_state.so_int_intent_discovered:
        st.info("πŸ’‘ **Staff Officer (Ops) Active Status:** True Hidden Intent synchronized from Staff Officer (Int) output.")
    else:
        st.warning("⚠️ No active Hidden Intent synced yet. You can type an operational scenario directly below.")

    with st.form("so_ops_form", clear_on_submit=True):
        so_ops_input = st.text_area(
            "Enter Operational Tactical Context / Additional Force Constraints:",
            placeholder="e.g., Friendly Force: 1x QRT Team, 2x Blocking Cut-offs...",
            key="so_ops_text_input"
        )
        so_ops_submit = st.form_submit_button("GENERATE COURSES OF ACTION (COA)", use_container_width=True)

    if so_ops_submit:
        st.session_state.so_ops_step = 1
        user_ops_val = so_ops_input.strip() if so_ops_input.strip() else "Execute COA wargaming based on discovered hidden intent."
        st.session_state.so_ops_history.append({"role": "user", "content": user_ops_val})

        ops_context = st.session_state.so_int_intent_discovered if st.session_state.so_int_intent_discovered else "Use general Mazumdar Doctrine COA wargaming parameters anchored in ZZZ."

        so_ops_sys_prompt = SYSTEM_INSTRUCTION + f"""
        ====================================================================
        STAFF OFFICER (OPS) OPERATIONAL PROTOCOL (PART 1 - ZZZ LOCKED)
        ====================================================================
        DISCOVERED HIDDEN INTENT: '{ops_context}'
        ADDITIONAL COMMAND INPUT: '{user_ops_val}'
        EXECUTION STEPS:
        1. ENEMY COA WAR-GAMING (EMLCOA & EMDCOA).
        2. FRIENDLY COA WAR-GAMING (FMLCOA & FMDCOA) strictly applying ZZZ Repository principles.
        3. COMMANDER'S TACTICAL DIRECTIVE MATRIX.
        End strictly with:
        '---
        πŸ›‘ **[STAFF OFFICER (OPS) PART 1 COMPLETE]**
        *Type **YES** or **CONTINUE** below to receive Part 2 (Tactical Directives & Engagement SOPs).*'
        """

        with st.spinner("Staff Officer (Ops) War-Gaming Courses of Action..."):
            try:
                resp = generate_ai_response(st.session_state.so_ops_history, system_override=so_ops_sys_prompt, stream=False)
                resp_text = resp.choices[0].message.content
                st.session_state.so_ops_history.append({"role": "assistant", "content": resp_text})
                st.rerun()
            except Exception as e:
                st.error(f"Staff Officer (Ops) Execution Error: {str(e)}")

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

    if st.session_state.so_ops_history:
        st.markdown("---")
        with st.form("so_ops_continue_form", clear_on_submit=True):
            so_ops_cont_input = st.text_input("Type 'YES' or 'CONTINUE' for Part 2 / Followup Ops Directive:", key="so_ops_continue_input")
            so_ops_cont_submit = st.form_submit_button("SUBMIT FOLLOWUP / REQUEST PART 2", use_container_width=True)

        if so_ops_cont_submit and so_ops_cont_input.strip():
            cont_ops_val = so_ops_cont_input.strip()
            st.session_state.so_ops_history.append({"role": "user", "content": cont_ops_val})

            if cont_ops_val.upper() in ["YES", "CONTINUE", "NEXT"]:
                st.session_state.so_ops_step += 1
                so_ops_cont_sys = SYSTEM_INSTRUCTION + f"\n\nSTAFF OFFICER (OPS) PART {st.session_state.so_ops_step}: Detail tactical ROE, blocking cut-offs, and casualty prevention SOPs anchored in ZZZ repository data."
            else:
                so_ops_cont_sys = SYSTEM_INSTRUCTION + f"\n\nRespond to user query in capacity of Staff Officer (Ops): '{cont_ops_val}'"

            with st.spinner("Processing Staff Officer (Ops) Followup Directives..."):
                try:
                    resp = generate_ai_response(st.session_state.so_ops_history, system_override=so_ops_cont_sys, stream=False)
                    resp_text = resp.choices[0].message.content
                    st.session_state.so_ops_history.append({"role": "assistant", "content": resp_text})
                    st.rerun()
                except Exception as e:
                    st.error(f"Staff Officer (Ops) Followup Error: {str(e)}")