File size: 30,767 Bytes
b30f068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Conversational AI Assistant - Streamlit UI
Natural language input β†’ Tool selection β†’ LLM response β†’ User
"""

import streamlit as st
import sys
import time
import logging
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

logger = logging.getLogger("agadvisor.app")

# Cap on characters accepted per chat message β€” bounds LLM cost/DoS on a public Space.
MAX_QUERY_CHARS = 2000

from src.parser import parse_query
from src.tools.tool_matcher import ToolMatcher
from src.tools.tool_executor import ToolExecutor


def _pretty_product(name: str) -> str:
    """Render a normalized catalog product name for display.

    'roundup' -> 'Roundup', '24-d' -> '2,4-D', 'boron' -> 'Boron'.
    """
    special = {"24-d": "2,4-D"}
    if name in special:
        return special[name]
    return name.upper() if len(name) <= 4 else name.title()

# ============================================================================
# PAGE CONFIGURATION
# ============================================================================

st.set_page_config(
    page_title="AgAdvisor",
    page_icon="🌿",
    layout="centered",
    initial_sidebar_state="collapsed"
)

# ============================================================================
# CUSTOM STYLING
# ============================================================================

st.markdown("""
    <style>
    /* Formal, nature-toned palette: muted sage / earth / slate / olive on light
       backgrounds. Badges use light fills with dark text (color-coded but subtle)
       rather than saturated blocks, for a professional look. */
    :root {
        --forest:       #2f6b4f;   /* primary deep sage (titles, accents) */
        --sage:         #4a7c59;
        --sage-soft:    #e4efe7;  --sage-border:  #bcd4c2;
        --earth:        #7a5f2e;
        --earth-soft:   #f2ead8;  --earth-border: #e3d3ad;
        --slate:        #2f5b64;
        --slate-soft:   #e2eef0;  --slate-border: #bcd8dd;
        --olive:        #566234;
        --olive-soft:   #eaeede;  --olive-border: #d3dab9;
        --muted:        #5c6b60;
    }
    .main-title {
        font-size: 2rem;
        font-weight: 600;
        text-align: center;
        color: var(--forest);
        letter-spacing: .2px;
        margin-bottom: .4rem;
    }
    .subtitle {
        text-align: center;
        color: var(--muted);
        font-size: .97rem;
        margin-bottom: 1.6rem;
    }
    .user-message {
        background-color: #eef4f0;
        padding: 15px;
        border-radius: 8px;
        margin: 10px 0;
        border-left: 3px solid var(--sage);
    }
    .assistant-message {
        background-color: #f6f8f5;
        padding: 15px;
        border-radius: 8px;
        margin: 10px 0;
        border-left: 3px solid #9bb58a;
    }
    /* Light, color-coded metadata badges (formal, nature-toned) */
    .tool-badge, .keyword-badge, .confidence-badge, .citation-badge {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 0.82rem;
        font-weight: 600;
        margin: 5px 5px 5px 0;
        border: 1px solid transparent;
    }
    .tool-badge       { background: var(--sage-soft);  color: var(--forest); border-color: var(--sage-border); }
    .keyword-badge    { background: var(--earth-soft); color: var(--earth);  border-color: var(--earth-border); }
    .confidence-badge { background: var(--slate-soft); color: var(--slate);  border-color: var(--slate-border); }
    .citation-badge   { background: var(--olive-soft); color: var(--olive);  border-color: var(--olive-border); }
    /* Chat input: subtle, formal (no bright gradient) */
    .stChatInput {
        border: 1.5px solid #cdddcf !important;
        border-radius: 8px !important;
        background: #fbfdfb !important;
    }
    .stChatInput:focus-within {
        border: 1.5px solid var(--sage) !important;
        box-shadow: 0 0 0 3px rgba(74, 124, 89, 0.12) !important;
    }
    /* Buttons: light sage, formal */
    .stButton > button {
        border: 1px solid var(--sage-border) !important;
        background: #f3f8f4 !important;
        color: var(--forest) !important;
        font-weight: 600 !important;
        border-radius: 8px !important;
    }
    .stButton > button:hover {
        border-color: var(--sage) !important;
        background: var(--sage-soft) !important;
    }
    /* Answer metadata badges: flex-wrap so they never overflow, readable on phone */
    .message-badges {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        align-items: center;
    }
    /* Mobile fix (ISA feedback: star rating clipped on phone). Enlarge and stack
       the badges on narrow screens instead of letting them shrink and clip. */
    @media (max-width: 640px) {
        .message-badges {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
        }
        .tool-badge, .keyword-badge, .confidence-badge, .citation-badge {
            font-size: 0.92rem;
            padding: 6px 12px;
            margin: 0;
            max-width: 100%;
        }
        .main-title { font-size: 1.35rem; }
        .assistant-message, .user-message { padding: 12px; }
    }
    </style>
""", unsafe_allow_html=True)

# ============================================================================
# ACCOUNTS + SHARED RESOURCES  (auth gate must precede chat state)
# ============================================================================
from src.accounts.service import AccountsService
from src.accounts import ui as accounts_ui


@st.cache_resource(show_spinner=False)
def get_accounts_service():
    """One AccountsService per process. On construction it pulls the durable DB
    from the private HF Dataset, so a restarted Space resumes with all accounts."""
    return AccountsService()


@st.cache_resource(show_spinner="Loading models…")
def get_tool_matcher():
    # Shared across all sessions on the Space (was per-session β€” big cold-start win).
    return ToolMatcher()


@st.cache_resource(show_spinner="Loading tools…")
def get_tool_executor():
    return ToolExecutor()


@st.cache_data(show_spinner=False)
def get_label_products():
    try:
        from src.cdms.product_catalog import get_catalog
        return sorted(get_catalog().available_products())
    except Exception:
        return []


# --- Authentication gate: anonymous users see the login screen and stop here ---
accounts = get_accounts_service()
user = accounts_ui.require_auth(accounts)
user_id = user["id"]


def _hydrate_user_chats(svc, uid):
    """Load this user's chats + messages from the durable store into session_state.
    session_state stays the working UI model; every mutation is mirrored to the DB."""
    chats_meta = svc.list_chats(uid)
    if not chats_meta:
        svc.create_chat(uid, "Chat 1")
        chats_meta = svc.list_chats(uid)
    chats = {}
    for c in chats_meta:
        chats[c["id"]] = {
            "name": c["name"],
            "messages": svc.get_messages(c["id"], uid),
            "created_at": c["created_at"],
        }
    st.session_state.chats = chats
    st.session_state.current_chat_id = chats_meta[0]["id"]
    st.session_state.chat_counter = len(chats_meta)
    st.session_state.chats_user_id = uid


# (Re)hydrate on first load this session or when a different user signs in.
if st.session_state.get("chats_user_id") != user_id or "chats" not in st.session_state:
    _hydrate_user_chats(accounts, user_id)

# Shared singletons + catalog (cached; assigned each run for the code below).
st.session_state.tool_matcher = get_tool_matcher()
st.session_state.tool_executor = get_tool_executor()
st.session_state.label_products = get_label_products()

# For backwards compatibility
st.session_state.conversation_history = st.session_state.chats.get(
    st.session_state.current_chat_id, {}
).get('messages', [])

# ============================================================================
# HEADER WITH CHAT CONTROLS
# ============================================================================

# Chat management in header
col_title, col_new_chat = st.columns([4, 1])

with col_title:
    st.markdown('<div class="main-title">🌿 AgAdvisor</div>', unsafe_allow_html=True)

with col_new_chat:
    if st.button("New chat", type="primary", use_container_width=True):
        # Create the chat in the durable store first so we use its real id.
        st.session_state.chat_counter += 1
        new_name = f'Chat {st.session_state.chat_counter}'
        new_chat_id = accounts.create_chat(user_id, new_name)
        st.session_state.chats[new_chat_id] = {
            'name': new_name,
            'messages': [],
            'created_at': time.time()
        }
        st.session_state.current_chat_id = new_chat_id
        st.rerun()

st.markdown(
    '<div class="subtitle">A CDMS pesticide-label assistant with weather, soil, and agronomic tools. Answers include page-level citations.</div>',
    unsafe_allow_html=True
)

# ============================================================================
# EXAMPLE QUESTIONS (MOVED TO TOP)
# ============================================================================

# Example queries section at the top
with st.expander("🌿 Example questions", expanded=False):
    label_products = st.session_state.get('label_products', [])

    st.markdown("**🧭 Tools**")
    col1, col2, col3 = st.columns(3)

    with col1:
        if st.button("🌑️ Weather", use_container_width=True, key="ex_weather"):
            st.session_state.example_input = "What's the weather in London?"

    with col2:
        if st.button("πŸ—ΊοΈ Soil data", use_container_width=True, key="ex_soil"):
            st.session_state.example_input = "Show me soil data for Iowa"

    with col3:
        if st.button("🏷️ Pesticide labels", use_container_width=True, key="ex_cdms"):
            first = _pretty_product(label_products[0]) if label_products else None
            st.session_state.example_input = (
                f"Find the {first} label" if first else "Find a pesticide label"
            )

    # CDMS pesticide labels β€” generated from the products actually in the index.
    st.markdown("**πŸ“‘ Pesticide labels (CDMS)**")
    if label_products:
        shown = label_products[:6]
        for row_start in range(0, len(shown), 3):
            cols = st.columns(3)
            for i, product in enumerate(shown[row_start:row_start + 3]):
                with cols[i]:
                    disp = _pretty_product(product)
                    if st.button(f"πŸ§ͺ {disp}", use_container_width=True, key=f"ex_label_{product}"):
                        st.session_state.example_input = f"Show me the {disp} label"
        st.caption(f"{len(label_products)} label(s) available in the current index.")
    else:
        st.caption("No labels are indexed yet β€” run the offline build to populate the catalog.")

    st.markdown("**πŸ“š Agriculture information**")
    col7, col8, col9 = st.columns(3)

    with col7:
        if st.button("πŸ›‘οΈ Pest control", use_container_width=True, key="ex_pest"):
            st.session_state.example_input = "How to control aphids on tomato plants?"

    with col8:
        if st.button("🌱 Fertilization", use_container_width=True, key="ex_fert"):
            st.session_state.example_input = "Best practices for corn fertilization timing"

    with col9:
        if st.button("πŸƒ Soil health", use_container_width=True, key="ex_soil_health"):
            st.session_state.example_input = "How to improve soil organic matter?"

st.markdown("---")

# Show current chat info
current_chat = st.session_state.chats[st.session_state.current_chat_id]
msg_count = len(current_chat['messages'])
st.caption(f"{current_chat['name']} β€’ {msg_count} messages")

# ============================================================================
# DISPLAY CONVERSATION HISTORY (CHAT-STYLE)
# ============================================================================

# Get messages for current chat
messages = current_chat['messages']

# Create a container for messages (chat window)
chat_container = st.container()

with chat_container:
    if not messages:
        st.info("πŸ‘‹ Welcome! Start a conversation by typing a question below.")
    else:
        # Display messages in chronological order (oldest to newest, like ChatGPT)
        for idx, message in enumerate(messages):
            if message["role"] == "user":
                st.markdown(f"""
                    <div class="user-message">
                        <strong>πŸ‘€ You:</strong><br>
                        {message["content"]}
                    </div>
                """, unsafe_allow_html=True)
            
            else:  # assistant
                st.markdown(f"""
                    <div class="assistant-message">
                        <strong>πŸ€– AgAdvisor:</strong><br>
                        {message["content"]}
                    </div>
                """, unsafe_allow_html=True)
                
                # Show metadata badges
                metadata = message.get("metadata", {})
                if metadata:
                    badges_html = f"""
                        <div class="message-badges" style="margin-top: 10px;">
                            <span class="tool-badge">πŸ”§ {metadata.get('tool', 'Unknown')}</span>
                            <span class="confidence-badge">πŸ“Š {metadata.get('confidence', 0):.0%} confidence</span>
                    """
                    
                    keywords = metadata.get('keywords', [])
                    if keywords:
                        keywords_text = ", ".join(keywords[:3])
                        badges_html += f'<span class="keyword-badge">πŸ”‘ {keywords_text}</span>'
                    
                    # Check for citations
                    raw_data = metadata.get('raw_data', {})
                    if raw_data and 'citations' in raw_data and raw_data.get('citations'):
                        badge_text = "πŸ“š Citations Included"
                        if 'labels' in raw_data:
                            count = len(raw_data.get('labels', []))
                            badge_text = f"πŸ“š {count} Source(s)"
                        elif 'sources' in raw_data:
                            count = len(raw_data.get('sources', []))
                            badge_text = f"πŸ“š {count} Source(s)"
                        badges_html += f'<span class="citation-badge">{badge_text}</span>'
                    
                    badges_html += "</div>"
                    st.markdown(badges_html, unsafe_allow_html=True)

# ============================================================================
# INPUT SECTION (AT BOTTOM, LIKE CHATGPT)
# ============================================================================

# Chat input (like ChatGPT)
user_input = st.chat_input(
    placeholder="Type your message here... e.g., 'Find Roundup label', 'Weather in Paris?', 'How to control aphids?'",
    key="chat_input",
    max_chars=MAX_QUERY_CHARS,  # bound per-message LLM cost / DoS on a public Space
)

# Handle example button clicks
if 'example_input' in st.session_state:
    user_input = st.session_state.example_input
    del st.session_state.example_input

# Defense in depth: normalize + hard-cap anything reaching the LLM (covers example
# injection and clients that bypass the widget's max_chars).
if user_input:
    from src.utils.input_guard import sanitize_user_query
    user_input = sanitize_user_query(user_input, MAX_QUERY_CHARS)

# Process if there's input OR if there's a pending processing task
current_chat = st.session_state.chats[st.session_state.current_chat_id]
has_new_input = user_input is not None and user_input.strip() != ""

# Check for pending processing (after rerun)
pending_processing_key = None
for key in st.session_state.keys():
    if key.startswith(f"processing_{st.session_state.current_chat_id}_"):
        pending_processing_key = key
        break

# ============================================================================
# PROCESS QUERY
# ============================================================================

if has_new_input or pending_processing_key:
    # Get current chat (already have it)
    
    if has_new_input:
        # Per-user daily quota: only signed-in users spend the shared OpenAI key,
        # and each is capped. Block (don't record) once the cap is reached.
        if not accounts.check_quota(user_id):
            st.warning(
                "You've reached today's question limit. Please come back tomorrow."
            )
            st.stop()

        # New input - add user message and set processing flag
        # Use message count before adding to create unique key
        msg_count_before = len(current_chat['messages'])
        processing_key = f"processing_{st.session_state.current_chat_id}_{msg_count_before}"

        # Add user message to current chat (session) and persist to the store.
        current_chat['messages'].append({
            "role": "user",
            "content": user_input,
            "timestamp": time.time()
        })
        accounts.add_message(st.session_state.current_chat_id, user_id, "user", user_input)
        accounts.record_query(user_id)
        st.session_state[processing_key] = user_input
        # Rerun immediately to show user message
        st.rerun()
    else:
        # Pending processing - continue with existing processing key
        processing_key = pending_processing_key
    
    # Get the question to process (from session state)
    question_to_process = st.session_state.get(processing_key, user_input if has_new_input else "")
    
    # Processing with detailed status (like before)
    try:
        with st.status("πŸ€” Processing your question...", expanded=True) as status:
            # Step 1: Parse and extract keywords
            st.write("**Step 1:** πŸ” Analyzing your question...")
            try:
                parsed = parse_query(question_to_process)
                keywords = parsed.get("extracted_keywords", [])
                st.write(f"   βœ… Keywords: {', '.join(keywords[:5])}")
            except Exception:
                st.write("   ⚠️ Using direct matching")
                keywords = []
            
            # Step 2: Get conversation history for context (needed for tool matching)
            st.write("**Step 2:** πŸ”„ Checking conversation context...")
            conversation_context = []
            if len(current_chat['messages']) > 1:  # Has previous messages
                recent_messages = current_chat['messages'][-6:-1]  # Last 5 before current
                for msg in recent_messages:
                    conversation_context.append({
                        "role": msg["role"],
                        "content": msg["content"]
                    })
                st.write(f"   βœ… Using context from {len(conversation_context)} previous messages")
            else:
                st.write("   ℹ️ No previous context")
            
            # Step 3: Match with tools (with context)
            st.write("**Step 3:** 🎯 Selecting best tool...")
            try:
                tool_match = st.session_state.tool_matcher.match_tool(
                    keywords, 
                    question_to_process,
                    conversation_context=conversation_context
                )
                selected_tool = tool_match["tool_name"]
                confidence = tool_match["confidence"]
                method = tool_match.get("method", "unknown")
                llm_used = tool_match.get("llm_used", False)
                
                # Display method used
                if method == "fast_path":
                    st.write("   ⚑ Fast path (keyword matching)")
                elif method == "llm_path" or method == "llm_cached":
                    st.write(f"   🧠 LLM classification ({'cached' if method == 'llm_cached' else 'live'})")
                elif method == "hybrid":
                    st.write("   πŸ”€ Hybrid (fast + LLM)")
                else:
                    st.write(f"   βš™οΈ {method}")
                
                st.write(f"   βœ… Selected: **{selected_tool}** ({confidence:.0%} confidence)")
                
                # Show LLM reasoning if available
                if llm_used and tool_match.get("llm_reasoning"):
                    st.write(f"   πŸ’­ Reasoning: {tool_match['llm_reasoning'][:100]}...")
            except Exception:
                st.write("   ⚠️ Using default tool")
                selected_tool = "cdms_label"  # Default fallback (CDMS is now the RAG tool)
                confidence = 0.3
                method = "fallback"
            
            # Step 4: Execute tool (with conversation context)
            st.write(f"**Step 4:** βš™οΈ Executing **{selected_tool}** tool...")
            try:
                tool_result = st.session_state.tool_executor.execute(
                    tool_name=selected_tool,
                    user_question=question_to_process,
                    conversation_context=conversation_context  # Pass context for follow-ups
                )
                
                # Check if execution was successful
                if not tool_result.get("success", False):
                    error_msg = tool_result.get("error", "Unknown error")
                    tool_result["llm_response"] = f"I encountered an error: {error_msg}"
                    st.write(f"   ❌ Error: {error_msg}")
                else:
                    # Check if fallback was used
                    if tool_result.get("fallback_used"):
                        st.write("   ⚠️ CDMS found no results, using agriculture web search as fallback")
                    else:
                        st.write("   βœ… Tool executed successfully!")
                        
                        # Show PDF download info for CDMS tool
                        if selected_tool in ["cdms_label", "cdms", "pesticide_label"]:
                            raw_data = tool_result.get("raw_data", {})
                            pdfs_downloaded = raw_data.get("pdfs_downloaded", 0)
                            pdfs_indexed = raw_data.get("pdfs_indexed", 0)
                            if pdfs_downloaded > 0:
                                st.write(f"   πŸ“₯ Downloaded {pdfs_downloaded} PDF(s) from CDMS")
                                if pdfs_indexed > 0:
                                    st.write(f"   πŸ“š Indexed {pdfs_indexed} PDF(s) for RAG search")
                                download_info = raw_data.get("download_info", {})
                                downloaded_pdfs = download_info.get("downloaded_pdfs", [])
                                if downloaded_pdfs:
                                    st.write("   πŸ“„ PDFs:")
                                    for pdf in downloaded_pdfs[:3]:  # Show first 3
                                        cached = "cached" if pdf.get("cached") else "new"
                                        st.write(f"      - {pdf.get('filename', 'Unknown')} ({cached})")
                
            except Exception as e:
                logger.exception("Tool execution error")
                tool_result = {
                    "success": False,
                    "error": "tool_execution_error",
                    "llm_response": "I couldn't complete that request due to an internal error. Please try again."
                }
                st.write("   ❌ Execution error (details logged server-side)")
            
            status.update(label="βœ… Complete!", state="complete", expanded=False)
        
        # Add assistant response to current chat
        response_text = tool_result.get("llm_response", "I couldn't process that request. Please try again.")
        
        current_chat['messages'].append({
            "role": "assistant",
            "content": response_text,
            "timestamp": time.time(),
            "metadata": {
                "tool": tool_result.get("tool_used", selected_tool),  # Use actual tool used (may be fallback)
                "original_tool": selected_tool,  # Keep original selection
                "fallback_used": tool_result.get("fallback_used", False),
                "keywords": keywords,
                "confidence": confidence,
                "raw_data": tool_result.get("raw_data"),
                "success": tool_result.get("success", False),
                "error": tool_result.get("error") if not tool_result.get("success") else None,
                "has_context": len(conversation_context) > 0,
                "context_messages": len(conversation_context)
            }
        })

        # Persist the assistant turn (compact metadata only β€” no bulky raw_data).
        accounts.add_message(
            st.session_state.current_chat_id, user_id, "assistant", response_text,
            metadata={
                "tool": tool_result.get("tool_used", selected_tool),
                "confidence": confidence,
                "keywords": keywords[:5] if keywords else [],
                "success": tool_result.get("success", False),
            },
        )

        # Clear processing flag
        if processing_key in st.session_state:
            del st.session_state[processing_key]

        # Rerun to show the new message
        st.rerun()
    
    except Exception as e:
        # SECURITY: never render tracebacks/exception text to end users. Log full
        # detail server-side; show a generic, friendly message in the UI.
        logger.exception("Unexpected error while processing a query")
        st.error("Something went wrong while processing your request. Please try again.")

        # Add error message to current chat
        _err_text = "I ran into an unexpected problem answering that. Please try rephrasing or ask again."
        current_chat['messages'].append({
            "role": "assistant",
            "content": _err_text,
            "timestamp": time.time(),
            "metadata": {
                "tool": "unknown",
                "error": "internal_error"
            }
        })
        accounts.add_message(
            st.session_state.current_chat_id, user_id, "assistant", _err_text,
            metadata={"tool": "unknown", "error": "internal_error"},
        )

        # Clear processing flag (use the one from outer scope)
        if 'processing_key' in locals() and processing_key in st.session_state:
            del st.session_state[processing_key]
        elif pending_processing_key and pending_processing_key in st.session_state:
            del st.session_state[pending_processing_key]
        
        st.rerun()

# Clear chat button moved to sidebar

# ============================================================================
# SIDEBAR - CHAT MANAGEMENT
# ============================================================================

with st.sidebar:
    # Signed-in user + logout + remaining daily quota.
    st.markdown(f"### πŸ‘€ {user['username']}")
    st.caption(f"{accounts.remaining_quota(user_id)} questions left today")
    if st.button("Log out", type="secondary", use_container_width=True, key="logout_btn"):
        accounts_ui.logout(accounts)

    st.markdown("---")
    st.markdown("### Chat sessions")

    # Clear current chat button
    if st.button("Clear current chat", type="secondary", use_container_width=True, key="clear_sidebar"):
        current_chat['messages'] = []
        accounts.clear_messages(st.session_state.current_chat_id, user_id)
        st.rerun()

    st.markdown("---")
    
    # Sort chats by created_at (newest first)
    sorted_chats = sorted(
        st.session_state.chats.items(),
        key=lambda x: x[1]['created_at'],
        reverse=True
    )
    
    # Display all chats
    for chat_id, chat_data in sorted_chats:
        # Count messages
        msg_count = len(chat_data['messages'])
        
        # Get first user message as preview
        preview = "Empty chat"
        if chat_data['messages']:
            first_msg = next(
                (msg for msg in chat_data['messages'] if msg['role'] == 'user'),
                None
            )
            if first_msg:
                preview = first_msg['content'][:30] + "..." if len(first_msg['content']) > 30 else first_msg['content']
        
        # Create button for each chat
        is_current = chat_id == st.session_state.current_chat_id
        button_type = "primary" if is_current else "secondary"
        
        col1, col2 = st.columns([4, 1])
        
        with col1:
            if st.button(
                f"{'●' if is_current else 'β—‹'} {chat_data['name']}\n{preview}\n({msg_count} msgs)",
                key=f"chat_{chat_id}",
                type=button_type,
                use_container_width=True
            ):
                if not is_current:
                    st.session_state.current_chat_id = chat_id
                    st.rerun()
        
        with col2:
            if not is_current and len(st.session_state.chats) > 1:
                if st.button("βœ•", key=f"delete_{chat_id}", help="Delete chat"):
                    accounts.delete_chat(chat_id, user_id)
                    del st.session_state.chats[chat_id]
                    # If we deleted the current chat, switch to another one
                    if st.session_state.current_chat_id == chat_id:
                        st.session_state.current_chat_id = list(st.session_state.chats.keys())[0]
                    st.rerun()
    
    st.markdown("---")
    
    # Debug mode
    st.markdown("### Debug")
    debug_mode = st.checkbox("Show debug info", value=False)
    
    if debug_mode:
        st.markdown("---")
        st.markdown("### Session State")
        current_chat = st.session_state.chats[st.session_state.current_chat_id]
        st.json({
            "total_chats": len(st.session_state.chats),
            "current_chat_id": st.session_state.current_chat_id,
            "current_chat_messages": len(current_chat['messages'])
        })

# ============================================================================
# FOOTER
# ============================================================================

st.markdown("---")
st.markdown("""
    <div style="text-align: center; color: #666; font-size: 0.9rem;">
        Powered by LangGraph, spaCy, OpenAI, Qdrant, and Tavily | 
        CDMS Labels β€’ USDA Soil Data β€’ Real-time Weather β€’ Web Search with Citations
    </div>
""", unsafe_allow_html=True)