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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
"""
FleetMind MCP - Gradio Web Interface
Simple dashboard to interact with the MCP server and database
"""

import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

import gradio as gr
from database.connection import execute_query, execute_write, test_connection
from datetime import datetime, timedelta
import json

# Import chat functionality
from chat.chat_engine import ChatEngine
from chat.conversation import ConversationManager
from chat.geocoding import GeocodingService

# ============================================
# DATABASE FUNCTIONS
# ============================================

def get_database_status():
    """Check if database is connected"""
    try:
        if test_connection():
            return "βœ… Connected", "success"
        else:
            return "❌ Disconnected", "error"
    except Exception as e:
        return f"❌ Error: {str(e)}", "error"


def get_orders_summary():
    """Get summary of orders by status"""
    try:
        query = """
            SELECT
                status,
                COUNT(*) as count
            FROM orders
            GROUP BY status
            ORDER BY count DESC
        """
        results = execute_query(query)

        if not results:
            return "No orders in database"

        summary = "**Orders Summary:**\n\n"
        for row in results:
            summary += f"- {row['status'].upper()}: {row['count']}\n"

        return summary
    except Exception as e:
        return f"Error: {str(e)}"


def get_all_orders():
    """Get all orders from database"""
    try:
        query = """
            SELECT
                order_id,
                customer_name,
                delivery_address,
                status,
                priority,
                created_at
            FROM orders
            ORDER BY created_at DESC
            LIMIT 50
        """
        results = execute_query(query)

        if not results:
            return [["No orders found", "", "", "", "", ""]]

        # Convert to list of lists for Gradio dataframe
        data = []
        for row in results:
            data.append([
                row['order_id'],
                row['customer_name'],
                row['delivery_address'][:50] + "..." if len(row['delivery_address']) > 50 else row['delivery_address'],
                row['status'],
                row['priority'],
                str(row['created_at'])
            ])

        return data
    except Exception as e:
        return [[f"Error: {str(e)}", "", "", "", "", ""]]


def create_sample_order():
    """Create a sample order for testing"""
    try:
        now = datetime.now()
        order_id = f"ORD-{now.strftime('%Y%m%d%H%M%S')}"

        query = """
            INSERT INTO orders (
                order_id, customer_name, customer_phone, customer_email,
                delivery_address, delivery_lat, delivery_lng,
                time_window_start, time_window_end,
                priority, weight_kg, status
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """

        params = (
            order_id,
            "Sample Customer",
            "+1-555-0100",
            "[email protected]",
            "456 Sample Street, San Francisco, CA 94103",
            37.7749,
            -122.4194,
            now + timedelta(hours=2),
            now + timedelta(hours=6),
            "standard",
            10.5,
            "pending"
        )

        execute_write(query, params)
        return f"βœ… Order {order_id} created successfully!", get_all_orders()
    except Exception as e:
        return f"❌ Error: {str(e)}", get_all_orders()


def search_orders(search_term):
    """Search orders by customer name or order ID"""
    try:
        if not search_term:
            return get_all_orders()

        query = """
            SELECT
                order_id,
                customer_name,
                delivery_address,
                status,
                priority,
                created_at
            FROM orders
            WHERE
                order_id ILIKE %s OR
                customer_name ILIKE %s
            ORDER BY created_at DESC
            LIMIT 50
        """

        search_pattern = f"%{search_term}%"
        results = execute_query(query, (search_pattern, search_pattern))

        if not results:
            return [["No matching orders found", "", "", "", "", ""]]

        data = []
        for row in results:
            data.append([
                row['order_id'],
                row['customer_name'],
                row['delivery_address'][:50] + "..." if len(row['delivery_address']) > 50 else row['delivery_address'],
                row['status'],
                row['priority'],
                str(row['created_at'])
            ])

        return data
    except Exception as e:
        return [[f"Error: {str(e)}", "", "", "", "", ""]]


# ============================================
# CHAT FUNCTIONS
# ============================================

# Initialize chat engine and geocoding service
chat_engine = ChatEngine()
geocoding_service = GeocodingService()


def get_api_status():
    """Get API status for chat"""
    # Get full status for all providers
    full_status = chat_engine.get_full_status()
    selected = full_status["selected"]
    claude_status = full_status["claude"]["status"]
    gemini_status = full_status["gemini"]["status"]

    geocoding_status = geocoding_service.get_status()

    # Mark selected provider
    claude_marker = "🎯 **ACTIVE** - " if selected == "anthropic" else ""
    gemini_marker = "🎯 **ACTIVE** - " if selected == "gemini" else ""

    return f"""### API Status

**AI Provider:**

**Claude (Anthropic):**
{claude_marker}{claude_status}

**Gemini (Google):**
{gemini_marker}{gemini_status}

*πŸ’‘ Switch provider by setting `AI_PROVIDER=anthropic` or `AI_PROVIDER=gemini` in .env*

---

**Geocoding:**

**HERE Maps:**
{geocoding_status}
"""


def handle_chat_message(message, conversation_state):
    """
    Handle chat message from user

    Args:
        message: User's message
        conversation_state: ConversationManager instance

    Returns:
        Updated chatbot history, tool display, conversation state
    """
    if not message.strip():
        return conversation_state.get_formatted_history(), conversation_state.get_tool_calls(), conversation_state

    # Process message through chat engine
    response, tool_calls = chat_engine.process_message(message, conversation_state)

    # Return updated UI
    return conversation_state.get_formatted_history(), conversation_state.get_tool_calls(), conversation_state


def reset_conversation():
    """Reset conversation to start fresh"""
    new_conversation = ConversationManager()

    # Add welcome message
    welcome = chat_engine.get_welcome_message()
    new_conversation.add_message("assistant", welcome)

    return (
        new_conversation.get_formatted_history(),
        [],  # Clear tool calls
        new_conversation
    )


def get_initial_chat():
    """Get initial chat state with welcome message"""
    conversation = ConversationManager()
    welcome = chat_engine.get_welcome_message()
    conversation.add_message("assistant", welcome)

    return conversation.get_formatted_history(), [], conversation


# ============================================
# MCP SERVER INFO
# ============================================

def get_mcp_server_info():
    """Get MCP server information"""
    mcp_info = {
        "server_name": "dispatch-coordinator-mcp",
        "version": "1.0.0",
        "status": "Ready",
        "tools": [
            "route_optimizer",
            "geocoder",
            "weather_monitor",
            "traffic_checker",
            "distance_matrix",
            "order_manager"
        ]
    }

    return f"""
### MCP Server Information

**Name:** {mcp_info['server_name']}
**Version:** {mcp_info['version']}
**Status:** 🟒 {mcp_info['status']}

**Available Tools ({len(mcp_info['tools'])}):**
{chr(10).join([f"- {tool}" for tool in mcp_info['tools']])}
"""


# ============================================
# GRADIO INTERFACE
# ============================================

def create_interface():
    """Create the Gradio interface"""

    with gr.Blocks(theme=gr.themes.Soft(), title="FleetMind MCP Dashboard") as app:

        gr.Markdown("# 🚚 FleetMind MCP Dashboard")
        gr.Markdown("*Autonomous Dispatch Coordinator powered by MCP and PostgreSQL*")

        with gr.Tabs():

            # ==========================================
            # TAB 1: OVERVIEW
            # ==========================================
            with gr.Tab("πŸ“Š Overview"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### System Status")
                        db_status = gr.Textbox(
                            label="Database Connection",
                            value=get_database_status()[0],
                            interactive=False
                        )
                        refresh_status_btn = gr.Button("πŸ”„ Refresh Status", size="sm")

                        gr.Markdown("---")
                        orders_summary = gr.Markdown(get_orders_summary())

                    with gr.Column(scale=2):
                        mcp_info = gr.Markdown(get_mcp_server_info())

                # Refresh status button action
                refresh_status_btn.click(
                    fn=lambda: get_database_status()[0],
                    outputs=db_status
                )

            # ==========================================
            # TAB 2: ORDERS MANAGEMENT
            # ==========================================
            with gr.Tab("πŸ“¦ Orders"):
                gr.Markdown("### Orders Management")

                with gr.Row():
                    search_box = gr.Textbox(
                        placeholder="Search by Order ID or Customer Name...",
                        label="Search Orders",
                        scale=3
                    )
                    search_btn = gr.Button("πŸ” Search", scale=1)
                    create_btn = gr.Button("βž• Create Sample Order", scale=1, variant="primary")

                create_result = gr.Textbox(label="Result", visible=False)

                orders_table = gr.Dataframe(
                    headers=["Order ID", "Customer", "Delivery Address", "Status", "Priority", "Created At"],
                    datatype=["str", "str", "str", "str", "str", "str"],
                    label="Orders List",
                    value=get_all_orders(),
                    interactive=False,
                    wrap=True
                )

                refresh_orders_btn = gr.Button("πŸ”„ Refresh Orders")

                # Button actions
                create_btn.click(
                    fn=create_sample_order,
                    outputs=[create_result, orders_table]
                ).then(
                    fn=lambda: gr.update(visible=True),
                    outputs=create_result
                ).then(
                    fn=lambda: get_orders_summary(),
                    outputs=orders_summary
                )

                search_btn.click(
                    fn=search_orders,
                    inputs=search_box,
                    outputs=orders_table
                )

                search_box.submit(
                    fn=search_orders,
                    inputs=search_box,
                    outputs=orders_table
                )

                refresh_orders_btn.click(
                    fn=get_all_orders,
                    outputs=orders_table
                ).then(
                    fn=lambda: get_orders_summary(),
                    outputs=orders_summary
                )

            # ==========================================
            # TAB 3: AI CHAT
            # ==========================================
            with gr.Tab("πŸ’¬ Chat"):
                provider_name = chat_engine.get_provider_name()
                model_name = chat_engine.get_model_name()

                gr.Markdown(f"### AI Order Assistant")
                gr.Markdown(f"*Powered by: **{provider_name}** ({model_name})*")

                # API Status
                api_status = gr.Markdown(get_api_status())

                # Chat interface
                chatbot = gr.Chatbot(
                    label="Order Assistant",
                    height=500,
                    type="messages",
                    show_copy_button=True
                )

                msg_input = gr.Textbox(
                    placeholder="e.g., 'Create an order for John Doe at 123 Main St, deliver by 5 PM'",
                    label="Your Message",
                    lines=2
                )

                with gr.Row():
                    send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=2)
                    clear_btn = gr.Button("πŸ”„ Clear Chat", scale=1)

                # Tool usage display (reasoning transparency)
                with gr.Accordion("πŸ”§ Tool Usage (AI Reasoning)", open=False):
                    gr.Markdown("See what tools the AI is using behind the scenes:")
                    tool_display = gr.JSON(label="Tools Called")

                # Conversation state
                conversation_state = gr.State(value=None)

                # Initialize with welcome message
                chatbot.value, tool_display.value, conversation_state.value = get_initial_chat()

                # Event handlers
                def send_message(message, conv_state):
                    """Handle send button click"""
                    chat_history, tools, new_state = handle_chat_message(message, conv_state)
                    return chat_history, tools, new_state, ""  # Clear input

                send_btn.click(
                    fn=send_message,
                    inputs=[msg_input, conversation_state],
                    outputs=[chatbot, tool_display, conversation_state, msg_input]
                )

                msg_input.submit(
                    fn=send_message,
                    inputs=[msg_input, conversation_state],
                    outputs=[chatbot, tool_display, conversation_state, msg_input]
                )

                clear_btn.click(
                    fn=reset_conversation,
                    outputs=[chatbot, tool_display, conversation_state]
                )

            # ==========================================
            # TAB 4: MCP TOOLS (Coming Soon)
            # ==========================================
            with gr.Tab("πŸ”§ MCP Tools"):
                gr.Markdown("### MCP Tools")
                gr.Markdown("*MCP tool integration coming soon...*")

                gr.Markdown("""
                Available tools:
                - **route_optimizer** - Optimize delivery routes
                - **geocoder** - Convert addresses to coordinates
                - **weather_monitor** - Check weather conditions
                - **traffic_checker** - Monitor traffic conditions
                - **distance_matrix** - Calculate distances
                - **order_manager** - Manage orders via MCP
                """)

            # ==========================================
            # TAB 5: DATABASE INFO
            # ==========================================
            with gr.Tab("πŸ’Ύ Database"):
                gr.Markdown("### Database Information")

                db_info = gr.Markdown(f"""
                **Database:** PostgreSQL
                **Name:** fleetmind
                **Host:** localhost
                **Port:** 5432

                **Tables:**
                - orders (26 columns)
                - drivers (coming soon)
                - assignments (coming soon)
                - exceptions (coming soon)
                """)

                test_db_btn = gr.Button("πŸ§ͺ Test Connection", variant="primary")
                test_result = gr.Textbox(label="Test Result", interactive=False)

                test_db_btn.click(
                    fn=lambda: "βœ… Connection successful!" if test_connection() else "❌ Connection failed",
                    outputs=test_result
                )

        gr.Markdown("---")
        gr.Markdown("*FleetMind MCP v1.0.0 - Built with Gradio, PostgreSQL, and FastMCP*")

    return app


# ============================================
# MAIN
# ============================================

if __name__ == "__main__":
    print("=" * 60)
    print("FleetMind MCP - Starting Gradio Server")
    print("=" * 60)

    # Check database connection
    print("\nChecking database connection...")
    if test_connection():
        print("βœ… Database connected")
    else:
        print("❌ Database connection failed")
        print("Please check your .env file and PostgreSQL server")

    print("\nStarting Gradio interface...")
    print("=" * 60)

    # Create and launch the interface
    app = create_interface()
    app.launch(
        server_name="0.0.0.0",  # Allow external connections for HF Spaces
        server_port=7860,
        share=False,
        show_error=True
    )