File size: 76,740 Bytes
6b7c27c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f305b
6b7c27c
 
 
 
63ff505
 
 
 
6b7c27c
 
 
 
 
 
b338c26
 
d965a0a
6b7c27c
 
 
 
 
63ff505
6b7c27c
 
 
 
 
79f305b
 
 
 
 
 
 
62ca1b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f305b
 
 
 
 
 
 
 
 
 
 
62ca1b3
 
 
 
79f305b
 
 
 
62ca1b3
 
79f305b
 
 
 
 
62ca1b3
 
 
 
 
 
 
 
 
 
 
 
79f305b
 
 
 
 
6b7c27c
 
 
 
 
 
082b2ad
 
6b7c27c
 
a2d87ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b7c27c
 
 
 
 
 
 
 
 
 
 
 
d965a0a
b338c26
d965a0a
 
a2d87ed
d965a0a
a2d87ed
 
 
 
 
 
 
 
d965a0a
 
 
 
 
a2d87ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f305b
 
a2d87ed
f474e49
 
 
79f305b
f474e49
79f305b
b338c26
 
 
 
79f305b
b338c26
 
79f305b
b338c26
 
a2d87ed
79f305b
62ca1b3
 
 
79f305b
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
 
b338c26
d965a0a
 
 
 
6b7c27c
 
 
 
 
 
 
 
79f305b
6b7c27c
 
 
 
 
 
 
79f305b
 
 
 
 
 
 
 
 
 
6b7c27c
 
 
 
79f305b
 
6b7c27c
 
 
79f305b
 
6b7c27c
 
 
 
 
 
 
 
 
 
79f305b
6b7c27c
 
 
 
 
 
 
79f305b
 
 
 
 
 
 
 
 
 
6b7c27c
 
 
 
79f305b
6b7c27c
 
79f305b
 
6b7c27c
 
 
 
 
 
 
 
 
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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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
"""
FleetMind Dispatch Coordinator - MCP Server
Industry-standard Model Context Protocol server for delivery dispatch management

Provides 18 AI tools for order and driver management via standardized MCP protocol.
Compatible with Claude Desktop, Continue, Cline, and all MCP clients.
"""

import os
import sys
import json
import logging
from pathlib import Path
from typing import Literal
from datetime import datetime
from contextvars import ContextVar

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

# Ensure logs directory exists
logs_dir = Path(__file__).parent / 'logs'
logs_dir.mkdir(exist_ok=True)

from fastmcp import FastMCP

# Import existing services (unchanged)
from chat.geocoding import GeocodingService
from database.connection import execute_query, execute_write, test_connection

# Import permission checking
from database.user_context import check_permission, get_required_scope

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(logs_dir / 'fleetmind_mcp.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# ============================================================================
# API KEY EXTRACTION FROM REQUEST
# ============================================================================

# Store API key per request using context variable
_current_api_key: ContextVar[str] = ContextVar('api_key', default=None)

# Session-to-API-key store: maps session_id -> api_key
# This allows tool calls to authenticate using the API key from the SSE connection
_session_auth_store: dict[str, str] = {}

def store_session_api_key(session_id: str, api_key: str):
    """Store API key for a session (called when SSE connection is made)"""
    _session_auth_store[session_id] = api_key
    logger.debug(f"Stored API key for session {session_id[:16]}...")

def get_api_key_from_session(session_id: str) -> str:
    """Get API key from session store"""
    return _session_auth_store.get(session_id)

def cleanup_session(session_id: str):
    """Remove session from store when disconnected"""
    if session_id in _session_auth_store:
        del _session_auth_store[session_id]
        logger.debug(f"Cleaned up session {session_id[:16]}...")

def get_api_key_from_context() -> str:
    """
    Get API key from the current request context.
    This is set by our custom dependencies.
    """
    return _current_api_key.get(None)

def extract_api_key_from_request():
    """
    Extract API key from HTTP request and store in context variable.
    Called at the start of each tool execution.

    Checks multiple sources:
    1. api_key query parameter in current request
    2. session_id query parameter -> lookup in session store
    """
    try:
        from fastmcp.server.dependencies import get_http_request
        request = get_http_request()

        # METHOD 1: Direct api_key in query params
        api_key = request.query_params.get('api_key')
        if api_key:
            _current_api_key.set(api_key)
            logger.debug(f"API key extracted from request: {api_key[:10]}...")
            return api_key

        # METHOD 2: Look up by session_id (for MCP tool calls)
        session_id = request.query_params.get('session_id')
        if session_id:
            api_key = get_api_key_from_session(session_id)
            if api_key:
                _current_api_key.set(api_key)
                logger.debug(f"API key found via session {session_id[:16]}...")
                return api_key
            else:
                logger.debug(f"No API key found for session {session_id[:16]}...")

    except RuntimeError:
        # No HTTP request available (e.g., stdio transport)
        logger.debug("No HTTP request available for API key extraction")
    return None

# ============================================================================
# MCP SERVER INITIALIZATION
# ============================================================================
mcp = FastMCP(
    name="FleetMind Dispatch Coordinator",
    version="1.0.0"
    # Note: request_timeout not supported in FastMCP 2.13.1
    # Timeout handling is done in proxy.py instead
)

# ============================================================================
# FASTMCP AUTHENTICATION MIDDLEWARE
# Uses FastMCP's native middleware system to properly pass user context to tools
# Reference: https://gelembjuk.com/blog/post/authentication-remote-mcp-server-python/
# ============================================================================
try:
    from fastmcp.server.middleware import Middleware, MiddlewareContext
    from fastmcp.exceptions import ToolError

    class ApiKeyAuthMiddleware(Middleware):
        """
        FastMCP middleware for API key authentication.
        Validates API key from request query params and injects user info into context.
        """

        async def on_call_tool(self, context: MiddlewareContext, call_next):
            """Intercept tool calls to validate authentication"""
            try:
                from fastmcp.server.dependencies import get_http_request
                request = get_http_request()

                # Get API key from query params
                api_key = request.query_params.get('api_key')

                # Also check session store if no direct api_key
                if not api_key:
                    session_id = request.query_params.get('session_id')
                    if session_id:
                        api_key = get_api_key_from_session(session_id)

                if api_key:
                    # Validate API key and get user info
                    from database.api_keys import verify_api_key
                    user_info = verify_api_key(api_key)

                    if user_info:
                        # Store user info in context for tools to access
                        context.fastmcp_context.set_state("user_id", user_info['user_id'])
                        context.fastmcp_context.set_state("user_email", user_info['email'])
                        context.fastmcp_context.set_state("user_scopes", user_info.get('scopes', []))
                        context.fastmcp_context.set_state("user_name", user_info.get('name', ''))
                        logger.info(f"βœ… Auth middleware: User {user_info['email']} authenticated")
                        return await call_next(context)
                    else:
                        logger.warning(f"❌ Auth middleware: Invalid API key {api_key[:10]}...")

                # Check SKIP_AUTH for development
                env = os.getenv("ENV") or os.getenv("ENVIRONMENT", "production")
                skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

                if skip_auth and env.lower() != "production":
                    # Development mode - use dev user
                    context.fastmcp_context.set_state("user_id", "dev-user")
                    context.fastmcp_context.set_state("user_email", "dev@fleetmind.local")
                    context.fastmcp_context.set_state("user_scopes", ["admin"])
                    context.fastmcp_context.set_state("user_name", "Development User")
                    logger.warning(f"⚠️ Auth middleware: SKIP_AUTH enabled, using dev user")
                    return await call_next(context)

                # No valid authentication
                raise ToolError("Authentication required. Please provide a valid API key.")

            except ImportError:
                # get_http_request not available (stdio transport)
                logger.debug("Auth middleware: No HTTP request available")
                return await call_next(context)

    # Register the middleware with FastMCP
    mcp.add_middleware(ApiKeyAuthMiddleware())
    logger.info("[Auth] FastMCP ApiKeyAuthMiddleware registered")

except ImportError as e:
    logger.warning(f"[Auth] Could not import FastMCP middleware: {e}")
    logger.warning("[Auth] Falling back to per-tool authentication")

# Initialize shared services
logger.info("Initializing FleetMind MCP Server...")
geocoding_service = GeocodingService()
logger.info(f"Geocoding Service: {geocoding_service.get_status()}")

# Test database connection
try:
    test_connection()
    logger.info("Database: Connected to PostgreSQL")
except Exception as e:
    logger.error(f"Database: Connection failed - {e}")

# ============================================================================
# AUTHENTICATION - API KEY SYSTEM
# ============================================================================

def get_authenticated_user(ctx=None):
    """
    Get authenticated user from multiple sources:
    1. FastMCP Context state (set by middleware) - PREFERRED
    2. HTTP request API key extraction (fallback)
    3. Environment variable (fallback for testing)
    4. SKIP_AUTH bypass (development only)

    Args:
        ctx: Optional FastMCP Context object from tool function

    Returns:
        User info dict with user_id, email, scopes, name or None if not authenticated
    """
    try:
        # METHOD 1: Get user from FastMCP Context state (set by middleware)
        # This is the preferred method when using FastMCP middleware
        if ctx is not None:
            try:
                user_id = ctx.get_state("user_id")
                if user_id:
                    return {
                        'user_id': user_id,
                        'email': ctx.get_state("user_email") or "",
                        'scopes': ctx.get_state("user_scopes") or [],
                        'name': ctx.get_state("user_name") or ""
                    }
            except Exception:
                pass  # Context state not available, try other methods

        # METHOD 2: Extract API key from current HTTP request
        api_key = extract_api_key_from_request()

        # METHOD 3: Fallback to environment variable for testing
        if not api_key:
            api_key = os.getenv("FLEETMIND_API_KEY")
            if api_key:
                logger.debug("Using API key from environment")

        # Validate the API key
        if api_key:
            from database.api_keys import verify_api_key
            user_info = verify_api_key(api_key)
            if user_info:
                logger.info(f"βœ… Authenticated: {user_info['email']} (user_id: {user_info['user_id']})")
                return user_info
            else:
                logger.warning(f"❌ Invalid API key: {api_key[:10]}...")
                return None

        # METHOD 4: Development bypass mode (local testing only)
        # SECURITY: Only allow SKIP_AUTH in development environments
        # Check both ENV and ENVIRONMENT variables for compatibility
        env = os.getenv("ENV") or os.getenv("ENVIRONMENT", "production")
        env = env.lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth:
            if env == "production":
                logger.error("⚠️ SKIP_AUTH is enabled but ENV=production - DENYING access for security")
                return None
            else:
                logger.warning(f"⚠️ SKIP_AUTH enabled in {env} environment - using development user")
                return {
                    'user_id': 'dev-user',
                    'email': 'dev@fleetmind.local',
                    'scopes': ['admin'],
                    'name': 'Development User'
                }

        return None

    except Exception as e:
        logger.error(f"Authentication error: {e}")
        return None

# ============================================================================
# MCP RESOURCES
# ============================================================================

@mcp.resource("orders://all")
def get_orders_resource() -> str:
    """
    Real-time orders dataset for AI context.
    Returns authenticated user's orders from the last 30 days.

    Returns:
        JSON string containing orders array with key fields:
        - order_id, customer_name, delivery_address
        - status, priority, created_at, assigned_driver_id
    """
    try:
        # Authenticate user
        user = get_authenticated_user()
        if not user:
            logger.warning("Resource orders://all - Authentication required")
            return json.dumps({
                "error": "Authentication required",
                "message": "Please provide a valid API key to access orders"
            })

        # Query only this user's orders
        query = """
            SELECT order_id, customer_name, delivery_address,
                   status, priority, created_at, assigned_driver_id
            FROM orders
            WHERE user_id = %s
              AND created_at > NOW() - INTERVAL '30 days'
            ORDER BY created_at DESC
            LIMIT 1000
        """
        orders = execute_query(query, (user['user_id'],))
        logger.info(f"Resource orders://all - User {user['user_id']} retrieved {len(orders) if orders else 0} orders")
        return json.dumps(orders, default=str, indent=2)
    except Exception as e:
        logger.error(f"Resource orders://all failed: {e}")
        return json.dumps({"error": str(e)})


@mcp.resource("drivers://all")
def get_drivers_resource() -> str:
    """
    Real-time drivers dataset for AI context.
    Returns authenticated user's drivers with current locations and status.

    Returns:
        JSON string containing drivers array with key fields:
        - driver_id, name, status, vehicle_type, vehicle_plate
        - current_lat, current_lng, last_location_update
    """
    try:
        # Authenticate user
        user = get_authenticated_user()
        if not user:
            logger.warning("Resource drivers://all - Authentication required")
            return json.dumps({
                "error": "Authentication required",
                "message": "Please provide a valid API key to access drivers"
            })

        # Query only this user's drivers
        query = """
            SELECT driver_id, name, status, vehicle_type, vehicle_plate,
                   current_lat, current_lng, last_location_update
            FROM drivers
            WHERE user_id = %s
            ORDER BY name ASC
        """
        drivers = execute_query(query, (user['user_id'],))
        logger.info(f"Resource drivers://all - User {user['user_id']} retrieved {len(drivers) if drivers else 0} drivers")
        return json.dumps(drivers, default=str, indent=2)
    except Exception as e:
        logger.error(f"Resource drivers://all failed: {e}")
        return json.dumps({"error": str(e)})


# ============================================================================
# MCP PROMPTS (Workflows)
# ============================================================================

# TODO: Add prompts once FastMCP prompt API is confirmed
# Prompts will provide guided workflows for:
# - create_order_workflow: Interactive order creation with validation
# - assign_driver_workflow: Smart driver assignment with route optimization
# - order_status_check: Quick order status queries


# ============================================================================
# MCP TOOLS - ORDER CREATION & VALIDATION
# ============================================================================

@mcp.tool()
def geocode_address(address: str) -> dict:
    """
    Convert a delivery address to GPS coordinates and validate the address format.
    Use this before creating an order to ensure the address is valid.

    Args:
        address: The full delivery address to geocode (e.g., '123 Main St, San Francisco, CA')

    Returns:
        dict: {
            success: bool,
            latitude: float,
            longitude: float,
            formatted_address: str,
            confidence: str (high/medium/low),
            message: str
        }
    """
    from chat.tools import handle_geocode_address
    logger.info(f"Tool: geocode_address('{address}')")
    return handle_geocode_address({"address": address})


@mcp.tool()
def calculate_route(
    origin: str,
    destination: str,
    mode: Literal["driving", "walking", "bicycling", "transit"] = "driving",
    vehicle_type: Literal["car", "van", "truck", "motorcycle", "bicycle"] = "car",
    alternatives: bool = False,
    include_steps: bool = False,
    avoid_tolls: bool = False,
    avoid_highways: bool = False,
    avoid_ferries: bool = False,
    emission_type: Literal["GASOLINE", "ELECTRIC", "HYBRID", "DIESEL"] = "GASOLINE",
    request_fuel_efficient: bool = False
) -> dict:
    """
    Calculate the shortest route between two locations with vehicle-specific optimization.
    Uses Google Routes API for accurate real-time traffic, toll info, and fuel consumption.

    Args:
        origin: Starting location - either full address or coordinates as 'lat,lng'
        destination: Destination location - either full address or coordinates as 'lat,lng'
        mode: Travel mode for route calculation (default: driving)
        vehicle_type: Type of vehicle for route optimization (default: car)
            - motorcycle: Uses TWO_WHEELER mode for motorcycle-specific routing
            - bicycle: Uses bike lanes and paths
            - car/van/truck: Uses DRIVE mode (no truck-specific routing available)
        alternatives: Return multiple route options if available (default: false)
        include_steps: Include turn-by-turn navigation steps in response (default: false)
        avoid_tolls: Avoid toll roads (for cars and motorcycles) (default: false)
        avoid_highways: Avoid highways (for cars and motorcycles) (default: false)
        avoid_ferries: Avoid ferry routes (for cars and motorcycles) (default: false)
        emission_type: Vehicle emission type for eco-routing (cars/vans/trucks only) (default: GASOLINE)
        request_fuel_efficient: Request eco-friendly route alternative (cars/vans/trucks only) (default: false)

    Returns:
        dict: {
            success: bool,
            origin: str,
            destination: str,
            distance: {meters: int, text: str},
            duration: {seconds: int, text: str} (without traffic),
            duration_in_traffic: {seconds: int, text: str} (with traffic),
            traffic_delay: {seconds: int, text: str},
            mode: str,
            vehicle_type: str,
            route_summary: str,
            route_labels: list,
            confidence: str,
            toll_info: {has_tolls: bool, details: str} (if applicable),
            fuel_consumption: {liters: float, text: str} (if DRIVE mode),
            traffic_data_available: bool,
            warning: str (if TWO_WHEELER or BICYCLE mode),
            steps: list (if include_steps=True)
        }
    """
    from chat.tools import handle_calculate_route
    logger.info(f"Tool: calculate_route('{origin}' -> '{destination}', vehicle={vehicle_type}, mode={mode})")
    return handle_calculate_route({
        "origin": origin,
        "destination": destination,
        "mode": mode,
        "vehicle_type": vehicle_type,
        "alternatives": alternatives,
        "include_steps": include_steps,
        "avoid_tolls": avoid_tolls,
        "avoid_highways": avoid_highways,
        "avoid_ferries": avoid_ferries,
        "emission_type": emission_type,
        "request_fuel_efficient": request_fuel_efficient
    })


@mcp.tool()
def calculate_intelligent_route(
    origin: str,
    destination: str,
    vehicle_type: Literal["car", "van", "truck", "motorcycle"] = "car",
    consider_weather: bool = True,
    consider_traffic: bool = True
) -> dict:
    """
    Calculate the optimal route considering real-time traffic, weather conditions, and vehicle type.
    This is an intelligent routing tool that factors in:
    - Real-time traffic delays
    - Weather conditions (rain, visibility, wind)
    - Vehicle-specific capabilities (motorcycle vs car vs truck)
    - Safety warnings and recommendations

    Use this when you need smart routing that accounts for current conditions.

    Args:
        origin: Starting location - either full address or coordinates as 'lat,lng'
        destination: Destination location - either full address or coordinates as 'lat,lng'
        vehicle_type: Type of vehicle for route optimization (default: car)
        consider_weather: Factor in weather conditions (default: true)
        consider_traffic: Factor in real-time traffic (default: true)

    Returns:
        dict: {
            success: bool,
            route: {
                origin: str,
                destination: str,
                distance: {meters: int, text: str},
                vehicle_type: str,
                route_summary: str
            },
            timing: {
                base_duration: {seconds: int, text: str},
                with_traffic: {seconds: int, text: str},
                adjusted_duration: {seconds: int, text: str},
                traffic_delay_percent: int,
                weather_delay_percent: int,
                total_delay_percent: int
            },
            conditions: {
                traffic_status: str (clear|light|moderate|heavy|severe),
                weather_considered: bool
            },
            weather: {
                conditions: str,
                temperature_c: float,
                precipitation_mm: float,
                visibility_m: int,
                impact_severity: str (none|minor|moderate|severe)
            },
            recommendations: list[str],
            warnings: list[str],
            alternatives: list (if available)
        }

    Examples:
        - "Find the best route from SF to Oakland for a motorcycle considering weather"
        - "What's the fastest route from downtown to airport with current traffic?"
        - "Calculate delivery route for a truck from warehouse to customer address"
    """
    from chat.route_optimizer import calculate_intelligent_route as calc_route
    logger.info(f"Tool: calculate_intelligent_route('{origin}' -> '{destination}', vehicle={vehicle_type})")
    return calc_route(origin, destination, vehicle_type, consider_weather, consider_traffic)


@mcp.tool()
def create_order(
    customer_name: str,
    delivery_address: str,
    delivery_lat: float,
    delivery_lng: float,
    expected_delivery_time: str,
    customer_phone: str | None = None,
    customer_email: str | None = None,
    priority: Literal["standard", "express", "urgent"] = "standard",
    weight_kg: float = 5.0,
    special_instructions: str | None = None,
    sla_grace_period_minutes: int = 15,
    time_window_end: str | None = None
) -> dict:
    """
    Create a new delivery order in the database with MANDATORY delivery deadline.

    IMPORTANT: expected_delivery_time is REQUIRED. This is the promised delivery time to the customer.
    Only call this after geocoding the address successfully.

    Args:
        customer_name: Full name of the customer
        delivery_address: Complete delivery address
        delivery_lat: Latitude from geocoding
        delivery_lng: Longitude from geocoding
        expected_delivery_time: REQUIRED - Promised delivery deadline in ISO 8601 format
                               Must be future timestamp. Examples:
                               - '2025-11-15T18:00:00' (6 PM today)
                               - '2025-11-16T12:00:00' (noon tomorrow)
        customer_phone: Customer phone number (optional)
        customer_email: Customer email address (optional)
        priority: Delivery priority level (default: standard)
        weight_kg: Package weight in kilograms (default: 5.0)
        special_instructions: Special delivery instructions (optional)
        sla_grace_period_minutes: Grace period after deadline (default: 15 mins)
                                  Deliveries within grace period marked as 'late' but acceptable
        time_window_end: Legacy field, defaults to expected_delivery_time if not provided

    Returns:
        dict: {
            success: bool,
            order_id: str,
            status: str,
            customer: str,
            address: str,
            expected_delivery: str (new),
            sla_grace_period_minutes: int (new),
            priority: str,
            message: str
        }
    """
    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {
            "success": False,
            "error": "Authentication required. Please login first.",
            "auth_required": True
        }

    # STEP 2: Check permissions
    required_scope = get_required_scope('create_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {
            "success": False,
            "error": f"Permission denied. Required scope: {required_scope}"
        }

    # STEP 3: Execute tool with user_id
    from chat.tools import handle_create_order
    logger.info(f"Tool: create_order by user {user.get('email')} (customer='{customer_name}')")

    return handle_create_order(
        tool_input={
            "customer_name": customer_name,
            "delivery_address": delivery_address,
            "delivery_lat": delivery_lat,
            "delivery_lng": delivery_lng,
            "expected_delivery_time": expected_delivery_time,
            "customer_phone": customer_phone,
            "customer_email": customer_email,
            "priority": priority,
            "weight_kg": weight_kg,
            "special_instructions": special_instructions,
            "sla_grace_period_minutes": sla_grace_period_minutes,
            "time_window_end": time_window_end
        },
        user_id=user['user_id']  # Pass user_id for data isolation
    )


# ============================================================================
# MCP TOOLS - ORDER QUERYING
# ============================================================================

@mcp.tool()
def count_orders(
    status: Literal["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"] | None = None,
    priority: Literal["standard", "express", "urgent"] | None = None,
    payment_status: Literal["pending", "paid", "cod"] | None = None,
    assigned_driver_id: str | None = None,
    is_fragile: bool | None = None,
    requires_signature: bool | None = None,
    requires_cold_storage: bool | None = None
) -> dict:
    """
    Count total orders in the database with optional filters.
    Use this when user asks 'how many orders', 'fetch orders', or wants to know order statistics.

    Args:
        status: Filter by order status (optional)
        priority: Filter by priority level (optional)
        payment_status: Filter by payment status (optional)
        assigned_driver_id: Filter by assigned driver ID (optional)
        is_fragile: Filter fragile packages only (optional)
        requires_signature: Filter orders requiring signature (optional)
        requires_cold_storage: Filter orders requiring cold storage (optional)

    Returns:
        dict: {
            success: bool,
            total: int,
            status_breakdown: dict,
            priority_breakdown: dict,
            message: str
        }
    """
    from chat.tools import handle_count_orders
    logger.info(f"Tool: count_orders(status={status}, priority={priority})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('count_orders')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {}
    if status is not None:
        tool_input["status"] = status
    if priority is not None:
        tool_input["priority"] = priority
    if payment_status is not None:
        tool_input["payment_status"] = payment_status
    if assigned_driver_id is not None:
        tool_input["assigned_driver_id"] = assigned_driver_id
    if is_fragile is not None:
        tool_input["is_fragile"] = is_fragile
    if requires_signature is not None:
        tool_input["requires_signature"] = requires_signature
    if requires_cold_storage is not None:
        tool_input["requires_cold_storage"] = requires_cold_storage
    return handle_count_orders(tool_input, user_id=user['user_id'])


@mcp.tool()
def fetch_orders(
    limit: int = 10,
    offset: int = 0,
    status: Literal["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"] | None = None,
    priority: Literal["standard", "express", "urgent"] | None = None,
    payment_status: Literal["pending", "paid", "cod"] | None = None,
    assigned_driver_id: str | None = None,
    is_fragile: bool | None = None,
    requires_signature: bool | None = None,
    requires_cold_storage: bool | None = None,
    sort_by: Literal["created_at", "priority", "time_window_start"] = "created_at",
    sort_order: Literal["ASC", "DESC"] = "DESC"
) -> dict:
    """
    Fetch orders from the database with optional filters, pagination, and sorting.
    Use after counting to show specific number of orders.

    Args:
        limit: Number of orders to fetch (default: 10, max: 100)
        offset: Number of orders to skip for pagination (default: 0)
        status: Filter by order status (optional)
        priority: Filter by priority level (optional)
        payment_status: Filter by payment status (optional)
        assigned_driver_id: Filter by assigned driver ID (optional)
        is_fragile: Filter fragile packages only (optional)
        requires_signature: Filter orders requiring signature (optional)
        requires_cold_storage: Filter orders requiring cold storage (optional)
        sort_by: Field to sort by (default: created_at)
        sort_order: Sort order (default: DESC for newest first)

    Returns:
        dict: {
            success: bool,
            orders: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_fetch_orders
    logger.info(f"Tool: fetch_orders(limit={limit}, offset={offset}, status={status})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('fetch_orders')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {
        "limit": limit,
        "offset": offset,
        "sort_by": sort_by,
        "sort_order": sort_order
    }
    if status is not None:
        tool_input["status"] = status
    if priority is not None:
        tool_input["priority"] = priority
    if payment_status is not None:
        tool_input["payment_status"] = payment_status
    if assigned_driver_id is not None:
        tool_input["assigned_driver_id"] = assigned_driver_id
    if is_fragile is not None:
        tool_input["is_fragile"] = is_fragile
    if requires_signature is not None:
        tool_input["requires_signature"] = requires_signature
    if requires_cold_storage is not None:
        tool_input["requires_cold_storage"] = requires_cold_storage
    return handle_fetch_orders(tool_input, user_id=user['user_id'])


@mcp.tool()
def get_order_details(order_id: str) -> dict:
    """
    Get complete details of a specific order by order ID.
    Use when user asks 'tell me about order X' or wants detailed information about a specific order.

    Args:
        order_id: The order ID to fetch details for (e.g., 'ORD-20251114163800')

    Returns:
        dict: {
            success: bool,
            order: dict (with all 26 fields),
            message: str
        }
    """
    from chat.tools import handle_get_order_details
    logger.info(f"Tool: get_order_details(order_id='{order_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('get_order_details')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_get_order_details({"order_id": order_id}, user_id=user['user_id'])


@mcp.tool()
def search_orders(search_term: str) -> dict:
    """
    Search for orders by customer name, email, phone, or order ID pattern.
    Use when user provides partial information to find orders.

    Args:
        search_term: Search term to match against customer_name, customer_email, customer_phone, or order_id

    Returns:
        dict: {
            success: bool,
            orders: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_search_orders
    logger.info(f"Tool: search_orders(search_term='{search_term}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('search_orders')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_search_orders({"search_term": search_term}, user_id=user['user_id'])


@mcp.tool()
def get_incomplete_orders(limit: int = 20) -> dict:
    """
    Get all orders that are not yet completed (excludes delivered and cancelled orders).
    Shortcut for finding orders in progress (pending, assigned, in_transit).

    Args:
        limit: Number of orders to fetch (default: 20)

    Returns:
        dict: {
            success: bool,
            orders: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_get_incomplete_orders
    logger.info(f"Tool: get_incomplete_orders(limit={limit})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('get_incomplete_orders')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_get_incomplete_orders({"limit": limit}, user_id=user['user_id'])


# ============================================================================
# MCP TOOLS - ORDER MANAGEMENT
# ============================================================================

@mcp.tool()
def update_order(
    order_id: str,
    customer_name: str | None = None,
    customer_phone: str | None = None,
    customer_email: str | None = None,
    delivery_address: str | None = None,
    delivery_lat: float | None = None,
    delivery_lng: float | None = None,
    status: Literal["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"] | None = None,
    priority: Literal["standard", "express", "urgent"] | None = None,
    special_instructions: str | None = None,
    time_window_end: str | None = None,
    payment_status: Literal["pending", "paid", "cod"] | None = None,
    weight_kg: float | None = None,
    order_value: float | None = None
) -> dict:
    """
    Update an existing order's details. You can update any combination of fields.
    Only provide the fields you want to change. Auto-geocodes if delivery_address updated without coordinates.

    Args:
        order_id: Order ID to update (e.g., 'ORD-20250114123456')
        customer_name: Updated customer name (optional)
        customer_phone: Updated customer phone number (optional)
        customer_email: Updated customer email address (optional)
        delivery_address: Updated delivery address (optional)
        delivery_lat: Updated delivery latitude (required if updating address) (optional)
        delivery_lng: Updated delivery longitude (required if updating address) (optional)
        status: Updated order status (optional)
        priority: Updated priority level (optional)
        special_instructions: Updated special delivery instructions (optional)
        time_window_end: Updated delivery deadline (ISO format datetime) (optional)
        payment_status: Updated payment status (optional)
        weight_kg: Updated package weight in kilograms (optional)
        order_value: Updated order value in currency (optional)

    Returns:
        dict: {
            success: bool,
            order_id: str,
            updated_fields: list[str],
            message: str
        }
    """
    from chat.tools import handle_update_order
    logger.info(f"Tool: update_order(order_id='{order_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('update_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {"order_id": order_id}
    if customer_name is not None:
        tool_input["customer_name"] = customer_name
    if customer_phone is not None:
        tool_input["customer_phone"] = customer_phone
    if customer_email is not None:
        tool_input["customer_email"] = customer_email
    if delivery_address is not None:
        tool_input["delivery_address"] = delivery_address
    if delivery_lat is not None:
        tool_input["delivery_lat"] = delivery_lat
    if delivery_lng is not None:
        tool_input["delivery_lng"] = delivery_lng
    if status is not None:
        tool_input["status"] = status
    if priority is not None:
        tool_input["priority"] = priority
    if special_instructions is not None:
        tool_input["special_instructions"] = special_instructions
    if time_window_end is not None:
        tool_input["time_window_end"] = time_window_end
    if payment_status is not None:
        tool_input["payment_status"] = payment_status
    if weight_kg is not None:
        tool_input["weight_kg"] = weight_kg
    if order_value is not None:
        tool_input["order_value"] = order_value
    return handle_update_order(tool_input, user_id=user['user_id'])


@mcp.tool()
def delete_order(order_id: str, confirm: bool) -> dict:
    """
    Permanently delete an order from the database. This action cannot be undone. Use with caution.

    Args:
        order_id: Order ID to delete (e.g., 'ORD-20250114123456')
        confirm: Must be set to true to confirm deletion

    Returns:
        dict: {
            success: bool,
            order_id: str,
            message: str
        }
    """
    from chat.tools import handle_delete_order
    logger.info(f"Tool: delete_order(order_id='{order_id}', confirm={confirm})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('delete_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_delete_order({"order_id": order_id, "confirm": confirm}, user_id=user['user_id'])


# ============================================================================
# MCP TOOLS - DRIVER CREATION
# ============================================================================

@mcp.tool()
def create_driver(
    name: str,
    vehicle_type: str,
    current_address: str,
    current_lat: float,
    current_lng: float,
    phone: str | None = None,
    email: str | None = None,
    vehicle_plate: str | None = None,
    capacity_kg: float = 1000.0,
    capacity_m3: float = 12.0,
    skills: list[str] | None = None,
    status: Literal["active", "busy", "offline", "unavailable"] = "active"
) -> dict:
    """
    Create a new delivery driver in the database. Use this to onboard new drivers to the fleet.

    Args:
        name: Full name of the driver (REQUIRED)
        vehicle_type: Type of vehicle: van, truck, car, motorcycle (REQUIRED)
        current_address: Driver's current location address, e.g. '123 Main St, New York, NY' (REQUIRED)
        current_lat: Driver's current latitude location (REQUIRED, -90 to 90)
        current_lng: Driver's current longitude location (REQUIRED, -180 to 180)
        phone: Driver phone number (optional)
        email: Driver email address (optional)
        vehicle_plate: Vehicle license plate number (optional)
        capacity_kg: Vehicle cargo capacity in kilograms (default: 1000.0)
        capacity_m3: Vehicle cargo volume in cubic meters (default: 12.0)
        skills: List of driver skills/certifications: refrigerated, medical_certified, fragile_handler, overnight, express_delivery (optional)
        status: Driver status (default: active)

    Returns:
        dict: {
            success: bool,
            driver_id: str,
            name: str,
            status: str,
            vehicle_type: str,
            vehicle_plate: str,
            capacity_kg: float,
            skills: list[str],
            location: {latitude, longitude, address},
            message: str
        }
    """
    from chat.tools import handle_create_driver
    logger.info(f"Tool: create_driver(name='{name}', vehicle_type='{vehicle_type}', address='{current_address}', location=({current_lat}, {current_lng}))")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('create_driver')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_create_driver({
        "name": name,
        "phone": phone,
        "email": email,
        "vehicle_type": vehicle_type,
        "vehicle_plate": vehicle_plate,
        "capacity_kg": capacity_kg,
        "capacity_m3": capacity_m3,
        "skills": skills or [],
        "status": status,
        "current_address": current_address,
        "current_lat": current_lat,
        "current_lng": current_lng
    }, user_id=user['user_id'])


# ============================================================================
# MCP TOOLS - DRIVER QUERYING
# ============================================================================

@mcp.tool()
def count_drivers(
    status: Literal["active", "busy", "offline", "unavailable"] | None = None,
    vehicle_type: str | None = None
) -> dict:
    """
    Count total drivers in the database with optional filters.
    Use this when user asks 'how many drivers', 'show drivers', or wants driver statistics.

    Args:
        status: Filter by driver status (optional)
        vehicle_type: Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)

    Returns:
        dict: {
            success: bool,
            total: int,
            status_breakdown: dict,
            vehicle_breakdown: dict,
            message: str
        }
    """
    from chat.tools import handle_count_drivers
    logger.info(f"Tool: count_drivers(status={status}, vehicle_type={vehicle_type})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('count_drivers')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {}
    if status is not None:
        tool_input["status"] = status
    if vehicle_type is not None:
        tool_input["vehicle_type"] = vehicle_type
    return handle_count_drivers(tool_input, user_id=user['user_id'])


@mcp.tool()
def fetch_drivers(
    limit: int = 10,
    offset: int = 0,
    status: Literal["active", "busy", "offline", "unavailable"] | None = None,
    vehicle_type: str | None = None,
    sort_by: Literal["name", "status", "created_at", "last_location_update"] = "name",
    sort_order: Literal["ASC", "DESC"] = "ASC"
) -> dict:
    """
    Fetch drivers from the database with optional filters, pagination, and sorting.
    Use after counting to show specific number of drivers.

    Args:
        limit: Number of drivers to fetch (default: 10, max: 100)
        offset: Number of drivers to skip for pagination (default: 0)
        status: Filter by driver status (optional)
        vehicle_type: Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)
        sort_by: Field to sort by (default: name)
        sort_order: Sort order (default: ASC for alphabetical)

    Returns:
        dict: {
            success: bool,
            drivers: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_fetch_drivers
    logger.info(f"Tool: fetch_drivers(limit={limit}, offset={offset}, status={status})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('fetch_drivers')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {
        "limit": limit,
        "offset": offset,
        "sort_by": sort_by,
        "sort_order": sort_order
    }
    if status is not None:
        tool_input["status"] = status
    if vehicle_type is not None:
        tool_input["vehicle_type"] = vehicle_type
    return handle_fetch_drivers(tool_input, user_id=user['user_id'])


@mcp.tool()
def get_driver_details(driver_id: str) -> dict:
    """
    Get complete details of a specific driver by driver ID, including current location
    (latitude, longitude, and human-readable address via reverse geocoding), contact info,
    vehicle details, status, and skills. Use when user asks about a driver's location,
    coordinates, position, or any other driver information.

    Args:
        driver_id: The driver ID to fetch details for (e.g., 'DRV-20251114163800')

    Returns:
        dict: {
            success: bool,
            driver: dict (with all fields including reverse-geocoded location address),
            message: str
        }
    """
    from chat.tools import handle_get_driver_details
    logger.info(f"Tool: get_driver_details(driver_id='{driver_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('get_driver_details')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_get_driver_details({"driver_id": driver_id}, user_id=user['user_id'])


@mcp.tool()
def search_drivers(search_term: str) -> dict:
    """
    Search for drivers by name, email, phone, vehicle plate, or driver ID pattern.
    Use when user provides partial information to find drivers.

    Args:
        search_term: Search term to match against name, email, phone, vehicle_plate, or driver_id

    Returns:
        dict: {
            success: bool,
            drivers: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_search_drivers
    logger.info(f"Tool: search_drivers(search_term='{search_term}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('search_drivers')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_search_drivers({"search_term": search_term}, user_id=user['user_id'])


@mcp.tool()
def get_available_drivers(limit: int = 20) -> dict:
    """
    Get all drivers that are available for assignment (active or offline status, excludes busy and unavailable).
    Shortcut for finding drivers ready for dispatch.

    Args:
        limit: Number of drivers to fetch (default: 20)

    Returns:
        dict: {
            success: bool,
            drivers: list[dict],
            count: int,
            message: str
        }
    """
    from chat.tools import handle_get_available_drivers
    logger.info(f"Tool: get_available_drivers(limit={limit})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('get_available_drivers')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_get_available_drivers({"limit": limit}, user_id=user['user_id'])


# ============================================================================
# MCP TOOLS - DRIVER MANAGEMENT
# ============================================================================

@mcp.tool()
def update_driver(
    driver_id: str,
    name: str | None = None,
    phone: str | None = None,
    email: str | None = None,
    status: Literal["active", "busy", "offline", "unavailable"] | None = None,
    vehicle_type: str | None = None,
    vehicle_plate: str | None = None,
    capacity_kg: float | None = None,
    capacity_m3: float | None = None,
    skills: list[str] | None = None,
    current_address: str | None = None,
    current_lat: float | None = None,
    current_lng: float | None = None
) -> dict:
    """
    Update an existing driver's details. You can update any combination of fields.
    Only provide the fields you want to change. Auto-updates last_location_update if coordinates changed.

    Args:
        driver_id: Driver ID to update (e.g., 'DRV-20250114123456')
        name: Updated driver name (optional)
        phone: Updated phone number (optional)
        email: Updated email address (optional)
        status: Updated driver status (optional)
        vehicle_type: Updated vehicle type (optional)
        vehicle_plate: Updated vehicle license plate (optional)
        capacity_kg: Updated cargo capacity in kilograms (optional)
        capacity_m3: Updated cargo capacity in cubic meters (optional)
        skills: Updated list of driver skills/certifications (optional)
        current_address: Updated current location address (optional)
        current_lat: Updated current latitude (optional)
        current_lng: Updated current longitude (optional)

    Returns:
        dict: {
            success: bool,
            driver_id: str,
            updated_fields: list[str],
            message: str
        }
    """
    from chat.tools import handle_update_driver
    logger.info(f"Tool: update_driver(driver_id='{driver_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('update_driver')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    tool_input = {"driver_id": driver_id}
    if name is not None:
        tool_input["name"] = name
    if phone is not None:
        tool_input["phone"] = phone
    if email is not None:
        tool_input["email"] = email
    if status is not None:
        tool_input["status"] = status
    if vehicle_type is not None:
        tool_input["vehicle_type"] = vehicle_type
    if vehicle_plate is not None:
        tool_input["vehicle_plate"] = vehicle_plate
    if capacity_kg is not None:
        tool_input["capacity_kg"] = capacity_kg
    if capacity_m3 is not None:
        tool_input["capacity_m3"] = capacity_m3
    if skills is not None:
        tool_input["skills"] = skills
    if current_address is not None:
        tool_input["current_address"] = current_address
    if current_lat is not None:
        tool_input["current_lat"] = current_lat
    if current_lng is not None:
        tool_input["current_lng"] = current_lng
    return handle_update_driver(tool_input, user_id=user['user_id'])


@mcp.tool()
def delete_driver(driver_id: str, confirm: bool) -> dict:
    """
    Permanently delete a driver from the database. This action cannot be undone. Use with caution.

    Args:
        driver_id: Driver ID to delete (e.g., 'DRV-20250114123456')
        confirm: Must be set to true to confirm deletion

    Returns:
        dict: {
            success: bool,
            driver_id: str,
            message: str
        }
    """
    from chat.tools import handle_delete_driver
    logger.info(f"Tool: delete_driver(driver_id='{driver_id}', confirm={confirm})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('delete_driver')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_delete_driver({"driver_id": driver_id, "confirm": confirm}, user_id=user['user_id'])


@mcp.tool()
def delete_all_orders(confirm: bool, status: str = None) -> dict:
    """
    Bulk delete all orders (or orders with specific status). DANGEROUS - Use with extreme caution!

    Safety checks:
    - Requires confirm=true
    - Blocks deletion if any active assignments exist
    - Optional status filter to delete only specific statuses

    Args:
        confirm: Must be set to true to confirm bulk deletion
        status: Optional status filter (pending/assigned/in_transit/delivered/failed/cancelled)

    Returns:
        dict: {
            success: bool,
            deleted_count: int,
            message: str
        }
    """
    from chat.tools import handle_delete_all_orders
    logger.info(f"Tool: delete_all_orders(confirm={confirm}, status='{status}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('delete_all_orders')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_delete_all_orders({"confirm": confirm, "status": status}, user_id=user['user_id'])


@mcp.tool()
def delete_all_drivers(confirm: bool, status: str = None) -> dict:
    """
    Bulk delete all drivers (or drivers with specific status). DANGEROUS - Use with extreme caution!

    Safety checks:
    - Requires confirm=true
    - Blocks deletion if ANY assignments exist (due to RESTRICT constraint)
    - Optional status filter to delete only specific statuses

    Args:
        confirm: Must be set to true to confirm bulk deletion
        status: Optional status filter (active/busy/offline/unavailable)

    Returns:
        dict: {
            success: bool,
            deleted_count: int,
            message: str
        }
    """
    from chat.tools import handle_delete_all_drivers
    logger.info(f"Tool: delete_all_drivers(confirm={confirm}, status='{status}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('delete_all_drivers')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_delete_all_drivers({"confirm": confirm, "status": status}, user_id=user['user_id'])


# ============================================================================
# ASSIGNMENT TOOLS
# ============================================================================

@mcp.tool()
def create_assignment(order_id: str, driver_id: str) -> dict:
    """
    Assign an order to a driver. Creates an assignment record with route data from driver location to delivery location.

    Requirements:
    - Order must be in 'pending' status
    - Driver must be in 'active' or 'available' status
    - Order cannot already have an active assignment

    After assignment:
    - Order status changes to 'assigned'
    - Driver status changes to 'busy'
    - Route data (distance, duration, path) is calculated and saved
    - Assignment record is created with all route details

    Args:
        order_id: Order ID to assign (e.g., 'ORD-20250114123456')
        driver_id: Driver ID to assign (e.g., 'DRV-20250114123456')

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            order_id: str,
            driver_id: str,
            route: {
                distance: {meters: int, text: str},
                duration: {seconds: int, text: str},
                route_summary: str,
                driver_start: {lat: float, lng: float},
                delivery_location: {lat: float, lng: float, address: str}
            }
        }
    """
    from chat.tools import handle_create_assignment
    logger.info(f"Tool: create_assignment(order_id='{order_id}', driver_id='{driver_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('create_assignment')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_create_assignment({"order_id": order_id, "driver_id": driver_id}, user_id=user['user_id'])


@mcp.tool()
def auto_assign_order(order_id: str) -> dict:
    """
    Automatically assign order to the nearest available driver (distance + validation based).

    Selection Criteria (Auto Algorithm):
    1. Driver must be 'active' with valid location
    2. Driver vehicle capacity must meet package weight/volume requirements
    3. Driver must have required skills (fragile handling, cold storage, etc.)
    4. Selects nearest driver by real-time route distance

    This is a fixed-rule algorithm that prioritizes proximity while ensuring
    the driver has the necessary capacity and skills for the delivery.

    After assignment:
    - Order status changes to 'assigned'
    - Driver status changes to 'busy'
    - Route data (distance, duration, path) is calculated and saved
    - Assignment record is created with all route details

    Args:
        order_id: Order ID to auto-assign (e.g., 'ORD-20250114123456')

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            method: 'auto_assignment',
            order_id: str,
            driver_id: str,
            driver_name: str,
            driver_phone: str,
            driver_vehicle_type: str,
            selection_reason: str,
            distance_km: float,
            distance_meters: int,
            estimated_duration_minutes: float,
            candidates_evaluated: int,
            suitable_candidates: int,
            route_summary: str,
            estimated_arrival: str
        }
    """
    from chat.tools import handle_auto_assign_order
    logger.info(f"Tool: auto_assign_order(order_id='{order_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('auto_assign_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_auto_assign_order({"order_id": order_id}, user_id=user['user_id'])


@mcp.tool()
def intelligent_assign_order(order_id: str) -> dict:
    """
    Intelligently assign order using Google Gemini 2.0 Flash AI to analyze all parameters and select the best driver.

    Uses Gemini 2.0 Flash (latest model) to evaluate:
    - Order characteristics (priority, weight, fragility, time constraints, value)
    - Driver capabilities (location, capacity, skills, vehicle type)
    - Real-time routing data (distance, traffic delays, tolls)
    - Weather conditions and impact on delivery
    - Complex tradeoffs and optimal matching

    The AI considers multiple factors holistically:
    - Distance efficiency vs skill requirements
    - Capacity utilization vs delivery urgency
    - Traffic conditions vs time constraints
    - Weather safety vs speed requirements
    - Cost efficiency (tolls, fuel) vs customer satisfaction

    Returns assignment with detailed AI reasoning explaining why the
    selected driver is the best match for this specific delivery.

    Requirements:
    - GOOGLE_API_KEY environment variable must be set
    - Order must be in 'pending' status
    - At least one active driver with valid location

    After assignment:
    - Order status changes to 'assigned'
    - Driver status changes to 'busy'
    - Route data (distance, duration, path) is calculated and saved
    - Assignment record is created with all route details
    - AI reasoning is returned for transparency

    Args:
        order_id: Order ID to intelligently assign (e.g., 'ORD-20250114123456')

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            method: 'intelligent_assignment',
            ai_provider: 'Google Gemini 2.0 Flash',
            order_id: str,
            driver_id: str,
            driver_name: str,
            driver_phone: str,
            driver_vehicle_type: str,
            distance_km: float,
            estimated_duration_minutes: float,
            ai_reasoning: {
                primary_factors: [str],
                trade_offs_considered: [str],
                risk_assessment: str,
                decision_summary: str
            },
            confidence_score: float,
            alternatives_considered: [{driver_id: str, reason_not_selected: str}],
            candidates_evaluated: int,
            route_summary: str,
            estimated_arrival: str
        }
    """
    from chat.tools import handle_intelligent_assign_order
    logger.info(f"Tool: intelligent_assign_order(order_id='{order_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('intelligent_assign_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_intelligent_assign_order({"order_id": order_id}, user_id=user['user_id'])


@mcp.tool()
def get_assignment_details(
    assignment_id: str = None,
    order_id: str = None,
    driver_id: str = None
) -> dict:
    """
    Get assignment details by assignment ID, order ID, or driver ID.
    Provide at least one parameter to search.

    Args:
        assignment_id: Assignment ID (e.g., 'ASN-20250114123456')
        order_id: Order ID to find assignments for (e.g., 'ORD-20250114123456')
        driver_id: Driver ID to find assignments for (e.g., 'DRV-20250114123456')

    Returns:
        dict: {
            success: bool,
            assignments: [
                {
                    assignment_id: str,
                    order_id: str,
                    driver_id: str,
                    customer_name: str,
                    driver_name: str,
                    status: str,
                    route_distance_meters: int,
                    route_duration_seconds: int,
                    route_summary: str,
                    driver_start_location: {lat: float, lng: float},
                    delivery_location: {lat: float, lng: float, address: str},
                    estimated_arrival: str,
                    assigned_at: str,
                    updated_at: str
                }
            ]
        }
    """
    from chat.tools import handle_get_assignment_details
    logger.info(f"Tool: get_assignment_details(assignment_id='{assignment_id}', order_id='{order_id}', driver_id='{driver_id}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('get_assignment_details')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_get_assignment_details({
        "assignment_id": assignment_id,
        "order_id": order_id,
        "driver_id": driver_id
    }, user_id=user['user_id'])


@mcp.tool()
def update_assignment(
    assignment_id: str,
    status: str = None,
    actual_arrival: str = None,
    actual_distance_meters: int = None,
    notes: str = None
) -> dict:
    """
    Update assignment status or details.

    Valid status transitions:
    - active β†’ in_progress (driver starts delivery)
    - in_progress β†’ completed (delivery successful)
    - in_progress β†’ failed (delivery failed)
    - active/in_progress β†’ cancelled (assignment cancelled)

    Cascading updates:
    - completed: order status β†’ 'delivered', driver checks for other assignments
    - failed: order status β†’ 'failed', driver checks for other assignments
    - cancelled: order status β†’ 'cancelled', order.assigned_driver_id β†’ NULL, driver β†’ 'active' if no other assignments

    Args:
        assignment_id: Assignment ID to update (e.g., 'ASN-20250114123456')
        status: New status (active, in_progress, completed, failed, cancelled)
        actual_arrival: Actual arrival timestamp (ISO format)
        actual_distance_meters: Actual distance traveled in meters
        notes: Additional notes about the assignment

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            updated_fields: list,
            cascading_actions: list,
            message: str
        }
    """
    from chat.tools import handle_update_assignment
    logger.info(f"Tool: update_assignment(assignment_id='{assignment_id}', status='{status}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('update_assignment')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_update_assignment({
        "assignment_id": assignment_id,
        "status": status,
        "actual_arrival": actual_arrival,
        "actual_distance_meters": actual_distance_meters,
        "notes": notes
    }, user_id=user['user_id'])


@mcp.tool()
def unassign_order(assignment_id: str, confirm: bool = False) -> dict:
    """
    Unassign an order from a driver by deleting the assignment.

    Requirements:
    - Assignment cannot be in 'in_progress' status (must cancel first using update_assignment)
    - Requires confirm=true to proceed

    Effects:
    - Assignment is deleted
    - Order status changes back to 'pending'
    - order.assigned_driver_id is set to NULL
    - Driver status changes to 'active' (if no other assignments)

    Args:
        assignment_id: Assignment ID to unassign (e.g., 'ASN-20250114123456')
        confirm: Must be set to true to confirm unassignment

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            order_id: str,
            driver_id: str,
            message: str
        }
    """
    from chat.tools import handle_unassign_order
    logger.info(f"Tool: unassign_order(assignment_id='{assignment_id}', confirm={confirm})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('unassign_order')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_unassign_order({"assignment_id": assignment_id, "confirm": confirm}, user_id=user['user_id'])


@mcp.tool()
def complete_delivery(
    assignment_id: str,
    confirm: bool,
    actual_distance_meters: int = None,
    notes: str = None
) -> dict:
    """
    Mark a delivery as successfully completed and automatically update driver location to delivery address.

    This is the primary tool for completing deliveries. It handles all necessary updates:
    - Marks assignment as 'completed' with timestamp
    - Updates order status to 'delivered'
    - **Automatically moves driver location to the delivery address**
    - Updates driver status to 'active' (if no other assignments)
    - Records actual distance and notes (optional)

    Requirements:
    - Assignment must be in 'active' or 'in_progress' status
    - Delivery location coordinates must exist
    - Requires confirm=true

    For failed deliveries: Use fail_delivery tool instead.

    Args:
        assignment_id: Assignment ID to complete (e.g., 'ASN-20250114123456')
        confirm: Must be set to true to confirm completion
        actual_distance_meters: Optional actual distance traveled in meters
        notes: Optional completion notes

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            order_id: str,
            driver_id: str,
            customer_name: str,
            driver_name: str,
            completed_at: str (ISO timestamp),
            delivery_location: {lat, lng, address},
            driver_updated: {new_location, location_updated_at},
            cascading_actions: list[str],
            message: str
        }
    """
    from chat.tools import handle_complete_delivery
    logger.info(f"Tool: complete_delivery(assignment_id='{assignment_id}', confirm={confirm})")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('complete_delivery')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_complete_delivery({
        "assignment_id": assignment_id,
        "confirm": confirm,
        "actual_distance_meters": actual_distance_meters,
        "notes": notes
    }, user_id=user['user_id'])


@mcp.tool()
def fail_delivery(
    assignment_id: str,
    current_address: str,
    current_lat: float,
    current_lng: float,
    failure_reason: str,
    confirm: bool,
    notes: str = None
) -> dict:
    """
    Mark a delivery as failed with mandatory driver location and failure reason.

    IMPORTANT: Driver MUST provide their current location (address + GPS coordinates) and a valid failure reason.
    This ensures accurate location tracking and proper failure documentation.

    Handles all necessary updates:
    - Marks assignment as 'failed' with timestamp
    - Updates order status to 'failed'
    - **Updates driver location to the reported current position**
    - Updates driver status to 'active' (if no other assignments)
    - Records structured failure reason and optional notes

    Valid failure reasons:
    - customer_not_available: Customer not present or not reachable
    - wrong_address: Incorrect or invalid delivery address
    - refused_delivery: Customer refused to accept delivery
    - damaged_goods: Package damaged during transit
    - payment_issue: Payment problems (for COD orders)
    - vehicle_breakdown: Driver's vehicle broke down
    - access_restricted: Cannot access delivery location
    - weather_conditions: Severe weather preventing delivery
    - other: Other reasons (provide details in notes)

    Requirements:
    - Assignment must be in 'active' or 'in_progress' status
    - Driver must provide current address and GPS coordinates
    - Must provide a valid failure_reason from the list above
    - Requires confirm=true

    Args:
        assignment_id: Assignment ID to mark as failed (e.g., 'ASN-20250114123456')
        current_address: Driver's current location address (e.g., '123 Main St, New York, NY')
        current_lat: Driver's current latitude (-90 to 90)
        current_lng: Driver's current longitude (-180 to 180)
        failure_reason: Reason for failure (must be from valid list)
        confirm: Must be set to true to confirm failure
        notes: Optional additional details about the failure

    Returns:
        dict: {
            success: bool,
            assignment_id: str,
            order_id: str,
            driver_id: str,
            customer_name: str,
            driver_name: str,
            failed_at: str (ISO timestamp),
            failure_reason: str,
            failure_reason_display: str (human-readable),
            delivery_address: str,
            driver_location: {lat, lng, address, updated_at},
            cascading_actions: list[str],
            message: str
        }
    """
    from chat.tools import handle_fail_delivery
    logger.info(f"Tool: fail_delivery(assignment_id='{assignment_id}', reason='{failure_reason}')")

    # STEP 1: Authenticate user
    user = get_authenticated_user()
    if not user:
        return {"success": False, "error": "Authentication required"}

    # STEP 2: Check permissions
    required_scope = get_required_scope('fail_delivery')
    if not check_permission(user.get('scopes', []), required_scope):
        return {"success": False, "error": "Permission denied"}

    # STEP 3: Execute with user_id
    return handle_fail_delivery({
        "assignment_id": assignment_id,
        "current_address": current_address,
        "current_lat": current_lat,
        "current_lng": current_lng,
        "failure_reason": failure_reason,
        "confirm": confirm,
        "notes": notes
    }, user_id=user['user_id'])


# ============================================================================
# MAIN ENTRY POINT
# ============================================================================

if __name__ == "__main__":
    logger.info("=" * 60)
    logger.info("FleetMind MCP Server v1.0.0")
    logger.info("=" * 60)
    logger.info(f"Geocoding: {geocoding_service.get_status()}")
    logger.info("Tools: 27 tools registered (19 core + 6 assignment + 2 bulk delete)")
    logger.info("Resources: 2 resources available")
    logger.info("Prompts: 3 workflow templates")
    logger.info("Authentication: Multi-tenant API key via URL query params")
    logger.info("Usage: Connect with ?api_key=YOUR_KEY in the SSE URL")
    logger.info("Starting MCP server...")
    mcp.run()