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

from fastapi import FastAPI, Request, Form, UploadFile, File, WebSocket, WebSocketDisconnect, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from dotenv import load_dotenv

import docx
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
import pypdf

from google import genai
from google.genai import types

def extract_text_from_pdf(file_path: str) -> str:
    """Extracts raw text from a PDF document (.pdf)."""
    try:
        reader = pypdf.PdfReader(file_path)
        text_content = []
        for page in reader.pages:
            text = page.extract_text()
            if text:
                text_content.append(text)
        return "\n".join(text_content)
    except Exception as e:
        print(f"[ERROR] Failed to extract text from PDF: {e}")
        return ""

# Load environment variables relative to main.py's directory location
base_dir = os.getcwd()  # Or relative to main.py
base_dir = os.path.dirname(os.path.abspath(__file__))
dotenv_path = os.path.join(base_dir, ".env")
load_dotenv(dotenv_path=dotenv_path, override=True)

app = FastAPI(title="TRON - Voice-Activated News Prototype")

# Enable CORS for cross-origin development or file:/// access
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.exception_handler(Exception)
async def debug_exception_handler(request: Request, exc: Exception):
    print("[CRITICAL UNCAUGHT EXCEPTION]", flush=True)
    import traceback
    traceback.print_exc()
    return HTMLResponse(content=f"Internal Server Error: {exc}", status_code=500)


# Ensure required static directories exist
os.makedirs("static/notes", exist_ok=True)
os.makedirs("static/uploads", exist_ok=True)
os.makedirs("static/articles", exist_ok=True)

# Initialize Firebase Admin SDK if credentials and bucket are configured in env
firebase_initialized = False
try:
    fb_creds_json = os.getenv("FIREBASE_CREDENTIALS")
    fb_bucket = os.getenv("FIREBASE_STORAGE_BUCKET")
    if fb_creds_json and fb_bucket:
        import firebase_admin
        from firebase_admin import credentials
        creds_dict = json.loads(fb_creds_json)
        cred = credentials.Certificate(creds_dict)
        firebase_admin.initialize_app(cred, {
            'storageBucket': fb_bucket
        })
        firebase_initialized = True
        print("[INFO] Firebase Admin SDK successfully initialized.", flush=True)
    else:
        print("[WARNING] Firebase environment variables not fully set. Running in local ephemeral mode.", flush=True)
except Exception as e:
    print(f"[ERROR] Failed to initialize Firebase Admin SDK: {e}", flush=True)
    traceback.print_exc()

def upload_to_firebase(local_path: str, destination_blob_name: str, content_type: str) -> Optional[str]:
    """Uploads a file to Firebase Storage and returns its public URL if successful."""
    if not firebase_initialized:
        return None
    try:
        from firebase_admin import storage
        bucket = storage.bucket()
        blob = bucket.blob(destination_blob_name)
        blob.upload_from_filename(local_path, content_type=content_type)
        blob.make_public()
        return blob.public_url
    except Exception as e:
        print(f"[ERROR] Firebase upload failed for {local_path}: {e}", flush=True)
        traceback.print_exc()
        return None

# Mount static folder for downloads and uploads
app.mount("/static", StaticFiles(directory="static"), name="static")

from analytics_db import init_db, log_session, log_utterance, get_analytics_data, get_session_timeline, get_articles_by_emotion
# Initialize local SQLite analytics database
init_db()

# Initialize Templates
templates = Jinja2Templates(directory="templates")

# Target model ID for Multimodal Live API
MODEL_ID = "gemini-3.8-live"

def extract_text_from_docx(file_path: str) -> str:
    """Extracts raw text from a Microsoft Word document (.docx)."""
    doc = Document(file_path)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                full_text.append(cell.text)
    return "\n".join(full_text)

def create_note_docx(subject: str, content_summary: str, filepath: str):
    """Generates a professionally styled Microsoft Word document matching the editorial context."""
    doc = Document()
    
    # Page Margins (1 inch)
    for section in doc.sections:
        section.top_margin = Inches(1)
        section.bottom_margin = Inches(1)
        section.left_margin = Inches(1)
        section.right_margin = Inches(1)
        
    # Title Section (Georgia Font - Times Replica)
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.paragraph_format.space_after = Pt(2)
    run = p.add_run("TRON RESEARCH NOTE")
    run.font.name = 'Georgia'
    run.font.size = Pt(20)
    run.bold = True
    run.font.color.rgb = RGBColor(15, 23, 42) # Slate-900

    # Subject Line
    p_sub = doc.add_paragraph()
    p_sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_sub.paragraph_format.space_after = Pt(12)
    run_sub = p_sub.add_run(f"Subject: {subject}")
    run_sub.font.name = 'Georgia'
    run_sub.font.size = Pt(12)
    run_sub.italic = True
    run_sub.font.color.rgb = RGBColor(71, 85, 105) # Slate-600

    # Thin Divider
    p_div = doc.add_paragraph()
    p_div.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_div.paragraph_format.space_after = Pt(18)
    run_div = p_div.add_run("—" * 50)
    run_div.font.name = 'Georgia'
    run_div.font.color.rgb = RGBColor(203, 213, 225) # Slate-300

    # Content Body
    for paragraph_text in content_summary.split('\n'):
        cleaned_text = paragraph_text.strip()
        if not cleaned_text:
            continue
        p_body = doc.add_paragraph()
        p_body.paragraph_format.line_spacing = 1.15
        p_body.paragraph_format.space_after = Pt(8)
        
        run_body = p_body.add_run(cleaned_text)
        run_body.font.name = 'Georgia'
        run_body.font.size = Pt(11)
        run_body.font.color.rgb = RGBColor(30, 41, 59) # Slate-800

    # Footer
    section = doc.sections[0]
    footer = section.footer
    f_p = footer.paragraphs[0]
    f_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    run_footer = f_p.add_run(f"Generated by TRON Assistant Prototype • {datetime.now().strftime('%Y-%m-%d')}")
    run_footer.font.name = 'Georgia'
    run_footer.font.size = Pt(8)
    run_footer.font.color.rgb = RGBColor(148, 163, 184) # Slate-400

    doc.save(filepath)

def send_email_dispute(original_fact: str, suggested_correction: str) -> bool:
    """Sends an email summarizing the editorial dispute using credentials from the .env file."""
    smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com")
    try:
        smtp_port = int(os.getenv("SMTP_PORT", "587"))
    except:
        smtp_port = 587
        
    sender_email = os.getenv("SENDER_EMAIL")
    sender_password = os.getenv("SENDER_PASSWORD")
    receiver_email = os.getenv("RECEIVER_EMAIL")

    if not sender_email or not sender_password or not receiver_email:
        print("[WARNING] SMTP configuration incomplete in .env. Logging dispute data to stdout:")
        print(f"  - Original Fact: {original_fact}")
        print(f"  - Suggested Correction: {suggested_correction}")
        return True  # Fallback success for local development/mock environment

    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = f"TRON ALERT: Editorial Dispute Reported"

    body = f"""TRON EDITORIAL DISPUTE ALERT

A reader has flagged an assertion in the investigative report during a voice-activated session.

Original Fact Mentioned:
"{original_fact}"

Reader's Suggested Correction:
"{suggested_correction}"

Timestamp: {datetime.now().isoformat()}

Please verify the claim and update the article source if necessary.
"""
    msg.attach(MIMEText(body, 'plain'))

    if smtp_server.startswith("http://") or smtp_server.startswith("https://"):
        import requests
        payload = {
            "to": receiver_email,
            "subject": f"TRON ALERT: Editorial Dispute Reported",
            "body": body,
            "secret_key": sender_password
        }
        try:
            res = requests.post(smtp_server, json=payload, timeout=25)
            if res.status_code == 200:
                res_data = res.json()
                if res_data.get("success") or res_data.get("status") == "success":
                    print("[INFO] Editorial dispute alert sent successfully via Web Gateway.", flush=True)
                    return True
                else:
                    print(f"[ERROR] Web Gateway returned error: {res_data}", flush=True)
                    return False
            else:
                print(f"[ERROR] Web Gateway returned HTTP {res.status_code}: {res.text}", flush=True)
                return False
        except Exception as e:
            print(f"[ERROR] Failed to send email via Web Gateway: {e}", flush=True)
            return False

    try:
        if smtp_port == 465:
            server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=10)
        else:
            server = smtplib.SMTP(smtp_server, smtp_port, timeout=10)
            server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())
        server.quit()
        print("[INFO] Editorial dispute alert email sent successfully.")
        return True
    except Exception as e:
        print(f"[ERROR] Failed to send dispute email: {e}")
        return False

# ROUTES

@app.get("/", response_class=HTMLResponse)
async def dashboard_home(request: Request):
    """Renders the main Creator Dashboard."""
    return templates.TemplateResponse(request=request, name="dashboard.html")

@app.post("/construct")
async def construct_article(
    request: Request,
    background_tasks: BackgroundTasks,
    headline: str = Form(...),
    author: str = Form(...),
    date: str = Form(...),
    body: str = Form(...),
    persona: str = Form(...),
    grounding: str = Form(...),
    grounding_instructions: str = Form(""),
    voice: str = Form(...),
    greeting: str = Form(...),
    silence_duration_ms: int = Form(1000),
    custom_backend_url: Optional[str] = Form(None),
    files: Optional[List[UploadFile]] = File(None)
):
    """Ingests files, caches them in the Gemini Files API, and compiles the standalone HTML article."""
    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        return HTMLResponse("Error: GEMINI_API_KEY is not set in the server's .env file.", status_code=500)

    # Set up the article itself as the primary grounding context
    document_context = (
        f"--- Article Headline: {headline} ---\n"
        f"--- Author: {author} ---\n"
        f"--- Date: {date} ---\n"
        f"--- Article Content ---\n{body}\n"
    )

    # Process files and extract text for context
    print(f"[DEBUG] Received files: {[f.filename for f in files] if files else 'None'}", flush=True)
    if files:
        extracted_texts = []
        for uploaded_file in files:
            if uploaded_file.filename == "":
                continue
            
            # Save file locally to temp path
            temp_filename = f"{uuid.uuid4().hex}_{uploaded_file.filename}"
            temp_path = os.path.join("static", "uploads", temp_filename)
            
            with open(temp_path, "wb") as buffer:
                content = await uploaded_file.read()
                buffer.write(content)

            try:
                filename_lower = uploaded_file.filename.lower()
                if filename_lower.endswith(".docx"):
                    text_content = extract_text_from_docx(temp_path)
                    print(f"[DEBUG] Extracted {len(text_content)} chars from Word doc: {uploaded_file.filename}", flush=True)
                    extracted_texts.append(f"--- Research Document Content: {uploaded_file.filename} ---\n{text_content}\n")
                elif filename_lower.endswith(".pdf"):
                    text_content = extract_text_from_pdf(temp_path)
                    print(f"[DEBUG] Extracted {len(text_content)} chars from PDF: {uploaded_file.filename}", flush=True)
                    extracted_texts.append(f"--- Research Document Content: {uploaded_file.filename} ---\n{text_content}\n")
                else:
                    print(f"[DEBUG] Unsupported file extension for file: {uploaded_file.filename}", flush=True)
            except Exception as e:
                print(f"[ERROR] Failed to extract text from {uploaded_file.filename}: {e}", flush=True)
                traceback.print_exc()
            finally:
                # Clean up local temporary file
                try: os.remove(temp_path)
                except: pass
        
        if extracted_texts:
            document_context += "\n" + "\n".join(extracted_texts)
            
    print(f"[DEBUG] Total document_context size: {len(document_context)} characters", flush=True)

    # Build system instructions based on constraints
    system_instruction = persona
    if grounding == "true" and grounding_instructions.strip():
        system_instruction += f"\n\nSTRICT GROUNDING & CONTEXT BOUNDING RULES:\n{grounding_instructions}"

    article_filename = f"tron_article_{uuid.uuid4().hex}.html"

    # Dynamic JSON config to embed inside downloaded file
    tron_config = {
        "voice": voice,
        "system_instruction": system_instruction,
        "greeting": greeting,
        "document_context": document_context,
        "silence_duration_ms": silence_duration_ms,
        "article_id": article_filename.split(".html")[0]
    }

    # Determine backend URL: use custom_backend_url if provided, otherwise derive it dynamically
    if custom_backend_url and custom_backend_url.strip():
        url_str = custom_backend_url.strip()
        if url_str.startswith("https://"):
            backend_url = url_str.replace("https://", "wss://")
        elif url_str.startswith("http://"):
            backend_url = url_str.replace("http://", "ws://")
        elif not url_str.startswith("ws://") and not url_str.startswith("wss://"):
            backend_url = f"wss://{url_str}"
        else:
            backend_url = url_str
        
        # Ensure it ends with /ws/live
        if not backend_url.endswith("/ws/live"):
            backend_url = backend_url.rstrip("/") + "/ws/live"
    else:
        # Automatically derive ws endpoint backend URL
        host_header = request.headers.get("host", "localhost:49999")
        proto = request.headers.get("x-forwarded-proto", request.url.scheme)
        protocol = "wss" if proto == "https" else "ws"
        backend_url = f"{protocol}://{host_header}/ws/live"

    # Render template using Jinja2
    template_response = templates.TemplateResponse(
        request=request,
        name="article_template.html",
        context={
            "headline": headline,
            "author": author,
            "date": date,
            "body": body,
            "backend_url": backend_url,
            "tron_config": tron_config
        }
    )
    
    # Read the rendered template response
    html_content = template_response.body.decode("utf-8")
    
    # Save the compiled HTML file permanently under static/articles/
    article_path = os.path.join("static", "articles", article_filename)
    with open(article_path, "w", encoding="utf-8") as f:
        f.write(html_content)

    # Upload to Firebase if initialized
    fb_url = upload_to_firebase(article_path, f"articles/{article_filename}", "text/html")
    if fb_url:
        shareable_url = fb_url
    else:
        # Build public shareable URL, respecting custom_backend_url if provided
        if custom_backend_url and custom_backend_url.strip():
            custom_host = custom_backend_url.strip()
            for prefix in ["wss://", "ws://", "https://", "http://"]:
                if custom_host.startswith(prefix):
                    custom_host = custom_host[len(prefix):]
            custom_host = custom_host.split("/")[0] # Get host domain only
            
            # Determine protocol scheme
            proto = "https" if ("https" in custom_backend_url or "wss" in custom_backend_url) else "http"
            shareable_url = f"{proto}://{custom_host}/static/articles/{article_filename}"
        else:
            host_header = request.headers.get("host", "localhost:49999")
            proto = request.headers.get("x-forwarded-proto", request.url.scheme)
            shareable_url = f"{proto}://{host_header}/static/articles/{article_filename}"

    print(f"[DEBUG] Constructed permanent article hosted at: {shareable_url}", flush=True)

    return {
        "success": True,
        "shareable_url": shareable_url,
        "filename": article_filename
    }

# ANALYTICS DASHBOARD PORTAL & API ENDPOINTS

@app.get("/admin/analytics", response_class=HTMLResponse)
async def admin_analytics_page(request: Request):
    return templates.TemplateResponse(request=request, name="admin_analytics.html")

@app.get("/api/analytics/data")
async def api_analytics_data():
    return get_analytics_data()

@app.get("/api/analytics/timeline/{session_id}")
async def api_session_timeline(session_id: str):
    return get_session_timeline(session_id)

@app.get("/api/analytics/emotion/{emotion}")
async def api_articles_by_emotion(emotion: str):
    return get_articles_by_emotion(emotion)

def get_geoip_location(ip: str):
    """Retrieves country and city from client IP using a free API."""
    try:
        if not ip or ip in ["127.0.0.1", "localhost", "testclient", "::1"]:
            return "India", "Local Dev"
        
        # Strip proxies/multiple IPs
        real_ip = ip.split(",")[0].strip()
        r = requests.get(f"http://ip-api.com/json/{real_ip}", timeout=1.5)
        if r.status_code == 200:
            res = r.json()
            if res.get("status") == "success":
                return res.get("country", "India"), res.get("city", "Unknown")
    except Exception as e:
        print(f"[WARNING] Geo-IP lookup failed for {ip}: {e}", flush=True)
    return "India", "Unknown"

async def analyze_and_log_sentiment(session_id: str, user_text: str, model_text: str, api_key: str):
    """Asynchronously calls Gemini text API to analyze user sentiment and logs it to SQLite."""
    try:
        if not user_text.strip():
            return
        
        prompt = (
            f"Analyze the sentiment and emotional state of this user utterance: \"{user_text}\"\n"
            f"Context: The user is interacting with an AI news/education assistant.\n\n"
            f"Respond with a JSON object containing:\n"
            f"- primary_emotion: Choose exactly one of these categories: [admiration, amusement, anger, annoyance, approval, caring, confusion, curiosity, desire, disappointment, disapproval, disgust, embarrassment, excitement, fear, gratitude, grief, joy, love, nervousness, optimism, pride, realization, relief, remorse, sadness, surprise, neutral].\n"
            f"- secondary_emotion: Choose one category from the same list (or 'neutral').\n"
            f"- valence: Float value between -1.0 (very negative) and +1.0 (very positive).\n"
            f"- arousal: Float value between -1.0 (very calm/sleepy) and +1.0 (very active/agitated/energetic).\n"
            f"- dominance: Float value between -1.0 (submissive/helpless) and +1.0 (empowered/dominant/in control)."
        )
        
        # Call Gemini Text API asynchronously in the background
        loop = asyncio.get_event_loop()
        def run_call():
            c = genai.Client(api_key=api_key)
            resp = c.models.generate_content(
                model="gemini-2.5-flash",
                contents=prompt,
                config=types.GenerateContentConfig(
                    response_mime_type="application/json",
                )
            )
            return resp.text
        
        resp_text = await loop.run_in_executor(None, run_call)
        res = json.loads(resp_text)
        
        primary = res.get("primary_emotion", "neutral")
        secondary = res.get("secondary_emotion", "neutral")
        valence = float(res.get("valence", 0.0))
        arousal = float(res.get("arousal", 0.0))
        dominance = float(res.get("dominance", 0.0))
        
        log_utterance(session_id, user_text, model_text, primary, secondary, valence, arousal, dominance)
        print(f"[DEBUG] Logged sentiment for {session_id}: {primary} (Valence: {valence})", flush=True)
    except Exception as e:
        print(f"[ERROR] Sentiment analysis background task failed: {e}", flush=True)

# WEBSOCKET BI-DIRECTIONAL BRIDGE

@app.websocket("/ws/live")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    print("[DEBUG] WebSocket connection accepted.", flush=True)
    
    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        print("[ERROR] GEMINI_API_KEY is not configured.", flush=True)
        await websocket.close(code=1008, reason="GEMINI_API_KEY not configured in .env file.")
        return

    # Extract query params for session RAG tracking
    query_params = websocket.query_params
    article_id = query_params.get("article_id", "general")
    session_id = query_params.get("session_id", "")
    if not session_id:
        session_id = f"session_{uuid.uuid4().hex[:12]}"

    current_user_text = ""
    current_model_text = ""

    # Wait for the client to send the setup configuration
    try:
        setup_data = await websocket.receive_text()
        config_payload = json.loads(setup_data)
        if config_payload.get("type") != "setup":
            print("[ERROR] First message was not setup.", flush=True)
            await websocket.close(code=1008, reason="First message must be setup configurations.")
            return
    except Exception as e:
        print(f"[ERROR] Setup configuration failed: {e}", flush=True)
        await websocket.close(code=1008, reason=f"Setup failed: {e}")
        return

    voice_name = config_payload.get("voice", "Fenrir")
    system_instruction = config_payload.get("system_instruction", "")
    greeting = config_payload.get("greeting", "Hello!")
    document_context = config_payload.get("document_context", "")
    silence_duration_ms = config_payload.get("silence_duration_ms", 1000)

    # Log session connection metadata and geo location
    client_ip = websocket.client.host
    forwarded_for = websocket.headers.get("x-forwarded-for")
    if forwarded_for:
        client_ip = forwarded_for.split(",")[0].strip()
    country, city = get_geoip_location(client_ip)
    log_session(session_id, article_id, voice_name, country, city)

    print(f"[DEBUG] Received setup config. Session: {session_id}, Voice: {voice_name}, Instruction length: {len(system_instruction)}, Context length: {len(document_context)}, VAD Silence: {silence_duration_ms}ms", flush=True)

    client = genai.Client(api_key=api_key)
    state = {"in_tool_call": False}

    # Establish Tools configuration
    tools = [
        types.Tool(
            function_declarations=[
                types.FunctionDeclaration(
                    name="send_editorial_dispute",
                    description=(
                        "Triggers an email notification if a reader reports that a fact "
                        "in the investigative report is wrong, incorrect, or suggests a layout correction."
                    ),
                    parameters=types.Schema(
                        type=types.Type.OBJECT,
                        properties={
                            "original_fact": types.Schema(
                                type=types.Type.STRING,
                                description="The original fact/assertion from the article that the reader disputes."
                            ),
                            "suggested_correction": types.Schema(
                                type=types.Type.STRING,
                                description="The correction or feedback suggested by the reader."
                            )
                        },
                        required=["original_fact", "suggested_correction"]
                    )
                ),
                types.FunctionDeclaration(
                    name="generate_document_note",
                    description=(
                        "Generates a Microsoft Word document note or summary about a specific sub-issue "
                        "within the article or context documents when requested by the user, returning a download link."
                    ),
                    parameters=types.Schema(
                        type=types.Type.OBJECT,
                        properties={
                            "subject": types.Schema(
                                type=types.Type.STRING,
                                description="The subject or topic of the note/summary."
                            ),
                            "content_summary": types.Schema(
                                type=types.Type.STRING,
                                description="A detailed summary of the sub-issue synthesized from the context documents."
                            )
                        },
                        required=["subject", "content_summary"]
                    )
                )
            ]
        )
    ]

    # Append document context to system instructions for RAG grounding in Live API
    if document_context:
        system_instruction += (
            "\n\nSTRICT GROUNDING CONTEXT (RAG KNOWLEDGE BASE):\n"
            "==================================================\n"
            f"{document_context}\n"
            "==================================================\n"
            "You must strictly ground your responses using ONLY the details inside the files/context above."
        )

    # Live Connect Config
    live_config = types.LiveConnectConfig(
        response_modalities=[types.Modality.AUDIO],
        system_instruction=types.Content(
            parts=[types.Part(text=system_instruction)]
        ),
        tools=tools,
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(
                    voice_name=voice_name
                )
            )
        ),
        input_audio_transcription=types.AudioTranscriptionConfig(),
        output_audio_transcription=types.AudioTranscriptionConfig(),
        realtime_input_config=types.RealtimeInputConfig(
            automatic_activity_detection=types.AutomaticActivityDetection(
                silence_duration_ms=silence_duration_ms
            )
        )
    )

    try:
        print("[DEBUG] Connecting to Gemini Live API...", flush=True)
        # Establish persistent Live connection to Gemini Live API
        async with client.aio.live.connect(model=MODEL_ID, config=live_config) as session:
            print("[DEBUG] Connected to Gemini Live API!", flush=True)

            # Bidirectional forwarding loops
            async def receive_from_client():
                """Loop: Receive 16kHz PCM audio bytes from browser and forward to Gemini Live session."""
                nonlocal current_user_text
                try:
                    while True:
                        data = await websocket.receive()
                        if data.get("type") == "websocket.disconnect":
                            print(f"[DEBUG] Client disconnected cleanly (code: {data.get('code', 1000)})", flush=True)
                            raise WebSocketDisconnect(code=data.get("code", 1000))
                        
                        if "bytes" in data:
                            if state["in_tool_call"]:
                                continue
                            # Calculate max amplitude for diagnostics
                            import struct
                            raw_bytes = data["bytes"]
                            max_val = 0
                            if len(raw_bytes) >= 2:
                                count = len(raw_bytes) // 2
                                ints = struct.unpack(f"<{count}h", raw_bytes[:count*2])
                                max_val = max(abs(x) for x in ints)
                            print(f"[DEBUG] Received audio chunk: {len(raw_bytes)} bytes, Max Amp: {max_val}", flush=True)
                            await session.send_realtime_input(
                                audio=types.Blob(
                                    data=raw_bytes,
                                    mime_type="audio/pcm;rate=16000"
                                )
                            )
                        elif "text" in data:
                            if state["in_tool_call"]:
                                print("[DEBUG] Skipping client text input during active tool call.", flush=True)
                                continue
                            print(f"[DEBUG] Received text message from client: {data['text']}", flush=True)
                            msg = json.loads(data["text"])
                            if msg.get("type") == "input_text":
                                current_user_text = msg.get("text", "")
                                await session.send_realtime_input(text=msg["text"])
                            elif msg.get("type") == "audio_stream_end":
                                print("[DEBUG] Client detected end-of-speech (Hybrid VAD). Sending audio_stream_end.", flush=True)
                                await session.send_realtime_input(audio_stream_end=True)
                except WebSocketDisconnect:
                    raise
                except Exception as e:
                    print(f"[DEBUG] Error receiving from client: {e}", flush=True)
                    traceback.print_exc()

            async def send_to_client():
                """Loop: Receive responses/tool calls from Gemini Live session and forward/process them."""
                nonlocal current_user_text, current_model_text
                try:
                    while True:
                        async for response in session.receive():
                            # Handle content output (Audio and Text)
                            if response.server_content is not None:
                                # Forward transcription events
                                if getattr(response.server_content, "input_transcription", None) is not None:
                                    t = response.server_content.input_transcription
                                    if t.text:
                                        current_user_text = t.text
                                    await websocket.send_json({
                                        "type": "input_transcription",
                                        "text": t.text,
                                        "finished": getattr(t, "finished", False)
                                    })
                                if getattr(response.server_content, "interim_input_transcription", None) is not None:
                                    t = response.server_content.interim_input_transcription
                                    await websocket.send_json({
                                        "type": "interim_input_transcription",
                                        "text": t.text,
                                        "finished": getattr(t, "finished", False)
                                    })
                                if getattr(response.server_content, "output_transcription", None) is not None:
                                    t = response.server_content.output_transcription
                                    if t.text:
                                        current_model_text = t.text
                                    await websocket.send_json({
                                        "type": "output_transcription",
                                        "text": t.text,
                                        "finished": getattr(t, "finished", False)
                                    })

                                model_turn = response.server_content.model_turn
                                if model_turn is not None:
                                    for part in model_turn.parts:
                                        if part.inline_data is not None:
                                            # Let client know model is actively speaking audio
                                            await websocket.send_json({"type": "model_speaking", "speaking": True})
                                            # Forward raw 24kHz audio bytes directly
                                            await websocket.send_bytes(part.inline_data.data)
                                        elif part.text:
                                            print(f"[DEBUG] Gemini sent transcript: {part.text}", flush=True)
                                            current_model_text += part.text
                                            # Forward transcript text
                                            await websocket.send_json({
                                                "type": "transcript",
                                                "text": part.text
                                            })
                                
                                # Handle barge-in/interruption
                                if response.server_content.interrupted:
                                    print("[DEBUG] Gemini detected interruption / barge-in.", flush=True)
                                    await websocket.send_json({"type": "model_speaking", "speaking": False})
                                    await websocket.send_json({"type": "interrupted"})

                                # Handle turn complete / generation complete to unmute the microphone
                                if getattr(response.server_content, "generation_complete", False) or getattr(response.server_content, "turn_complete", False):
                                    print("[DEBUG] Gemini generation / turn complete. Unmuting client microphone.", flush=True)
                                    await websocket.send_json({"type": "model_speaking", "speaking": False})
                                    
                                    # Trigger asynchronous sentiment logging
                                    if current_user_text.strip():
                                        asyncio.create_task(
                                            analyze_and_log_sentiment(
                                                session_id=session_id,
                                                user_text=current_user_text,
                                                model_text=current_model_text,
                                                api_key=api_key
                                            )
                                        )
                                        current_user_text = ""
                                        current_model_text = ""

                            # Handle Tool Calls (Editorial Dispute / Document Gen)
                            if response.tool_call is not None:
                                state["in_tool_call"] = True
                                try:
                                    for call in response.tool_call.function_calls:
                                        print(f"[DEBUG] Gemini triggered tool call: {call.name}", flush=True)
                                        if call.name == "send_editorial_dispute":
                                            orig_fact = call.args.get("original_fact", "")
                                            sugg_corr = call.args.get("suggested_correction", "")
                                            
                                            # Execute dispute email
                                            success = send_email_dispute(orig_fact, sugg_corr)
                                            
                                            # Respond to Gemini model
                                            await session.send_tool_response(
                                                function_responses=[
                                                    types.FunctionResponse(
                                                        name=call.name,
                                                        id=call.id,
                                                        response={"success": success}
                                                    )
                                                ]
                                            )
                                            
                                            # Notify client to render alert banner
                                            await websocket.send_json({
                                                "type": "dispute_triggered",
                                                "original_fact": orig_fact,
                                                "suggested_correction": sugg_corr
                                            })

                                        elif call.name == "generate_document_note":
                                            subject = call.args.get("subject", "Research Summary")
                                            content_summary = call.args.get("content_summary", "")
                                            
                                            # Generate docx note
                                            note_id = uuid.uuid4().hex[:8]
                                            filename = f"note_{note_id}.docx"
                                            filepath = os.path.join("static", "notes", filename)
                                            
                                            create_note_docx(subject, content_summary, filepath)
                                            
                                            # Upload to Firebase if initialized
                                            fb_url = upload_to_firebase(filepath, f"notes/{filename}", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                                            if fb_url:
                                                download_url = fb_url
                                            else:
                                                # Construct download link using derived websocket URL
                                                ws_url = str(websocket.url)
                                                http_url = ws_url.replace("wss://", "https://").replace("ws://", "http://")
                                                base_url = http_url.split("/ws/live")[0]
                                                download_url = f"{base_url}/static/notes/{filename}"
                                            
                                            # Respond to Gemini model
                                            await session.send_tool_response(
                                                function_responses=[
                                                    types.FunctionResponse(
                                                        name=call.name,
                                                        id=call.id,
                                                        response={
                                                            "success": True,
                                                            "download_url": download_url
                                                        }
                                                    )
                                                ]
                                            )
                                            
                                            # Notify client to display download button
                                            await websocket.send_json({
                                                "type": "document_ready",
                                                "subject": subject,
                                                "download_url": download_url
                                            })
                                finally:
                                    state["in_tool_call"] = False
                        # Yield control to prevent CPU spinning if session.receive() exits immediately
                        await asyncio.sleep(0.01)

                except WebSocketDisconnect:
                    raise
                except Exception as e:
                    print(f"[DEBUG] Error sending to client: {e}", flush=True)
                    traceback.print_exc()

            # Start listener loops concurrently first so we don't miss the initial response stream
            receive_task = asyncio.create_task(receive_from_client())
            send_task = asyncio.create_task(send_to_client())

            # Trigger the custom greeting message
            greeting_prompt = (
                f"Please greet the user now. Speak out loud exactly this greeting: \"{greeting}\" "
                "Do not add any additional greetings or extra chatter. Immediately ask the user if they want you to read the news article."
            )
            print("[DEBUG] Sending greeting prompt to Gemini...", flush=True)
            # Notify the client that the model is preparing to speak
            await websocket.send_json({"type": "model_speaking", "speaking": True})
            await session.send_client_content(
                turns=types.Content(
                    role="user",
                    parts=[types.Part(text=greeting_prompt)]
                ),
                turn_complete=True
            )

            # Signal the client that setup is complete
            print("[DEBUG] Ready signal sent to client.", flush=True)
            await websocket.send_json({"type": "ready"})

            # Wait for the loops to finish or fail
            done, pending = await asyncio.wait(
                [receive_task, send_task],
                return_when=asyncio.FIRST_COMPLETED
            )
            print(f"[DEBUG] One of the loops completed. Done: {done}", flush=True)
            for task in pending:
                task.cancel()

    except WebSocketDisconnect:
        print("[DEBUG] WebSocketDisconnect propagated to outer scope.", flush=True)
    except Exception as e:
        print(f"[ERROR] Session connection exception: {e}", flush=True)
        traceback.print_exc()
        try:
            await websocket.send_json({"type": "transcript", "text": f"[Error connecting to Gemini Live API: {e}]"})
        except:
            pass
        finally:
            await websocket.close()