File size: 206,927 Bytes
d69447e
 
 
 
 
d965a0a
d69447e
 
 
 
1ba61d9
d69447e
 
 
 
d3ecfe5
1ba61d9
9b94aa0
d69447e
 
 
1ba61d9
 
 
d69447e
 
 
1ba61d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d500687
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
 
580a4eb
 
 
 
 
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91af657
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d901a6
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba61d9
 
d69447e
 
 
 
 
 
 
 
 
 
 
5769203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba61d9
 
5769203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba61d9
 
 
5769203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba61d9
5769203
1ba61d9
 
5769203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d69447e
 
 
 
a6d2d54
d965a0a
d69447e
 
 
 
79f305b
d965a0a
 
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
a6d2d54
d69447e
 
 
9b94aa0
 
 
 
a6d2d54
d69447e
a6d2d54
 
d69447e
 
a6d2d54
d69447e
 
d3ecfe5
d69447e
d3ecfe5
d69447e
a6d2d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
 
 
 
a6d2d54
d69447e
a6d2d54
d69447e
 
 
 
 
 
 
 
a6d2d54
9b94aa0
d965a0a
 
d69447e
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
d69447e
 
9b94aa0
 
 
 
d69447e
a6d2d54
d965a0a
 
d69447e
 
 
 
a6d2d54
d69447e
 
 
 
 
 
 
a6d2d54
 
d69447e
a6d2d54
d69447e
 
 
 
 
 
 
 
 
d965a0a
d69447e
 
 
 
 
d965a0a
d69447e
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d69447e
 
 
 
a6d2d54
d69447e
 
 
a6d2d54
 
580a4eb
d69447e
 
 
 
 
1ba61d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
580a4eb
 
a6d2d54
 
580a4eb
a6d2d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
a6d2d54
d69447e
 
d3ecfe5
d69447e
d3ecfe5
d69447e
 
 
 
 
580a4eb
d69447e
d965a0a
580a4eb
d69447e
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d69447e
 
 
 
 
 
d965a0a
 
d69447e
 
 
 
 
 
 
 
 
 
580a4eb
d69447e
 
 
 
 
580a4eb
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
d3ecfe5
fb3312c
 
 
d965a0a
fb3312c
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
d965a0a
 
 
fb3312c
 
 
 
 
 
 
d3ecfe5
 
 
fb3312c
1ba61d9
fb3312c
 
1ba61d9
fb3312c
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
d965a0a
fb3312c
 
 
 
 
d965a0a
fb3312c
 
 
 
 
 
d3ecfe5
fb3312c
 
 
 
 
d3ecfe5
 
 
 
 
fb3312c
 
 
 
 
 
 
 
d965a0a
d3ecfe5
d965a0a
d3ecfe5
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
d965a0a
 
 
d3ecfe5
d965a0a
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
d3ecfe5
fb3312c
 
 
d965a0a
fb3312c
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
 
 
fb3312c
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
 
d965a0a
fb3312c
 
d3ecfe5
fb3312c
 
 
 
d3ecfe5
 
 
 
 
fb3312c
 
 
 
 
 
 
 
d965a0a
fb3312c
d3ecfe5
fb3312c
 
 
d965a0a
fb3312c
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
d965a0a
 
 
fb3312c
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
5d901a6
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
d965a0a
fb3312c
 
 
 
 
d965a0a
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
d965a0a
d3ecfe5
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
d965a0a
 
 
d3ecfe5
d965a0a
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
fb3312c
d3ecfe5
fb3312c
 
 
d965a0a
fb3312c
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
fb3312c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
 
 
fb3312c
 
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3312c
d965a0a
fb3312c
 
d965a0a
fb3312c
 
d3ecfe5
fb3312c
 
 
 
d3ecfe5
 
 
 
 
fb3312c
 
d3ecfe5
 
 
 
 
 
fb3312c
 
d3ecfe5
fb3312c
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
d965a0a
d500687
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
d965a0a
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
d965a0a
d500687
79f305b
d965a0a
 
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
d965a0a
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
d965a0a
d500687
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
d500687
a6d2d54
 
d500687
 
 
d965a0a
d500687
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
 
 
 
 
 
d500687
 
 
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
d965a0a
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
d965a0a
d500687
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
d965a0a
 
 
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
d965a0a
d500687
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
 
 
91af657
1ba61d9
91af657
 
 
580a4eb
91af657
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
91af657
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
 
 
 
 
 
 
580a4eb
 
d500687
 
d965a0a
 
 
 
 
 
 
d500687
 
 
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
 
 
 
 
 
 
 
 
d500687
 
 
 
 
580a4eb
 
 
 
 
d500687
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
d965a0a
d500687
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d500687
 
 
 
 
580a4eb
d500687
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
d965a0a
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d500687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ecfe5
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
d965a0a
 
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
d965a0a
 
9b94aa0
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
d965a0a
 
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
d965a0a
 
9b94aa0
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba61d9
 
 
 
 
 
 
 
 
 
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
9b94aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
d965a0a
 
d3ecfe5
 
 
 
d965a0a
d3ecfe5
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
a6d2d54
d3ecfe5
 
 
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d3ecfe5
 
 
 
580a4eb
d3ecfe5
 
 
580a4eb
d3ecfe5
580a4eb
d3ecfe5
a6d2d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ecfe5
 
a6d2d54
 
 
 
d3ecfe5
a6d2d54
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
 
d3ecfe5
 
 
 
 
 
 
 
 
 
a6d2d54
d3ecfe5
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
79f305b
d965a0a
79f305b
 
 
 
 
d965a0a
 
 
 
 
 
 
 
d3ecfe5
 
 
580a4eb
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d3ecfe5
 
580a4eb
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d965a0a
d3ecfe5
 
 
 
a6d2d54
d3ecfe5
 
 
 
d965a0a
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580a4eb
d3ecfe5
 
 
 
580a4eb
d3ecfe5
 
 
580a4eb
d3ecfe5
580a4eb
d3ecfe5
a6d2d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ecfe5
 
a6d2d54
 
 
 
d3ecfe5
a6d2d54
 
 
d3ecfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6d2d54
 
d3ecfe5
 
 
 
580a4eb
d3ecfe5
 
 
580a4eb
d3ecfe5
 
 
 
 
 
 
 
 
 
d69447e
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
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
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
"""
Tool definitions and execution handlers for FleetMind chat
Simulates MCP tools using Claude's tool calling feature
"""

import os
import sys
from pathlib import Path
from datetime import datetime, timedelta
import logging
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError

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

from database.connection import execute_write, execute_query, get_db_connection
from chat.geocoding import GeocodingService, GEOCODING_TIMEOUT
from psycopg2.extras import RealDictCursor

logger = logging.getLogger(__name__)

# Thread pool for running blocking operations (geocoding, external APIs)
_blocking_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="blocking_ops")

# Initialize geocoding service
geocoding_service = GeocodingService()


def safe_geocode(address: str) -> dict:
    """
    Thread-safe geocoding with timeout protection.
    Runs geocoding in a thread pool to prevent blocking the main event loop.

    Args:
        address: Address to geocode

    Returns:
        Geocoding result dict
    """
    try:
        future = _blocking_executor.submit(geocoding_service.geocode, address)
        result = future.result(timeout=GEOCODING_TIMEOUT + 2)
        return result
    except FuturesTimeoutError:
        logger.error(f"Geocoding timed out for: {address}, using mock fallback")
        return geocoding_service._geocode_mock(address)
    except Exception as e:
        logger.error(f"Geocoding failed for {address}: {e}, using mock fallback")
        return geocoding_service._geocode_mock(address)


def safe_reverse_geocode(lat: float, lng: float) -> dict:
    """
    Thread-safe reverse geocoding with timeout protection.
    Runs reverse geocoding in a thread pool to prevent blocking.

    Args:
        lat: Latitude
        lng: Longitude

    Returns:
        Reverse geocoding result dict
    """
    try:
        future = _blocking_executor.submit(geocoding_service.reverse_geocode, lat, lng)
        result = future.result(timeout=GEOCODING_TIMEOUT + 2)
        return result
    except FuturesTimeoutError:
        logger.error(f"Reverse geocoding timed out for ({lat}, {lng}), using mock fallback")
        return geocoding_service._reverse_geocode_mock(lat, lng)
    except Exception as e:
        logger.error(f"Reverse geocoding failed for ({lat}, {lng}): {e}, using mock fallback")
        return geocoding_service._reverse_geocode_mock(lat, lng)

# Tool schemas for Claude
TOOLS_SCHEMA = [
    {
        "name": "geocode_address",
        "description": "Convert a delivery address to GPS coordinates and validate the address format. Use this before creating an order to ensure the address is valid.",
        "input_schema": {
            "type": "object",
            "properties": {
                "address": {
                    "type": "string",
                    "description": "The full delivery address to geocode (e.g., '123 Main St, San Francisco, CA')"
                }
            },
            "required": ["address"]
        }
    },
    {
        "name": "create_order",
        "description": "Create a new delivery order in the database. Only call this after geocoding the address successfully.",
        "input_schema": {
            "type": "object",
            "properties": {
                "customer_name": {
                    "type": "string",
                    "description": "Full name of the customer"
                },
                "customer_phone": {
                    "type": "string",
                    "description": "Customer phone number (optional)"
                },
                "customer_email": {
                    "type": "string",
                    "description": "Customer email address (optional)"
                },
                "delivery_address": {
                    "type": "string",
                    "description": "Full delivery address"
                },
                "delivery_lat": {
                    "type": "number",
                    "description": "Latitude from geocoding"
                },
                "delivery_lng": {
                    "type": "number",
                    "description": "Longitude from geocoding"
                },
                "time_window_end": {
                    "type": "string",
                    "description": "Delivery deadline in ISO format (e.g., '2025-11-13T17:00:00'). If not specified by user, default to 6 hours from now."
                },
                "priority": {
                    "type": "string",
                    "enum": ["standard", "express", "urgent"],
                    "description": "Delivery priority. Default to 'standard' unless user specifies urgent/express."
                },
                "special_instructions": {
                    "type": "string",
                    "description": "Any special delivery instructions (optional)"
                },
                "weight_kg": {
                    "type": "number",
                    "description": "Package weight in kilograms (optional, default to 5.0)"
                }
            },
            "required": ["customer_name", "delivery_address", "delivery_lat", "delivery_lng"]
        }
    },
    {
        "name": "create_driver",
        "description": "Create a new delivery driver in the database. Use this to onboard new drivers to the fleet. Requires driver location (address + coordinates).",
        "input_schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Full name of the driver"
                },
                "phone": {
                    "type": "string",
                    "description": "Driver phone number (optional)"
                },
                "email": {
                    "type": "string",
                    "description": "Driver email address (optional)"
                },
                "vehicle_type": {
                    "type": "string",
                    "description": "Type of vehicle: van, truck, car, motorcycle"
                },
                "vehicle_plate": {
                    "type": "string",
                    "description": "Vehicle license plate number (optional)"
                },
                "current_address": {
                    "type": "string",
                    "description": "Driver's current location address (e.g., '123 Main St, New York, NY')"
                },
                "current_lat": {
                    "type": "number",
                    "description": "Driver's current latitude coordinate"
                },
                "current_lng": {
                    "type": "number",
                    "description": "Driver's current longitude coordinate"
                },
                "capacity_kg": {
                    "type": "number",
                    "description": "Vehicle cargo capacity in kilograms (default: 1000.0)"
                },
                "capacity_m3": {
                    "type": "number",
                    "description": "Vehicle cargo volume in cubic meters (default: 12.0)"
                },
                "skills": {
                    "type": "array",
                    "description": "List of driver skills/certifications: refrigerated, medical_certified, fragile_handler, overnight, express_delivery",
                    "items": {
                        "type": "string"
                    }
                },
                "status": {
                    "type": "string",
                    "enum": ["active", "busy", "offline", "unavailable"],
                    "description": "Driver status (default: active)"
                }
            },
            "required": ["name", "vehicle_type", "current_address", "current_lat", "current_lng"]
        }
    },
    {
        "name": "count_orders",
        "description": "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.",
        "input_schema": {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"],
                    "description": "Filter by order status (optional)"
                },
                "priority": {
                    "type": "string",
                    "enum": ["standard", "express", "urgent"],
                    "description": "Filter by priority level (optional)"
                },
                "payment_status": {
                    "type": "string",
                    "enum": ["pending", "paid", "cod"],
                    "description": "Filter by payment status (optional)"
                },
                "assigned_driver_id": {
                    "type": "string",
                    "description": "Filter by assigned driver ID (optional)"
                },
                "is_fragile": {
                    "type": "boolean",
                    "description": "Filter fragile packages only (optional)"
                },
                "requires_signature": {
                    "type": "boolean",
                    "description": "Filter orders requiring signature (optional)"
                },
                "requires_cold_storage": {
                    "type": "boolean",
                    "description": "Filter orders requiring cold storage (optional)"
                }
            },
            "required": []
        }
    },
    {
        "name": "fetch_orders",
        "description": "Fetch orders from the database with optional filters, pagination, and sorting. Use after counting to show specific number of orders.",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Number of orders to fetch (default: 10, max: 100)"
                },
                "offset": {
                    "type": "integer",
                    "description": "Number of orders to skip for pagination (default: 0)"
                },
                "status": {
                    "type": "string",
                    "enum": ["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"],
                    "description": "Filter by order status (optional)"
                },
                "priority": {
                    "type": "string",
                    "enum": ["standard", "express", "urgent"],
                    "description": "Filter by priority level (optional)"
                },
                "payment_status": {
                    "type": "string",
                    "enum": ["pending", "paid", "cod"],
                    "description": "Filter by payment status (optional)"
                },
                "assigned_driver_id": {
                    "type": "string",
                    "description": "Filter by assigned driver ID (optional)"
                },
                "is_fragile": {
                    "type": "boolean",
                    "description": "Filter fragile packages only (optional)"
                },
                "requires_signature": {
                    "type": "boolean",
                    "description": "Filter orders requiring signature (optional)"
                },
                "requires_cold_storage": {
                    "type": "boolean",
                    "description": "Filter orders requiring cold storage (optional)"
                },
                "sort_by": {
                    "type": "string",
                    "enum": ["created_at", "priority", "time_window_start"],
                    "description": "Field to sort by (default: created_at)"
                },
                "sort_order": {
                    "type": "string",
                    "enum": ["ASC", "DESC"],
                    "description": "Sort order (default: DESC for newest first)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_order_details",
        "description": "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.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {
                    "type": "string",
                    "description": "The order ID to fetch details for (e.g., 'ORD-20251114163800')"
                }
            },
            "required": ["order_id"]
        }
    },
    {
        "name": "search_orders",
        "description": "Search for orders by customer name, email, phone, or order ID pattern. Use when user provides partial information to find orders.",
        "input_schema": {
            "type": "object",
            "properties": {
                "search_term": {
                    "type": "string",
                    "description": "Search term to match against customer_name, customer_email, customer_phone, or order_id"
                }
            },
            "required": ["search_term"]
        }
    },
    {
        "name": "get_incomplete_orders",
        "description": "Get all orders that are not yet completed (excludes delivered and cancelled orders). Shortcut for finding orders in progress (pending, assigned, in_transit).",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Number of orders to fetch (default: 20)"
                }
            },
            "required": []
        }
    },
    {
        "name": "count_drivers",
        "description": "Count total drivers in the database with optional filters. Use this when user asks 'how many drivers', 'show drivers', or wants driver statistics.",
        "input_schema": {
            "type": "object",
            "properties": {
                "status": {
                    "type": "string",
                    "enum": ["active", "busy", "offline", "unavailable"],
                    "description": "Filter by driver status (optional)"
                },
                "vehicle_type": {
                    "type": "string",
                    "description": "Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)"
                }
            },
            "required": []
        }
    },
    {
        "name": "fetch_drivers",
        "description": "Fetch drivers from the database with optional filters, pagination, and sorting. Use after counting to show specific number of drivers.",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Number of drivers to fetch (default: 10, max: 100)"
                },
                "offset": {
                    "type": "integer",
                    "description": "Number of drivers to skip for pagination (default: 0)"
                },
                "status": {
                    "type": "string",
                    "enum": ["active", "busy", "offline", "unavailable"],
                    "description": "Filter by driver status (optional)"
                },
                "vehicle_type": {
                    "type": "string",
                    "description": "Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)"
                },
                "sort_by": {
                    "type": "string",
                    "enum": ["name", "status", "created_at", "last_location_update"],
                    "description": "Field to sort by (default: name)"
                },
                "sort_order": {
                    "type": "string",
                    "enum": ["ASC", "DESC"],
                    "description": "Sort order (default: ASC for alphabetical)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_driver_details",
        "description": "Get complete details of a specific driver by driver ID, including current location (latitude, longitude, and human-readable address), contact info, vehicle details, status, and skills. Use when user asks about a driver's location, coordinates, position, or any other driver information.",
        "input_schema": {
            "type": "object",
            "properties": {
                "driver_id": {
                    "type": "string",
                    "description": "The driver ID to fetch details for (e.g., 'DRV-20251114163800')"
                }
            },
            "required": ["driver_id"]
        }
    },
    {
        "name": "search_drivers",
        "description": "Search for drivers by name, email, phone, vehicle plate, or driver ID pattern. Use when user provides partial information to find drivers.",
        "input_schema": {
            "type": "object",
            "properties": {
                "search_term": {
                    "type": "string",
                    "description": "Search term to match against name, email, phone, vehicle_plate, or driver_id"
                }
            },
            "required": ["search_term"]
        }
    },
    {
        "name": "get_available_drivers",
        "description": "Get all drivers that are available for assignment (active or offline status, excludes busy and unavailable). Shortcut for finding drivers ready for dispatch.",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Number of drivers to fetch (default: 20)"
                }
            },
            "required": []
        }
    },
    {
        "name": "update_order",
        "description": "Update an existing order's details. You can update any combination of fields. Only provide the fields you want to change.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {
                    "type": "string",
                    "description": "Order ID to update (e.g., 'ORD-20250114123456')"
                },
                "customer_name": {
                    "type": "string",
                    "description": "Updated customer name"
                },
                "customer_phone": {
                    "type": "string",
                    "description": "Updated customer phone number"
                },
                "customer_email": {
                    "type": "string",
                    "description": "Updated customer email address"
                },
                "delivery_address": {
                    "type": "string",
                    "description": "Updated delivery address"
                },
                "delivery_lat": {
                    "type": "number",
                    "description": "Updated delivery latitude (required if updating address)"
                },
                "delivery_lng": {
                    "type": "number",
                    "description": "Updated delivery longitude (required if updating address)"
                },
                "status": {
                    "type": "string",
                    "description": "Updated order status",
                    "enum": ["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"]
                },
                "priority": {
                    "type": "string",
                    "description": "Updated priority level",
                    "enum": ["standard", "express", "urgent"]
                },
                "special_instructions": {
                    "type": "string",
                    "description": "Updated special delivery instructions"
                },
                "time_window_end": {
                    "type": "string",
                    "description": "Updated delivery deadline (ISO format datetime)"
                },
                "payment_status": {
                    "type": "string",
                    "description": "Updated payment status",
                    "enum": ["pending", "paid", "cod"]
                },
                "weight_kg": {
                    "type": "number",
                    "description": "Updated package weight in kilograms"
                },
                "order_value": {
                    "type": "number",
                    "description": "Updated order value in currency"
                }
            },
            "required": ["order_id"]
        }
    },
    {
        "name": "delete_order",
        "description": "Permanently delete an order from the database. This action cannot be undone. Use with caution.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {
                    "type": "string",
                    "description": "Order ID to delete (e.g., 'ORD-20250114123456')"
                },
                "confirm": {
                    "type": "boolean",
                    "description": "Must be set to true to confirm deletion"
                }
            },
            "required": ["order_id", "confirm"]
        }
    },
    {
        "name": "update_driver",
        "description": "Update an existing driver's details. You can update any combination of fields. Only provide the fields you want to change.",
        "input_schema": {
            "type": "object",
            "properties": {
                "driver_id": {
                    "type": "string",
                    "description": "Driver ID to update (e.g., 'DRV-20250114123456')"
                },
                "name": {
                    "type": "string",
                    "description": "Updated driver name"
                },
                "phone": {
                    "type": "string",
                    "description": "Updated phone number"
                },
                "email": {
                    "type": "string",
                    "description": "Updated email address"
                },
                "status": {
                    "type": "string",
                    "description": "Updated driver status",
                    "enum": ["active", "busy", "offline", "unavailable"]
                },
                "vehicle_type": {
                    "type": "string",
                    "description": "Updated vehicle type"
                },
                "vehicle_plate": {
                    "type": "string",
                    "description": "Updated vehicle license plate"
                },
                "capacity_kg": {
                    "type": "number",
                    "description": "Updated cargo capacity in kilograms"
                },
                "capacity_m3": {
                    "type": "number",
                    "description": "Updated cargo capacity in cubic meters"
                },
                "skills": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Updated list of driver skills/certifications"
                },
                "current_address": {
                    "type": "string",
                    "description": "Updated current location address (e.g., '123 Main St, New York, NY')"
                },
                "current_lat": {
                    "type": "number",
                    "description": "Updated current latitude"
                },
                "current_lng": {
                    "type": "number",
                    "description": "Updated current longitude"
                }
            },
            "required": ["driver_id"]
        }
    },
    {
        "name": "delete_driver",
        "description": "Permanently delete a driver from the database. This action cannot be undone. Use with caution.",
        "input_schema": {
            "type": "object",
            "properties": {
                "driver_id": {
                    "type": "string",
                    "description": "Driver ID to delete (e.g., 'DRV-20250114123456')"
                },
                "confirm": {
                    "type": "boolean",
                    "description": "Must be set to true to confirm deletion"
                }
            },
            "required": ["driver_id", "confirm"]
        }
    }
]


def execute_tool(tool_name: str, tool_input: dict) -> dict:
    """
    Route tool execution to appropriate handler

    Args:
        tool_name: Name of the tool to execute
        tool_input: Tool input parameters

    Returns:
        Dict with tool execution results
    """
    try:
        if tool_name == "geocode_address":
            return handle_geocode_address(tool_input)
        elif tool_name == "create_order":
            return handle_create_order(tool_input)
        elif tool_name == "create_driver":
            return handle_create_driver(tool_input)
        elif tool_name == "count_orders":
            return handle_count_orders(tool_input)
        elif tool_name == "fetch_orders":
            return handle_fetch_orders(tool_input)
        elif tool_name == "get_order_details":
            return handle_get_order_details(tool_input)
        elif tool_name == "search_orders":
            return handle_search_orders(tool_input)
        elif tool_name == "get_incomplete_orders":
            return handle_get_incomplete_orders(tool_input)
        elif tool_name == "count_drivers":
            return handle_count_drivers(tool_input)
        elif tool_name == "fetch_drivers":
            return handle_fetch_drivers(tool_input)
        elif tool_name == "get_driver_details":
            return handle_get_driver_details(tool_input)
        elif tool_name == "search_drivers":
            return handle_search_drivers(tool_input)
        elif tool_name == "get_available_drivers":
            return handle_get_available_drivers(tool_input)
        elif tool_name == "update_order":
            return handle_update_order(tool_input)
        elif tool_name == "delete_order":
            return handle_delete_order(tool_input)
        elif tool_name == "update_driver":
            return handle_update_driver(tool_input)
        elif tool_name == "delete_driver":
            return handle_delete_driver(tool_input)
        else:
            return {
                "success": False,
                "error": f"Unknown tool: {tool_name}"
            }
    except Exception as e:
        logger.error(f"Tool execution error ({tool_name}): {e}")
        return {
            "success": False,
            "error": str(e)
        }


def handle_geocode_address(tool_input: dict) -> dict:
    """
    Execute geocoding tool

    Args:
        tool_input: Dict with 'address' key

    Returns:
        Geocoding result
    """
    address = tool_input.get("address", "")

    if not address:
        return {
            "success": False,
            "error": "Address is required"
        }

    logger.info(f"Geocoding address: {address}")

    # Use safe_geocode with timeout protection
    result = safe_geocode(address)

    return {
        "success": True,
        "latitude": result["lat"],
        "longitude": result["lng"],
        "formatted_address": result["formatted_address"],
        "confidence": result["confidence"],
        "message": f"Address geocoded successfully ({result['confidence']})"
    }


def handle_calculate_route(tool_input: dict) -> dict:
    """
    Execute route calculation tool

    Args:
        tool_input: Dict with origin, destination, mode, vehicle_type, alternatives, include_steps

    Returns:
        Route calculation result with distance, duration, and optional directions
    """
    import math
    from datetime import datetime

    origin = tool_input.get("origin", "")
    destination = tool_input.get("destination", "")
    mode = tool_input.get("mode", "driving")
    vehicle_type = tool_input.get("vehicle_type", "car")
    alternatives = tool_input.get("alternatives", False)
    include_steps = tool_input.get("include_steps", False)

    if not origin or not destination:
        return {
            "success": False,
            "error": "Both origin and destination are required"
        }

    # Map vehicle type to travel mode
    VEHICLE_TYPE_TO_MODE = {
        "motorcycle": "TWO_WHEELER",  # Use proper TWO_WHEELER mode for motorcycle-specific routing
        "bicycle": "bicycling",
        "car": "driving",
        "van": "driving",
        "truck": "driving"  # Note: No truck-specific routing available in API
    }

    # Override mode if vehicle_type is provided
    if vehicle_type in VEHICLE_TYPE_TO_MODE:
        mode = VEHICLE_TYPE_TO_MODE[vehicle_type]
        logger.info(f"Vehicle type '{vehicle_type}' mapped to mode '{mode}'")

    logger.info(f"Calculating route: {origin}{destination} (mode: {mode}, vehicle: {vehicle_type})")

    # Triple fallback: Routes API → Directions API → Mock
    if geocoding_service.use_mock:
        logger.info("Using mock route calculation (no API key)")
        result = _calculate_route_mock(origin, destination, mode)
    else:
        try:
            # Try Routes API first (recommended, more accurate)
            logger.info("Attempting Routes API (recommended)")
            result = _calculate_route_routes_api(origin, destination, mode, alternatives, include_steps, vehicle_type, tool_input)
        except Exception as e:
            logger.warning(f"Routes API failed: {e}")
            try:
                # Fall back to Directions API (legacy)
                logger.info("Falling back to Directions API (legacy)")
                result = _calculate_route_google(origin, destination, mode, alternatives, include_steps)
            except Exception as e2:
                # Fall back to mock calculation
                logger.error(f"Directions API also failed: {e2}, falling back to mock")
                result = _calculate_route_mock(origin, destination, mode)

    # Add vehicle type to result for use in intelligent routing
    result["vehicle_type"] = vehicle_type

    return result


def _calculate_route_google(origin: str, destination: str, mode: str, alternatives: bool, include_steps: bool) -> dict:
    """Calculate route using Google Maps Directions API"""
    try:
        # Map our mode to Google Maps mode
        mode_mapping = {
            "driving": "driving",
            "walking": "walking",
            "bicycling": "bicycling",
            "transit": "transit"
        }
        gmaps_mode = mode_mapping.get(mode, "driving")

        # Call Google Maps Directions API
        result = geocoding_service.gmaps_client.directions(
            origin=origin,
            destination=destination,
            mode=gmaps_mode,
            alternatives=alternatives,
            departure_time="now"  # Get real-time traffic data
        )

        if not result:
            logger.warning(f"Google Maps Directions API found no routes for: {origin}{destination}")
            return _calculate_route_mock(origin, destination, mode)

        # Get first (best) route
        route = result[0]
        leg = route['legs'][0]  # First leg (direct route)

        # Extract route information
        distance_meters = leg['distance']['value']
        distance_text = leg['distance']['text']
        duration_seconds = leg['duration']['value']
        duration_text = leg['duration']['text']

        # Get traffic-aware duration if available
        duration_in_traffic = leg.get('duration_in_traffic')
        if duration_in_traffic:
            traffic_duration_seconds = duration_in_traffic['value']
            traffic_duration_text = duration_in_traffic['text']
        else:
            traffic_duration_seconds = duration_seconds
            traffic_duration_text = duration_text

        # Get route summary
        route_summary = route.get('summary', 'Via main roads')

        # Prepare response
        response = {
            "success": True,
            "origin": leg['start_address'],
            "destination": leg['end_address'],
            "distance": {
                "meters": distance_meters,
                "text": distance_text
            },
            "duration": {
                "seconds": duration_seconds,
                "text": duration_text
            },
            "duration_in_traffic": {
                "seconds": traffic_duration_seconds,
                "text": traffic_duration_text
            },
            "mode": mode,
            "route_summary": route_summary,
            "confidence": "high (Google Maps API)"
        }

        # Add turn-by-turn steps if requested
        if include_steps and 'steps' in leg:
            steps = []
            for step in leg['steps']:
                steps.append({
                    "instruction": step.get('html_instructions', '').replace('<b>', '').replace('</b>', ''),
                    "distance": step['distance']['text'],
                    "duration": step['duration']['text']
                })
            response["steps"] = steps
            response["total_steps"] = len(steps)

        # Add alternative routes if requested
        if alternatives and len(result) > 1:
            alt_routes = []
            for alt_route in result[1:]:  # Skip first route (already returned)
                alt_leg = alt_route['legs'][0]
                alt_routes.append({
                    "route_summary": alt_route.get('summary', 'Alternative route'),
                    "distance": alt_leg['distance']['text'],
                    "duration": alt_leg['duration']['text']
                })
            response["alternatives"] = alt_routes
            response["alternatives_count"] = len(alt_routes)

        logger.info(f"Route calculated: {distance_text}, {traffic_duration_text}")
        return response

    except Exception as e:
        logger.error(f"Google Maps Directions API error: {e}")
        raise


def _location_to_latlng(location: str) -> dict:
    """
    Convert location (address or coordinates) to lat/lng dict for Routes API

    Args:
        location: Either an address string or "lat,lng" coordinates

    Returns:
        Dict with {"latitude": float, "longitude": float}
    """
    # Check if already in "lat,lng" format
    if ',' in location:
        parts = location.split(',')
        if len(parts) == 2:
            try:
                lat = float(parts[0].strip())
                lng = float(parts[1].strip())
                return {"latitude": lat, "longitude": lng}
            except ValueError:
                pass  # Not valid coordinates, treat as address

    # Geocode the address using safe version with timeout
    geocoded = safe_geocode(location)
    return {
        "latitude": geocoded["lat"],
        "longitude": geocoded["lng"]
    }


def _calculate_route_routes_api(origin: str, destination: str, mode: str, alternatives: bool, include_steps: bool, vehicle_type: str = "car", tool_input: dict = None) -> dict:
    """
    Calculate route using Google Routes API (new, recommended)

    This uses the modern Routes API which provides better accuracy,
    real-time traffic data, vehicle-specific routing, and additional features.

    Args:
        origin: Starting location (address or "lat,lng")
        destination: Ending location (address or "lat,lng")
        mode: Travel mode (driving, walking, bicycling, transit, TWO_WHEELER)
        alternatives: Whether to return alternative routes
        include_steps: Whether to include turn-by-turn directions
        vehicle_type: Vehicle type (motorcycle, bicycle, car, van, truck)
        tool_input: Original tool input dict for route modifiers

    Returns:
        Route calculation result dict with vehicle-specific data
    """
    if tool_input is None:
        tool_input = {}
    import requests
    import re

    try:
        # Convert locations to lat/lng
        origin_latlng = _location_to_latlng(origin)
        dest_latlng = _location_to_latlng(destination)

        # Map travel modes to Routes API format
        mode_mapping = {
            "driving": "DRIVE",
            "walking": "WALK",
            "bicycling": "BICYCLE",
            "transit": "TRANSIT",
            "TWO_WHEELER": "TWO_WHEELER"  # Motorcycle-specific routing
        }
        routes_mode = mode_mapping.get(mode, "DRIVE")

        # Prepare API request
        url = "https://routes.googleapis.com/directions/v2:computeRoutes"

        # Build enhanced field mask for vehicle-specific data
        field_mask_parts = [
            "routes.duration",
            "routes.staticDuration",  # Duration without traffic
            "routes.distanceMeters",
            "routes.polyline.encodedPolyline",
            "routes.legs",
            "routes.description",
            "routes.localizedValues",
            "routes.routeLabels",  # Get route type labels (FUEL_EFFICIENT, etc.)
            "routes.travelAdvisory.speedReadingIntervals",  # Traffic segments
            "routes.travelAdvisory.tollInfo"  # Toll information
        ]

        # Add fuel consumption for DRIVE mode
        if routes_mode == "DRIVE":
            field_mask_parts.append("routes.travelAdvisory.fuelConsumptionMicroliters")

        headers = {
            "Content-Type": "application/json",
            "X-Goog-Api-Key": geocoding_service.google_maps_key,
            "X-Goog-FieldMask": ",".join(field_mask_parts)
        }

        # Build request body
        body = {
            "origin": {
                "location": {
                    "latLng": origin_latlng
                }
            },
            "destination": {
                "location": {
                    "latLng": dest_latlng
                }
            },
            "travelMode": routes_mode,
            "computeAlternativeRoutes": alternatives,
            "languageCode": "en-US",
            "units": "METRIC"
        }

        # Add routing preference only for DRIVE and TWO_WHEELER (not for WALK/BICYCLE)
        if routes_mode in ["DRIVE", "TWO_WHEELER"]:
            body["routingPreference"] = "TRAFFIC_AWARE"

        # Add route modifiers based on vehicle type
        route_modifiers = {}

        # Vehicle emission type for DRIVE mode (cars, vans, trucks)
        if routes_mode == "DRIVE":
            emission_type = tool_input.get("emission_type", "GASOLINE").upper()
            if emission_type in ["GASOLINE", "ELECTRIC", "HYBRID", "DIESEL"]:
                route_modifiers["vehicleInfo"] = {
                    "emissionType": emission_type
                }

        # Avoid options (applicable to DRIVE and TWO_WHEELER)
        if routes_mode in ["DRIVE", "TWO_WHEELER"]:
            if tool_input.get("avoid_tolls", False):
                route_modifiers["avoidTolls"] = True
            if tool_input.get("avoid_highways", False):
                route_modifiers["avoidHighways"] = True
            if tool_input.get("avoid_ferries", False):
                route_modifiers["avoidFerries"] = True

        if route_modifiers:
            body["routeModifiers"] = route_modifiers

        # Add extra computations for enhanced data
        extra_computations = []

        # Traffic data for DRIVE and TWO_WHEELER
        if routes_mode in ["DRIVE", "TWO_WHEELER"]:
            extra_computations.append("TRAFFIC_ON_POLYLINE")

            # Toll information (unless avoiding tolls)
            if not tool_input.get("avoid_tolls", False):
                extra_computations.append("TOLLS")

            # Fuel consumption for DRIVE mode only
            if routes_mode == "DRIVE":
                extra_computations.append("FUEL_CONSUMPTION")

        if extra_computations:
            body["extraComputations"] = extra_computations

        # Request fuel-efficient alternative for DRIVE mode
        if routes_mode == "DRIVE" and tool_input.get("request_fuel_efficient", False):
            body["requestedReferenceRoutes"] = ["FUEL_EFFICIENT"]

        # Make API request
        logger.info(f"Calling Routes API: {origin}{destination} (mode: {routes_mode})")
        response = requests.post(url, headers=headers, json=body, timeout=10)

        if response.status_code != 200:
            logger.error(f"Routes API error: {response.status_code} - {response.text}")
            raise Exception(f"Routes API returned {response.status_code}: {response.text[:200]}")

        data = response.json()

        if not data.get("routes"):
            logger.warning(f"Routes API found no routes for: {origin}{destination}")
            return _calculate_route_google(origin, destination, mode, alternatives, include_steps)

        # Get first (best) route
        route = data["routes"][0]

        # Extract distance
        distance_meters = route.get("distanceMeters", 0)
        if distance_meters >= 1000:
            distance_text = f"{distance_meters/1000:.1f} km"
        else:
            distance_text = f"{distance_meters} m"

        # Helper function to format duration
        def format_duration(seconds):
            hours = seconds // 3600
            minutes = (seconds % 3600) // 60
            if hours > 0:
                return f"{hours} hour{'s' if hours > 1 else ''} {minutes} min{'s' if minutes != 1 else ''}"
            else:
                return f"{minutes} min{'s' if minutes != 1 else ''}"

        # Extract duration WITH traffic (format: "123s" or "123.456s")
        duration_str = route.get("duration", "0s")
        duration_with_traffic_seconds = int(float(re.sub(r'[^\d.]', '', duration_str)))

        # Extract static duration (WITHOUT traffic)
        static_duration_str = route.get("staticDuration", duration_str)
        static_duration_seconds = int(float(re.sub(r'[^\d.]', '', static_duration_str)))

        # Calculate traffic delay
        traffic_delay_seconds = duration_with_traffic_seconds - static_duration_seconds

        # Get route description/summary and labels
        route_summary = route.get("description", "Route via Routes API")
        route_labels = route.get("routeLabels", [])

        # Extract travel advisory information
        travel_advisory = route.get("travelAdvisory", {})

        # Toll information
        toll_info = travel_advisory.get("tollInfo")
        has_tolls = toll_info is not None

        # Fuel consumption (DRIVE mode only)
        fuel_consumption_ml = travel_advisory.get("fuelConsumptionMicroliters")
        fuel_consumption_liters = None
        if fuel_consumption_ml:
            fuel_consumption_liters = float(fuel_consumption_ml) / 1_000_000

        # Traffic segments
        speed_intervals = travel_advisory.get("speedReadingIntervals", [])
        has_traffic_data = len(speed_intervals) > 0

        # Get origin and destination addresses (geocode if needed) - use safe version with timeout
        origin_geocoded = safe_geocode(origin)
        dest_geocoded = safe_geocode(destination)

        # Build enhanced response with vehicle-specific data
        response_data = {
            "success": True,
            "origin": origin_geocoded["formatted_address"],
            "destination": dest_geocoded["formatted_address"],
            "distance": {
                "meters": distance_meters,
                "text": distance_text
            },
            "duration": {
                "seconds": static_duration_seconds,
                "text": format_duration(static_duration_seconds)
            },
            "duration_in_traffic": {
                "seconds": duration_with_traffic_seconds,
                "text": format_duration(duration_with_traffic_seconds)
            },
            "traffic_delay": {
                "seconds": traffic_delay_seconds,
                "text": format_duration(traffic_delay_seconds) if traffic_delay_seconds > 0 else "No delay"
            },
            "mode": mode,
            "vehicle_type": vehicle_type,
            "route_summary": route_summary,
            "route_labels": route_labels,
            "confidence": "high (Routes API with real-time traffic)"
        }

        # Add toll information if available
        if has_tolls:
            response_data["toll_info"] = {
                "has_tolls": True,
                "details": "Toll roads on route"
            }
        else:
            response_data["toll_info"] = {"has_tolls": False}

        # Add fuel consumption if available (DRIVE mode)
        if fuel_consumption_liters is not None:
            response_data["fuel_consumption"] = {
                "liters": round(fuel_consumption_liters, 2),
                "text": f"{fuel_consumption_liters:.2f} L"
            }

        # Add traffic data availability indicator
        if has_traffic_data:
            response_data["traffic_data_available"] = True
            response_data["traffic_segments_count"] = len(speed_intervals)

        # Add beta warnings for specific modes
        if routes_mode == "TWO_WHEELER":
            response_data["warning"] = (
                "Motorcycle routing uses TWO_WHEELER mode (beta). "
                "May occasionally miss clear paths. Billed at higher rate."
            )
        elif routes_mode == "BICYCLE":
            response_data["warning"] = (
                "Bicycle routing is in beta and may occasionally miss clear bike paths."
            )

        # Add turn-by-turn steps if requested
        if include_steps and route.get("legs"):
            steps = []
            for leg in route["legs"]:
                if leg.get("steps"):
                    for step in leg["steps"]:
                        # Routes API has different step format, adapt as needed
                        steps.append({
                            "instruction": step.get("navigationInstruction", {}).get("instructions", "Continue"),
                            "distance": step.get("distanceMeters", 0),
                            "duration": step.get("staticDuration", "0s")
                        })
            if steps:
                response_data["steps"] = steps
                response_data["steps_count"] = len(steps)

        # Add alternative routes if requested and available
        if alternatives and len(data["routes"]) > 1:
            alt_routes = []
            for alt_route in data["routes"][1:]:
                alt_distance = alt_route.get("distanceMeters", 0)
                alt_duration_str = alt_route.get("duration", "0s")
                alt_duration_sec = int(float(re.sub(r'[^\d.]', '', alt_duration_str)))

                alt_hours = alt_duration_sec // 3600
                alt_minutes = (alt_duration_sec % 3600) // 60
                if alt_hours > 0:
                    alt_duration_text = f"{alt_hours} hour{'s' if alt_hours > 1 else ''} {alt_minutes} min"
                else:
                    alt_duration_text = f"{alt_minutes} min"

                alt_routes.append({
                    "route_summary": alt_route.get("description", "Alternative route"),
                    "distance": f"{alt_distance/1000:.1f} km" if alt_distance >= 1000 else f"{alt_distance} m",
                    "duration": alt_duration_text
                })

            response_data["alternatives"] = alt_routes
            response_data["alternatives_count"] = len(alt_routes)

        logger.info(f"Routes API: {distance_text}, {format_duration(duration_with_traffic_seconds)}")
        return response_data

    except Exception as e:
        logger.error(f"Routes API error: {e}")
        raise


# City-specific traffic profiles for realistic routing
CITY_PROFILES = {
    "dhaka": {
        "name": "Dhaka, Bangladesh",
        "peak_speed_kmh": 8,      # 8 km/h during peak hours (7-10 AM, 5-9 PM)
        "offpeak_speed_kmh": 18,  # 18 km/h during off-peak hours
        "night_speed_kmh": 25,    # 25 km/h at night (10 PM - 6 AM)
        "signals_per_km": 4,      # 4 traffic signals per km in urban areas
        "signal_delay_sec": 50,   # 50 seconds average per signal
        "intersection_delay_per_km": 30,  # 30 seconds per km for intersections
        "congestion_multiplier": 2.5,     # Heavy congestion factor
        "keywords": ["dhaka", "bangladesh"]
    },
    "default": {
        "name": "Default Urban Area",
        "peak_speed_kmh": 20,     # 20 km/h during peak hours
        "offpeak_speed_kmh": 30,  # 30 km/h during off-peak hours
        "night_speed_kmh": 40,    # 40 km/h at night
        "signals_per_km": 2,      # 2 traffic signals per km
        "signal_delay_sec": 45,   # 45 seconds average per signal
        "intersection_delay_per_km": 20,  # 20 seconds per km
        "congestion_multiplier": 1.5,     # Moderate congestion
        "keywords": []
    }
}


def _calculate_route_mock(origin: str, destination: str, mode: str) -> dict:
    """Mock route calculation with realistic urban traffic modeling"""
    import math
    from datetime import datetime

    # Try to geocode both locations to get coordinates (using safe version)
    try:
        origin_geocoded = safe_geocode(origin)
        dest_geocoded = safe_geocode(destination)

        origin_lat = origin_geocoded["lat"]
        origin_lng = origin_geocoded["lng"]
        dest_lat = dest_geocoded["lat"]
        dest_lng = dest_geocoded["lng"]

        # Detect city from destination address
        dest_address_lower = dest_geocoded["formatted_address"].lower()
        city_profile = CITY_PROFILES["default"]
        for city_key, profile in CITY_PROFILES.items():
            if city_key != "default":
                for keyword in profile["keywords"]:
                    if keyword in dest_address_lower:
                        city_profile = profile
                        logger.info(f"Detected city: {profile['name']}")
                        break
                if city_profile != CITY_PROFILES["default"]:
                    break

        # Detect time of day
        current_hour = datetime.now().hour
        if 7 <= current_hour < 10 or 17 <= current_hour < 21:
            time_period = "peak"
            speed_kmh = city_profile["peak_speed_kmh"]
        elif 22 <= current_hour or current_hour < 6:
            time_period = "night"
            speed_kmh = city_profile["night_speed_kmh"]
        else:
            time_period = "offpeak"
            speed_kmh = city_profile["offpeak_speed_kmh"]

        logger.info(f"Time period: {time_period}, base speed: {speed_kmh} km/h")

        # Calculate straight-line distance using Haversine formula
        R = 6371000  # Earth radius in meters

        phi1 = math.radians(origin_lat)
        phi2 = math.radians(dest_lat)
        delta_phi = math.radians(dest_lat - origin_lat)
        delta_lambda = math.radians(dest_lng - origin_lng)

        a = math.sin(delta_phi/2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda/2)**2
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))

        distance_meters = R * c

        # Estimate driving distance based on mode
        if mode == "driving":
            distance_meters *= 1.3  # 30% longer for road network
            speed_mps = speed_kmh / 3.6  # Convert km/h to m/s
        elif mode == "walking":
            distance_meters *= 1.2
            speed_mps = 1.4  # ~5 km/h walking speed
        elif mode == "bicycling":
            distance_meters *= 1.25
            speed_mps = 4.5  # ~16 km/h cycling speed
        elif mode == "transit":
            distance_meters *= 1.4
            speed_mps = 8.9  # ~32 km/h transit speed
        else:
            speed_mps = speed_kmh / 3.6

        # Calculate base duration from speed
        base_duration_seconds = int(distance_meters / speed_mps)

        # Add realistic urban delays for driving mode
        traffic_duration_seconds = base_duration_seconds

        if mode == "driving":
            distance_km = distance_meters / 1000.0

            # Add traffic signal delays
            num_signals = int(distance_km * city_profile["signals_per_km"])
            signal_delay = num_signals * city_profile["signal_delay_sec"]

            # Add intersection delays
            intersection_delay = int(distance_km * city_profile["intersection_delay_per_km"])

            # Apply congestion multiplier for peak hours
            if time_period == "peak":
                congestion_delay = int(base_duration_seconds * (city_profile["congestion_multiplier"] - 1.0))
            else:
                congestion_delay = 0

            # Calculate total traffic-aware duration
            traffic_duration_seconds = base_duration_seconds + signal_delay + intersection_delay + congestion_delay

            # Apply minimum travel time (2 minutes)
            MIN_TRAVEL_TIME = 120
            if traffic_duration_seconds < MIN_TRAVEL_TIME:
                traffic_duration_seconds = MIN_TRAVEL_TIME

            logger.info(f"Urban delays - Signals: {signal_delay}s, Intersections: {intersection_delay}s, Congestion: {congestion_delay}s")

        # Format distance
        if distance_meters >= 1000:
            distance_text = f"{distance_meters/1000:.1f} km"
        else:
            distance_text = f"{int(distance_meters)} m"

        # Format base duration
        hours = base_duration_seconds // 3600
        minutes = (base_duration_seconds % 3600) // 60
        if hours > 0:
            base_duration_text = f"{hours} hour{'s' if hours > 1 else ''} {minutes} min{'s' if minutes != 1 else ''}"
        else:
            base_duration_text = f"{minutes} min{'s' if minutes != 1 else ''}"

        # Format traffic-aware duration
        hours = traffic_duration_seconds // 3600
        minutes = (traffic_duration_seconds % 3600) // 60
        if hours > 0:
            traffic_duration_text = f"{hours} hour{'s' if hours > 1 else ''} {minutes} min{'s' if minutes != 1 else ''}"
        else:
            traffic_duration_text = f"{minutes} min{'s' if minutes != 1 else ''}"

        logger.info(f"Mock route calculated: {distance_text}, {traffic_duration_text} (base: {base_duration_text}, city: {city_profile['name']})")

        return {
            "success": True,
            "origin": origin_geocoded["formatted_address"],
            "destination": dest_geocoded["formatted_address"],
            "distance": {
                "meters": int(distance_meters),
                "text": distance_text
            },
            "duration": {
                "seconds": base_duration_seconds,
                "text": base_duration_text
            },
            "duration_in_traffic": {
                "seconds": traffic_duration_seconds,
                "text": traffic_duration_text
            },
            "mode": mode,
            "route_summary": f"Direct route via {city_profile['name']} ({time_period} traffic)",
            "confidence": "low (mock calculation with urban traffic modeling)"
        }

    except Exception as e:
        logger.error(f"Mock route calculation failed: {e}")
        return {
            "success": False,
            "error": f"Could not calculate route: {str(e)}"
        }


def handle_create_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute order creation tool

    Args:
        tool_input: Dict with order fields (expected_delivery_time now REQUIRED)
        user_id: ID of authenticated user creating the order

    Returns:
        Order creation result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # Development mode - use default user
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Extract fields with defaults
    customer_name = tool_input.get("customer_name")
    customer_phone = tool_input.get("customer_phone")
    customer_email = tool_input.get("customer_email")
    delivery_address = tool_input.get("delivery_address")
    delivery_lat = tool_input.get("delivery_lat")
    delivery_lng = tool_input.get("delivery_lng")
    expected_delivery_time_str = tool_input.get("expected_delivery_time")
    priority = tool_input.get("priority", "standard")
    special_instructions = tool_input.get("special_instructions")
    weight_kg = tool_input.get("weight_kg", 5.0)
    volume_m3 = tool_input.get("volume_m3", 1.0)
    is_fragile = tool_input.get("is_fragile", False)
    requires_cold_storage = tool_input.get("requires_cold_storage", False)
    requires_signature = tool_input.get("requires_signature", False)
    sla_grace_period_minutes = tool_input.get("sla_grace_period_minutes", 15)

    # Validate required fields (expected_delivery_time is now MANDATORY)
    if not all([customer_name, delivery_address, delivery_lat, delivery_lng, expected_delivery_time_str]):
        return {
            "success": False,
            "error": "Missing required fields: customer_name, delivery_address, delivery_lat, delivery_lng, expected_delivery_time"
        }

    # Generate order ID with microseconds to prevent collisions
    now = datetime.now()
    order_id = f"ORD-{now.strftime('%Y%m%d%H%M%S%f')[:18]}"  # YYYYMMDDHHMMSSμμμμμμ (18 chars)

    # Parse and validate expected_delivery_time
    try:
        expected_delivery_time = datetime.fromisoformat(expected_delivery_time_str.replace('Z', '+00:00'))

        # Validate it's in the future
        if expected_delivery_time <= now:
            return {
                "success": False,
                "error": f"expected_delivery_time must be in the future. Provided: {expected_delivery_time_str}, Current time: {now.isoformat()}"
            }
    except (ValueError, AttributeError) as e:
        return {
            "success": False,
            "error": f"Invalid expected_delivery_time format. Must be ISO 8601 format (e.g., '2025-11-15T18:00:00'). Error: {str(e)}"
        }

    # Handle time window (kept for backward compatibility)
    time_window_end_str = tool_input.get("time_window_end")
    if time_window_end_str:
        try:
            time_window_end = datetime.fromisoformat(time_window_end_str.replace('Z', '+00:00'))
        except:
            time_window_end = expected_delivery_time  # Use expected time as fallback
    else:
        time_window_end = expected_delivery_time  # Default to expected delivery time

    time_window_start = now + timedelta(hours=2)

    # Insert into database
    query = """
        INSERT INTO orders (
            order_id, customer_name, customer_phone, customer_email,
            delivery_address, delivery_lat, delivery_lng,
            time_window_start, time_window_end, expected_delivery_time,
            priority, weight_kg, volume_m3, is_fragile, requires_cold_storage, requires_signature,
            status, special_instructions, sla_grace_period_minutes, user_id
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    """

    params = (
        order_id,
        customer_name,
        customer_phone,
        customer_email,
        delivery_address,
        delivery_lat,
        delivery_lng,
        time_window_start,
        time_window_end,
        expected_delivery_time,
        priority,
        weight_kg,
        volume_m3,
        is_fragile,
        requires_cold_storage,
        requires_signature,
        "pending",
        special_instructions,
        sla_grace_period_minutes,
        user_id  # Add user_id to track ownership
    )

    try:
        execute_write(query, params)
        logger.info(f"Order created: {order_id}, expected delivery: {expected_delivery_time.strftime('%Y-%m-%d %H:%M')}")

        return {
            "success": True,
            "order_id": order_id,
            "status": "pending",
            "customer": customer_name,
            "address": delivery_address,
            "expected_delivery": expected_delivery_time.strftime("%Y-%m-%d %H:%M"),
            "sla_grace_period_minutes": sla_grace_period_minutes,
            "priority": priority,
            "message": f"Order {order_id} created successfully! Expected delivery: {expected_delivery_time.strftime('%Y-%m-%d %H:%M')}"
        }
    except Exception as e:
        logger.error(f"Database error creating order: {e}")
        return {
            "success": False,
            "error": f"Failed to create order: {str(e)}"
        }


def handle_create_driver(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute driver creation tool

    Args:
        tool_input: Dict with driver fields
        user_id: ID of authenticated user creating the driver

    Returns:
        Driver creation result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Extract fields with defaults
    name = tool_input.get("name")
    phone = tool_input.get("phone")
    email = tool_input.get("email")
    vehicle_type = tool_input.get("vehicle_type")  # No default - REQUIRED
    vehicle_plate = tool_input.get("vehicle_plate")
    capacity_kg = tool_input.get("capacity_kg", 1000.0)
    capacity_m3 = tool_input.get("capacity_m3", 12.0)
    current_lat = tool_input.get("current_lat")  # No default - REQUIRED
    current_lng = tool_input.get("current_lng")  # No default - REQUIRED
    current_address = tool_input.get("current_address")  # No default - REQUIRED

    # Convert skills to regular list (handles protobuf RepeatedComposite)
    skills_raw = tool_input.get("skills", [])
    skills = list(skills_raw) if skills_raw else []

    # Define valid skills
    VALID_SKILLS = [
        "refrigerated",
        "medical_certified",
        "fragile_handler",
        "overnight",
        "express_delivery"
    ]

    # Validate skills
    if skills:
        invalid_skills = [s for s in skills if s not in VALID_SKILLS]
        if invalid_skills:
            return {
                "success": False,
                "error": f"Invalid skills: {invalid_skills}. Valid skills are: {VALID_SKILLS}"
            }

    status = tool_input.get("status", "active")

    # Validate ALL required fields (name, vehicle_type, current_address, current_lat, current_lng)
    if not all([name, vehicle_type, current_address, current_lat is not None, current_lng is not None]):
        return {
            "success": False,
            "error": "Missing required fields: name, vehicle_type, current_address, current_lat, current_lng. All fields are mandatory."
        }

    # Validate coordinates are valid numbers
    try:
        current_lat = float(current_lat)
        current_lng = float(current_lng)
    except (ValueError, TypeError):
        return {
            "success": False,
            "error": "current_lat and current_lng must be valid numbers"
        }

    # Validate coordinates are within valid ranges
    if not (-90 <= current_lat <= 90):
        return {
            "success": False,
            "error": f"Invalid latitude {current_lat}. Must be between -90 and 90"
        }

    if not (-180 <= current_lng <= 180):
        return {
            "success": False,
            "error": f"Invalid longitude {current_lng}. Must be between -180 and 180"
        }

    # Generate driver ID with microseconds to prevent collisions
    now = datetime.now()
    driver_id = f"DRV-{now.strftime('%Y%m%d%H%M%S%f')[:18]}"  # YYYYMMDDHHMMSSμμμμμμ (18 chars)

    # Insert into database
    query = """
        INSERT INTO drivers (
            driver_id, name, phone, email,
            current_lat, current_lng, current_address, last_location_update,
            status, vehicle_type, vehicle_plate,
            capacity_kg, capacity_m3, skills, user_id
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    """

    # Convert skills list to JSON
    import json
    skills_json = json.dumps(skills) if skills else json.dumps([])

    params = (
        driver_id,
        name,
        phone,
        email,
        current_lat,
        current_lng,
        current_address,
        now,
        status,
        vehicle_type,
        vehicle_plate,
        capacity_kg,
        capacity_m3,
        skills_json,
        user_id  # Add user_id to track ownership
    )

    try:
        execute_write(query, params)
        logger.info(f"Driver created: {driver_id}")

        return {
            "success": True,
            "driver_id": driver_id,
            "name": name,
            "phone": phone,
            "status": status,
            "vehicle_type": vehicle_type,
            "vehicle_plate": vehicle_plate,
            "capacity_kg": capacity_kg,
            "skills": skills,
            "location": {
                "latitude": current_lat,
                "longitude": current_lng,
                "address": current_address
            },
            "message": f"Driver {driver_id} ({name}) created successfully!"
        }
    except Exception as e:
        logger.error(f"Database error creating driver: {e}")
        return {
            "success": False,
            "error": f"Failed to create driver: {str(e)}"
        }


def handle_update_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute order update tool with assignment cascading logic

    Args:
        tool_input: Dict with order_id and fields to update
        user_id: Authenticated user ID

    Returns:
        Update result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    import json

    order_id = tool_input.get("order_id")

    # Validate required field
    if not order_id:
        return {
            "success": False,
            "error": "Missing required field: order_id"
        }

    # Check if order exists and belongs to user
    check_query = "SELECT order_id, status, assigned_driver_id FROM orders WHERE order_id = %s AND user_id = %s"
    existing = execute_query(check_query, (order_id, user_id))

    if not existing:
        return {
            "success": False,
            "error": f"Order {order_id} not found"
        }

    current_status = existing[0].get("status")
    current_assigned_driver = existing[0].get("assigned_driver_id")

    # Auto-geocode if delivery address is updated without coordinates
    # Use safe_geocode with timeout protection
    if "delivery_address" in tool_input and ("delivery_lat" not in tool_input or "delivery_lng" not in tool_input):
        try:
            geocode_result = safe_geocode(tool_input["delivery_address"])
            tool_input["delivery_lat"] = geocode_result["lat"]
            tool_input["delivery_lng"] = geocode_result["lng"]
            logger.info(f"Auto-geocoded delivery address: {geocode_result['formatted_address']}")
        except Exception as e:
            logger.warning(f"Failed to geocode address, skipping coordinate update: {e}")

    # Handle status changes with assignment cascading logic
    new_status = tool_input.get("status")
    cascading_actions = []

    if new_status and new_status != current_status:
        # Check if order has active assignment
        assignment_check = execute_query("""
            SELECT assignment_id, status, driver_id
            FROM assignments
            WHERE order_id = %s AND status IN ('active', 'in_progress')
            LIMIT 1
        """, (order_id,))

        has_active_assignment = len(assignment_check) > 0

        # Validate status transitions based on assignment state
        if new_status == "pending" and current_status == "assigned":
            if has_active_assignment:
                # Changing assigned order back to pending - must cancel assignment
                assignment_id = assignment_check[0]["assignment_id"]
                driver_id = assignment_check[0]["driver_id"]

                # Cancel the assignment
                execute_write("""
                    UPDATE assignments SET status = 'cancelled', updated_at = %s
                    WHERE assignment_id = %s
                """, (datetime.now(), assignment_id))

                # Clear assigned_driver_id from order
                execute_write("""
                    UPDATE orders SET assigned_driver_id = NULL
                    WHERE order_id = %s
                """, (order_id,))

                # Check if driver has other active assignments
                other_assignments = execute_query("""
                    SELECT COUNT(*) as count FROM assignments
                    WHERE driver_id = %s AND status IN ('active', 'in_progress')
                    AND assignment_id != %s
                """, (driver_id, assignment_id))

                if other_assignments[0]["count"] == 0:
                    # Set driver back to active if no other assignments
                    execute_write("""
                        UPDATE drivers SET status = 'active', updated_at = %s
                        WHERE driver_id = %s
                    """, (datetime.now(), driver_id))
                    cascading_actions.append(f"Driver {driver_id} set to active (no other assignments)")

                cascading_actions.append(f"Assignment {assignment_id} cancelled and removed")

        elif new_status == "cancelled":
            if has_active_assignment:
                # Cancel active assignment when order is cancelled
                assignment_id = assignment_check[0]["assignment_id"]
                driver_id = assignment_check[0]["driver_id"]

                execute_write("""
                    UPDATE assignments SET status = 'cancelled', updated_at = %s
                    WHERE assignment_id = %s
                """, (datetime.now(), assignment_id))

                # Clear assigned_driver_id
                execute_write("""
                    UPDATE orders SET assigned_driver_id = NULL
                    WHERE order_id = %s
                """, (order_id,))

                # Check if driver has other active assignments
                other_assignments = execute_query("""
                    SELECT COUNT(*) as count FROM assignments
                    WHERE driver_id = %s AND status IN ('active', 'in_progress')
                    AND assignment_id != %s
                """, (driver_id, assignment_id))

                if other_assignments[0]["count"] == 0:
                    execute_write("""
                        UPDATE drivers SET status = 'active', updated_at = %s
                        WHERE driver_id = %s
                    """, (datetime.now(), driver_id))
                    cascading_actions.append(f"Driver {driver_id} set to active")

                cascading_actions.append(f"Assignment {assignment_id} cancelled")

        elif new_status in ["delivered", "failed"] and has_active_assignment:
            # Note: This should normally be handled by update_assignment tool
            # but we allow it here for flexibility
            assignment_id = assignment_check[0]["assignment_id"]
            final_status = "completed" if new_status == "delivered" else "failed"

            execute_write("""
                UPDATE assignments SET status = %s, updated_at = %s
                WHERE assignment_id = %s
            """, (final_status, datetime.now(), assignment_id))

            cascading_actions.append(f"Assignment {assignment_id} marked as {final_status}")

    # Build UPDATE query dynamically based on provided fields
    update_fields = []
    params = []

    # Map of field names to their database columns
    updateable_fields = {
        "customer_name": "customer_name",
        "customer_phone": "customer_phone",
        "customer_email": "customer_email",
        "delivery_address": "delivery_address",
        "delivery_lat": "delivery_lat",
        "delivery_lng": "delivery_lng",
        "status": "status",
        "priority": "priority",
        "special_instructions": "special_instructions",
        "time_window_end": "time_window_end",
        "payment_status": "payment_status",
        "weight_kg": "weight_kg",
        "order_value": "order_value"
    }

    for field, column in updateable_fields.items():
        if field in tool_input:
            update_fields.append(f"{column} = %s")
            params.append(tool_input[field])

    if not update_fields:
        return {
            "success": False,
            "error": "No fields provided to update"
        }

    # Always update the updated_at timestamp
    update_fields.append("updated_at = %s")
    params.append(datetime.now())

    # Add order_id and user_id for WHERE clause
    params.append(order_id)
    params.append(user_id)

    # Execute update
    query = f"""
        UPDATE orders
        SET {', '.join(update_fields)}
        WHERE order_id = %s AND user_id = %s
    """

    try:
        execute_write(query, tuple(params))
        logger.info(f"Order updated: {order_id}")

        result = {
            "success": True,
            "order_id": order_id,
            "updated_fields": list(updateable_fields.keys() & tool_input.keys()),
            "message": f"Order {order_id} updated successfully!"
        }

        if cascading_actions:
            result["cascading_actions"] = cascading_actions

        return result
    except Exception as e:
        logger.error(f"Database error updating order: {e}")
        return {
            "success": False,
            "error": f"Failed to update order: {str(e)}"
        }


def handle_delete_all_orders(tool_input: dict, user_id: str = None) -> dict:
    """
    Delete all orders (bulk delete) for the authenticated user

    Args:
        tool_input: Dict with confirm flag and optional status filter
        user_id: Authenticated user ID

    Returns:
        Deletion result with count
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    confirm = tool_input.get("confirm", False)
    status_filter = tool_input.get("status")  # Optional: delete only specific status

    if not confirm:
        return {
            "success": False,
            "error": "Bulk deletion requires confirm=true for safety"
        }

    try:
        # Check for active assignments first (only for this user's orders)
        active_assignments = execute_query("""
            SELECT COUNT(*) as count FROM assignments
            WHERE user_id = %s AND status IN ('active', 'in_progress')
        """, (user_id,))

        active_count = active_assignments[0]['count']

        if active_count > 0:
            return {
                "success": False,
                "error": f"Cannot delete orders: {active_count} active assignment(s) exist. Cancel or complete them first."
            }

        # Build delete query based on status filter (always filter by user_id)
        if status_filter:
            count_query = "SELECT COUNT(*) as count FROM orders WHERE user_id = %s AND status = %s"
            delete_query = "DELETE FROM orders WHERE user_id = %s AND status = %s"
            params = (user_id, status_filter)
        else:
            count_query = "SELECT COUNT(*) as count FROM orders WHERE user_id = %s"
            delete_query = "DELETE FROM orders WHERE user_id = %s"
            params = (user_id,)

        # Get count before deletion
        count_result = execute_query(count_query, params)
        total_count = count_result[0]['count']

        if total_count == 0:
            return {
                "success": True,
                "deleted_count": 0,
                "message": "No orders to delete"
            }

        # Execute bulk delete
        execute_write(delete_query, params)
        logger.info(f"Bulk deleted {total_count} orders")

        return {
            "success": True,
            "deleted_count": total_count,
            "message": f"Successfully deleted {total_count} order(s)"
        }

    except Exception as e:
        logger.error(f"Database error bulk deleting orders: {e}")
        return {
            "success": False,
            "error": f"Failed to bulk delete orders: {str(e)}"
        }


def handle_delete_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute order deletion tool with assignment safety checks

    Args:
        tool_input: Dict with order_id and confirm flag
        user_id: Authenticated user ID

    Returns:
        Deletion result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    order_id = tool_input.get("order_id")
    confirm = tool_input.get("confirm", False)

    # Validate required fields
    if not order_id:
        return {
            "success": False,
            "error": "Missing required field: order_id"
        }

    if not confirm:
        return {
            "success": False,
            "error": "Deletion not confirmed. Set confirm=true to proceed."
        }

    # Check if order exists and belongs to user
    check_query = "SELECT order_id, status FROM orders WHERE order_id = %s AND user_id = %s"
    existing = execute_query(check_query, (order_id, user_id))

    if not existing:
        return {
            "success": False,
            "error": f"Order {order_id} not found"
        }

    order_status = existing[0].get("status")

    # Check for active assignments
    assignment_check = execute_query("""
        SELECT assignment_id, status, driver_id
        FROM assignments
        WHERE order_id = %s AND status IN ('active', 'in_progress')
    """, (order_id,))

    if assignment_check:
        # Warn about active assignments that will be cascade deleted
        assignment_count = len(assignment_check)
        assignment_ids = [a["assignment_id"] for a in assignment_check]

        return {
            "success": False,
            "error": f"Cannot delete order {order_id}: it has {assignment_count} active assignment(s): {', '.join(assignment_ids)}. Please cancel or complete the assignment(s) first using update_assignment or unassign_order.",
            "active_assignments": assignment_ids
        }

    # Check for any completed assignments (these will be cascade deleted)
    completed_assignments = execute_query("""
        SELECT COUNT(*) as count FROM assignments
        WHERE order_id = %s AND status IN ('completed', 'failed', 'cancelled')
    """, (order_id,))

    cascading_info = []
    if completed_assignments[0]["count"] > 0:
        cascading_info.append(f"{completed_assignments[0]['count']} completed/failed/cancelled assignment(s) will be cascade deleted")

    # Delete the order (will cascade to assignments via FK)
    query = "DELETE FROM orders WHERE order_id = %s AND user_id = %s"

    try:
        execute_write(query, (order_id, user_id))
        logger.info(f"Order deleted: {order_id}")

        result = {
            "success": True,
            "order_id": order_id,
            "message": f"Order {order_id} has been permanently deleted."
        }

        if cascading_info:
            result["cascading_info"] = cascading_info

        return result
    except Exception as e:
        logger.error(f"Database error deleting order: {e}")
        return {
            "success": False,
            "error": f"Failed to delete order: {str(e)}"
        }


def handle_update_driver(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute driver update tool with assignment validation

    Args:
        tool_input: Dict with driver_id and fields to update
        user_id: Authenticated user ID

    Returns:
        Update result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    import json

    driver_id = tool_input.get("driver_id")

    # Validate required field
    if not driver_id:
        return {
            "success": False,
            "error": "Missing required field: driver_id"
        }

    # Check if driver exists and belongs to user
    check_query = "SELECT driver_id, status FROM drivers WHERE driver_id = %s AND user_id = %s"
    existing = execute_query(check_query, (driver_id, user_id))

    if not existing:
        return {
            "success": False,
            "error": f"Driver {driver_id} not found"
        }

    current_status = existing[0].get("status")

    # Validate status changes against active assignments
    new_status = tool_input.get("status")
    if new_status and new_status != current_status:
        # Check for active assignments
        assignment_check = execute_query("""
            SELECT assignment_id, status, order_id
            FROM assignments
            WHERE driver_id = %s AND status IN ('active', 'in_progress')
        """, (driver_id,))

        has_active_assignments = len(assignment_check) > 0

        # Prevent setting driver to offline/inactive when they have active assignments
        if new_status in ["offline", "inactive"] and has_active_assignments:
            assignment_count = len(assignment_check)
            assignment_ids = [a["assignment_id"] for a in assignment_check]

            return {
                "success": False,
                "error": f"Cannot set driver {driver_id} to '{new_status}': driver has {assignment_count} active assignment(s): {', '.join(assignment_ids)}. Please complete or cancel assignments first.",
                "active_assignments": assignment_ids
            }

        # Note: Setting driver to 'active' when they have assignments is allowed
        # The system manages 'busy' status automatically via assignment creation
        # But we allow manual override to 'active' for edge cases

    # Build UPDATE query dynamically based on provided fields
    update_fields = []
    params = []

    # Map of field names to their database columns
    updateable_fields = {
        "name": "name",
        "phone": "phone",
        "email": "email",
        "status": "status",
        "vehicle_type": "vehicle_type",
        "vehicle_plate": "vehicle_plate",
        "capacity_kg": "capacity_kg",
        "capacity_m3": "capacity_m3",
        "current_address": "current_address",
        "current_lat": "current_lat",
        "current_lng": "current_lng"
    }

    for field, column in updateable_fields.items():
        if field in tool_input:
            update_fields.append(f"{column} = %s")
            params.append(tool_input[field])

    # Handle skills array specially (convert to JSON)
    if "skills" in tool_input:
        skills = list(tool_input.get("skills", []))
        update_fields.append("skills = %s")
        params.append(json.dumps(skills))

    if not update_fields:
        return {
            "success": False,
            "error": "No fields provided to update"
        }

    # Always update the updated_at timestamp
    update_fields.append("updated_at = %s")
    params.append(datetime.now())

    # Update location timestamp if lat/lng changed
    if "current_lat" in tool_input or "current_lng" in tool_input:
        update_fields.append("last_location_update = %s")
        params.append(datetime.now())

    # Add driver_id and user_id for WHERE clause
    params.append(driver_id)
    params.append(user_id)

    # Execute update
    query = f"""
        UPDATE drivers
        SET {', '.join(update_fields)}
        WHERE driver_id = %s AND user_id = %s
    """

    try:
        execute_write(query, tuple(params))
        logger.info(f"Driver updated: {driver_id}")

        updated_list = list(updateable_fields.keys() & tool_input.keys())
        if "skills" in tool_input:
            updated_list.append("skills")

        return {
            "success": True,
            "driver_id": driver_id,
            "updated_fields": updated_list,
            "message": f"Driver {driver_id} updated successfully!"
        }
    except Exception as e:
        logger.error(f"Database error updating driver: {e}")
        return {
            "success": False,
            "error": f"Failed to update driver: {str(e)}"
        }


def handle_delete_all_drivers(tool_input: dict, user_id: str = None) -> dict:
    """
    Delete all drivers (bulk delete) for the authenticated user

    Args:
        tool_input: Dict with confirm flag and optional status filter
        user_id: Authenticated user ID

    Returns:
        Deletion result with count
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    confirm = tool_input.get("confirm", False)
    status_filter = tool_input.get("status")  # Optional: delete only specific status

    if not confirm:
        return {
            "success": False,
            "error": "Bulk deletion requires confirm=true for safety"
        }

    try:
        # Check for ANY assignments for this user (RESTRICT constraint will block if any exist)
        assignments = execute_query("""
            SELECT COUNT(*) as count FROM assignments WHERE user_id = %s
        """, (user_id,))

        assignment_count = assignments[0]['count']

        if assignment_count > 0:
            return {
                "success": False,
                "error": f"Cannot delete drivers: {assignment_count} assignment(s) exist in database. Database RESTRICT constraint prevents driver deletion when assignments exist."
            }

        # Build delete query based on status filter (always filter by user_id)
        if status_filter:
            count_query = "SELECT COUNT(*) as count FROM drivers WHERE user_id = %s AND status = %s"
            delete_query = "DELETE FROM drivers WHERE user_id = %s AND status = %s"
            params = (user_id, status_filter)
        else:
            count_query = "SELECT COUNT(*) as count FROM drivers WHERE user_id = %s"
            delete_query = "DELETE FROM drivers WHERE user_id = %s"
            params = (user_id,)

        # Get count before deletion
        count_result = execute_query(count_query, params)
        total_count = count_result[0]['count']

        if total_count == 0:
            return {
                "success": True,
                "deleted_count": 0,
                "message": "No drivers to delete"
            }

        # Execute bulk delete
        execute_write(delete_query, params)
        logger.info(f"Bulk deleted {total_count} drivers")

        return {
            "success": True,
            "deleted_count": total_count,
            "message": f"Successfully deleted {total_count} driver(s)"
        }

    except Exception as e:
        logger.error(f"Database error bulk deleting drivers: {e}")

        # Provide more context if it's a FK constraint error
        error_message = str(e)
        if "foreign key" in error_message.lower() or "violates" in error_message.lower():
            error_message = f"Cannot delete drivers due to database constraint (assignments exist). Error: {error_message}"

        return {
            "success": False,
            "error": f"Failed to bulk delete drivers: {error_message}"
        }


def handle_delete_driver(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute driver deletion tool with assignment safety checks

    Args:
        tool_input: Dict with driver_id and confirm flag
        user_id: Authenticated user ID

    Returns:
        Deletion result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    driver_id = tool_input.get("driver_id")
    confirm = tool_input.get("confirm", False)

    # Validate required fields
    if not driver_id:
        return {
            "success": False,
            "error": "Missing required field: driver_id"
        }

    if not confirm:
        return {
            "success": False,
            "error": "Deletion not confirmed. Set confirm=true to proceed."
        }

    # Check if driver exists and belongs to user
    check_query = "SELECT driver_id, name FROM drivers WHERE driver_id = %s AND user_id = %s"
    existing = execute_query(check_query, (driver_id, user_id))

    if not existing:
        return {
            "success": False,
            "error": f"Driver {driver_id} not found"
        }

    driver_name = existing[0]["name"]

    # Check for ANY assignments (active or completed)
    # FK constraint with ON DELETE RESTRICT will prevent deletion if ANY assignments exist
    assignment_check = execute_query("""
        SELECT assignment_id, status, order_id
        FROM assignments
        WHERE driver_id = %s
    """, (driver_id,))

    if assignment_check:
        # Count active vs completed assignments
        active_assignments = [a for a in assignment_check if a["status"] in ("active", "in_progress")]
        completed_assignments = [a for a in assignment_check if a["status"] in ("completed", "failed", "cancelled")]

        total_count = len(assignment_check)
        active_count = len(active_assignments)
        completed_count = len(completed_assignments)

        error_msg = f"Cannot delete driver {driver_id} ({driver_name}): driver has {total_count} assignment(s)"

        if active_count > 0:
            active_ids = [a["assignment_id"] for a in active_assignments]
            error_msg += f" ({active_count} active: {', '.join(active_ids)})"

        if completed_count > 0:
            error_msg += f" ({completed_count} completed/failed/cancelled)"

        error_msg += ". The database has RESTRICT constraint preventing driver deletion when assignments exist. Please cancel/complete active assignments and consider archiving the driver instead of deleting."

        return {
            "success": False,
            "error": error_msg,
            "total_assignments": total_count,
            "active_assignments": [a["assignment_id"] for a in active_assignments],
            "completed_assignments": [a["assignment_id"] for a in completed_assignments]
        }

    # Check for orders that reference this driver in assigned_driver_id
    # FK constraint with ON DELETE SET NULL will set these to NULL
    assigned_orders = execute_query("""
        SELECT order_id FROM orders WHERE assigned_driver_id = %s
    """, (driver_id,))

    cascading_info = []
    if assigned_orders:
        order_count = len(assigned_orders)
        cascading_info.append(f"{order_count} order(s) will have assigned_driver_id set to NULL")

    # Delete the driver
    query = "DELETE FROM drivers WHERE driver_id = %s AND user_id = %s"

    try:
        execute_write(query, (driver_id, user_id))
        logger.info(f"Driver deleted: {driver_id}")

        result = {
            "success": True,
            "driver_id": driver_id,
            "message": f"Driver {driver_id} ({driver_name}) has been permanently deleted."
        }

        if cascading_info:
            result["cascading_info"] = cascading_info

        return result
    except Exception as e:
        logger.error(f"Database error deleting driver: {e}")

        # Provide more context if it's a FK constraint error
        error_message = str(e)
        if "foreign key" in error_message.lower() or "violates" in error_message.lower():
            error_message = f"Cannot delete driver due to database constraint (likely has related assignments). Error: {error_message}"

        return {
            "success": False,
            "error": f"Failed to delete driver: {error_message}"
        }


def handle_count_orders(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute count orders tool

    Args:
        tool_input: Dict with optional filter fields
        user_id: ID of authenticated user

    Returns:
        Order count result with breakdown (only user's orders)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Build WHERE clause based on filters
    # IMPORTANT: Always filter by user_id FIRST
    where_clauses = ["user_id = %s"]
    params = [user_id]

    if "status" in tool_input:
        where_clauses.append("status = %s")
        params.append(tool_input["status"])

    if "priority" in tool_input:
        where_clauses.append("priority = %s")
        params.append(tool_input["priority"])

    if "payment_status" in tool_input:
        where_clauses.append("payment_status = %s")
        params.append(tool_input["payment_status"])

    if "assigned_driver_id" in tool_input:
        where_clauses.append("assigned_driver_id = %s")
        params.append(tool_input["assigned_driver_id"])

    if "is_fragile" in tool_input:
        where_clauses.append("is_fragile = %s")
        params.append(tool_input["is_fragile"])

    if "requires_signature" in tool_input:
        where_clauses.append("requires_signature = %s")
        params.append(tool_input["requires_signature"])

    if "requires_cold_storage" in tool_input:
        where_clauses.append("requires_cold_storage = %s")
        params.append(tool_input["requires_cold_storage"])

    where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""

    # Total count query
    count_query = f"SELECT COUNT(*) as total FROM orders{where_sql}"

    # Breakdown by status query
    breakdown_query = f"""
        SELECT status, COUNT(*) as count
        FROM orders{where_sql}
        GROUP BY status
        ORDER BY count DESC
    """

    # Breakdown by priority query
    priority_query = f"""
        SELECT priority, COUNT(*) as count
        FROM orders{where_sql}
        GROUP BY priority
        ORDER BY CASE priority
            WHEN 'urgent' THEN 1
            WHEN 'express' THEN 2
            WHEN 'standard' THEN 3
        END
    """

    try:
        # Execute queries
        total_result = execute_query(count_query, tuple(params) if params else None)
        total = total_result[0]['total'] if total_result else 0

        status_result = execute_query(breakdown_query, tuple(params) if params else None)
        priority_result = execute_query(priority_query, tuple(params) if params else None)

        # Format breakdown
        status_breakdown = {row['status']: row['count'] for row in status_result} if status_result else {}
        priority_breakdown = {row['priority']: row['count'] for row in priority_result} if priority_result else {}

        logger.info(f"Counted orders: {total} total")

        return {
            "success": True,
            "total": total,
            "status_breakdown": status_breakdown,
            "priority_breakdown": priority_breakdown,
            "message": f"Found {total} order(s)"
        }
    except Exception as e:
        logger.error(f"Database error counting orders: {e}")
        return {
            "success": False,
            "error": f"Failed to count orders: {str(e)}"
        }


def handle_fetch_orders(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute fetch orders tool

    Args:
        tool_input: Dict with filter, pagination, and sorting options
        user_id: ID of authenticated user (filters to only their orders)

    Returns:
        List of orders matching criteria (only user's orders)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # Development mode - use default user
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Extract pagination and sorting
    limit = min(tool_input.get("limit", 10), 100)  # Cap at 100
    offset = tool_input.get("offset", 0)
    sort_by = tool_input.get("sort_by", "created_at")
    sort_order = tool_input.get("sort_order", "DESC")

    # Build WHERE clause based on filters
    # IMPORTANT: Always filter by user_id FIRST for security
    where_clauses = ["user_id = %s"]
    params = [user_id]

    if "status" in tool_input:
        where_clauses.append("status = %s")
        params.append(tool_input["status"])

    if "priority" in tool_input:
        where_clauses.append("priority = %s")
        params.append(tool_input["priority"])

    if "payment_status" in tool_input:
        where_clauses.append("payment_status = %s")
        params.append(tool_input["payment_status"])

    if "assigned_driver_id" in tool_input:
        where_clauses.append("assigned_driver_id = %s")
        params.append(tool_input["assigned_driver_id"])

    if "is_fragile" in tool_input:
        where_clauses.append("is_fragile = %s")
        params.append(tool_input["is_fragile"])

    if "requires_signature" in tool_input:
        where_clauses.append("requires_signature = %s")
        params.append(tool_input["requires_signature"])

    if "requires_cold_storage" in tool_input:
        where_clauses.append("requires_cold_storage = %s")
        params.append(tool_input["requires_cold_storage"])

    where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""

    # Build query
    query = f"""
        SELECT
            order_id, customer_name, customer_phone, customer_email,
            delivery_address, delivery_lat, delivery_lng,
            time_window_start, time_window_end,
            priority, weight_kg, volume_m3, special_instructions,
            status, assigned_driver_id,
            created_at, updated_at, delivered_at,
            order_value, payment_status,
            requires_signature, is_fragile, requires_cold_storage
        FROM orders
        {where_sql}
        ORDER BY {sort_by} {sort_order}
        LIMIT %s OFFSET %s
    """

    params.extend([limit, offset])

    try:
        results = execute_query(query, tuple(params))

        if not results:
            return {
                "success": True,
                "orders": [],
                "count": 0,
                "message": "No orders found matching criteria"
            }

        # Format orders for readability
        orders = []
        for row in results:
            order = {
                "order_id": row['order_id'],
                "customer": {
                    "name": row['customer_name'],
                    "phone": row['customer_phone'],
                    "email": row['customer_email']
                },
                "delivery": {
                    "address": row['delivery_address'],
                    "latitude": float(row['delivery_lat']) if row['delivery_lat'] else None,
                    "longitude": float(row['delivery_lng']) if row['delivery_lng'] else None
                },
                "time_window": {
                    "start": str(row['time_window_start']) if row['time_window_start'] else None,
                    "end": str(row['time_window_end']) if row['time_window_end'] else None
                },
                "details": {
                    "priority": row['priority'],
                    "status": row['status'],
                    "weight_kg": float(row['weight_kg']) if row['weight_kg'] else None,
                    "volume_m3": float(row['volume_m3']) if row['volume_m3'] else None,
                    "special_instructions": row['special_instructions']
                },
                "flags": {
                    "requires_signature": row['requires_signature'],
                    "is_fragile": row['is_fragile'],
                    "requires_cold_storage": row['requires_cold_storage']
                },
                "payment": {
                    "order_value": float(row['order_value']) if row['order_value'] else None,
                    "payment_status": row['payment_status']
                },
                "assigned_driver_id": row['assigned_driver_id'],
                "timestamps": {
                    "created_at": str(row['created_at']),
                    "updated_at": str(row['updated_at']) if row['updated_at'] else None,
                    "delivered_at": str(row['delivered_at']) if row['delivered_at'] else None
                }
            }
            orders.append(order)

        logger.info(f"Fetched {len(orders)} orders")

        return {
            "success": True,
            "orders": orders,
            "count": len(orders),
            "message": f"Retrieved {len(orders)} order(s)"
        }
    except Exception as e:
        logger.error(f"Database error fetching orders: {e}")
        return {
            "success": False,
            "error": f"Failed to fetch orders: {str(e)}"
        }


def handle_get_order_details(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute get order details tool

    Args:
        tool_input: Dict with order_id
        user_id: ID of authenticated user

    Returns:
        Complete order details (only if owned by user)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    order_id = tool_input.get("order_id")

    if not order_id:
        return {
            "success": False,
            "error": "order_id is required"
        }

    query = """
        SELECT
            order_id, customer_name, customer_phone, customer_email,
            pickup_address, pickup_lat, pickup_lng,
            delivery_address, delivery_lat, delivery_lng,
            time_window_start, time_window_end, expected_delivery_time,
            priority, weight_kg, volume_m3, special_instructions,
            status, assigned_driver_id, delivery_status,
            created_at, updated_at, delivered_at, sla_grace_period_minutes,
            order_value, payment_status,
            requires_signature, is_fragile, requires_cold_storage
        FROM orders
        WHERE order_id = %s AND user_id = %s
    """

    try:
        results = execute_query(query, (order_id, user_id))

        if not results:
            return {
                "success": False,
                "error": f"Order {order_id} not found"
            }

        row = results[0]

        order = {
            "order_id": row['order_id'],
            "customer": {
                "name": row['customer_name'],
                "phone": row['customer_phone'],
                "email": row['customer_email']
            },
            "pickup": {
                "address": row['pickup_address'],
                "latitude": float(row['pickup_lat']) if row['pickup_lat'] else None,
                "longitude": float(row['pickup_lng']) if row['pickup_lng'] else None
            } if row['pickup_address'] else None,
            "delivery": {
                "address": row['delivery_address'],
                "latitude": float(row['delivery_lat']) if row['delivery_lat'] else None,
                "longitude": float(row['delivery_lng']) if row['delivery_lng'] else None
            },
            "time_window": {
                "start": str(row['time_window_start']) if row['time_window_start'] else None,
                "end": str(row['time_window_end']) if row['time_window_end'] else None
            },
            "details": {
                "priority": row['priority'],
                "status": row['status'],
                "weight_kg": float(row['weight_kg']) if row['weight_kg'] else None,
                "volume_m3": float(row['volume_m3']) if row['volume_m3'] else None,
                "special_instructions": row['special_instructions']
            },
            "delivery_status": row['delivery_status'],
            "timing": {
                "expected_delivery_time": str(row['expected_delivery_time']) if row['expected_delivery_time'] else None,
                "delivered_at": str(row['delivered_at']) if row['delivered_at'] else None,
                "sla_grace_period_minutes": row['sla_grace_period_minutes']
            },
            "flags": {
                "requires_signature": row['requires_signature'],
                "is_fragile": row['is_fragile'],
                "requires_cold_storage": row['requires_cold_storage']
            },
            "payment": {
                "order_value": float(row['order_value']) if row['order_value'] else None,
                "payment_status": row['payment_status']
            },
            "assigned_driver_id": row['assigned_driver_id'],
            "timestamps": {
                "created_at": str(row['created_at']),
                "updated_at": str(row['updated_at']) if row['updated_at'] else None
            }
        }

        logger.info(f"Retrieved details for order: {order_id}")

        return {
            "success": True,
            "order": order,
            "message": f"Order {order_id} details retrieved"
        }
    except Exception as e:
        logger.error(f"Database error getting order details: {e}")
        return {
            "success": False,
            "error": f"Failed to get order details: {str(e)}"
        }


def handle_search_orders(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute search orders tool

    Args:
        tool_input: Dict with search_term
        user_id: Authenticated user ID

    Returns:
        List of matching orders
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    search_term = tool_input.get("search_term", "").strip()

    if not search_term:
        return {
            "success": False,
            "error": "search_term is required"
        }

    query = """
        SELECT
            order_id, customer_name, customer_phone, customer_email,
            delivery_address, priority, status, created_at
        FROM orders
        WHERE
            user_id = %s AND (
                order_id ILIKE %s OR
                customer_name ILIKE %s OR
                customer_email ILIKE %s OR
                customer_phone ILIKE %s
            )
        ORDER BY created_at DESC
        LIMIT 50
    """

    search_pattern = f"%{search_term}%"
    params = (user_id, search_pattern, search_pattern, search_pattern, search_pattern)

    try:
        results = execute_query(query, params)

        if not results:
            return {
                "success": True,
                "orders": [],
                "count": 0,
                "message": f"No orders found matching '{search_term}'"
            }

        orders = []
        for row in results:
            orders.append({
                "order_id": row['order_id'],
                "customer_name": row['customer_name'],
                "customer_phone": row['customer_phone'],
                "customer_email": row['customer_email'],
                "delivery_address": row['delivery_address'],
                "priority": row['priority'],
                "status": row['status'],
                "created_at": str(row['created_at'])
            })

        logger.info(f"Search '{search_term}' found {len(orders)} orders")

        return {
            "success": True,
            "orders": orders,
            "count": len(orders),
            "message": f"Found {len(orders)} order(s) matching '{search_term}'"
        }
    except Exception as e:
        logger.error(f"Database error searching orders: {e}")
        return {
            "success": False,
            "error": f"Failed to search orders: {str(e)}"
        }


def handle_get_incomplete_orders(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute get incomplete orders tool

    Args:
        tool_input: Dict with optional limit
        user_id: Authenticated user ID

    Returns:
        List of incomplete orders (pending, assigned, in_transit)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    limit = min(tool_input.get("limit", 20), 100)

    query = """
        SELECT
            order_id, customer_name, delivery_address,
            priority, status, time_window_end, created_at,
            assigned_driver_id
        FROM orders
        WHERE user_id = %s AND status IN ('pending', 'assigned', 'in_transit')
        ORDER BY
            CASE priority
                WHEN 'urgent' THEN 1
                WHEN 'express' THEN 2
                WHEN 'standard' THEN 3
            END,
            time_window_end ASC
        LIMIT %s
    """

    try:
        results = execute_query(query, (user_id, limit))

        if not results:
            return {
                "success": True,
                "orders": [],
                "count": 0,
                "message": "No incomplete orders found"
            }

        orders = []
        for row in results:
            orders.append({
                "order_id": row['order_id'],
                "customer_name": row['customer_name'],
                "delivery_address": row['delivery_address'],
                "priority": row['priority'],
                "status": row['status'],
                "time_window_end": str(row['time_window_end']) if row['time_window_end'] else None,
                "created_at": str(row['created_at']),
                "assigned_driver_id": row['assigned_driver_id']
            })

        logger.info(f"Retrieved {len(orders)} incomplete orders")

        return {
            "success": True,
            "orders": orders,
            "count": len(orders),
            "message": f"Found {len(orders)} incomplete order(s)"
        }
    except Exception as e:
        logger.error(f"Database error getting incomplete orders: {e}")
        return {
            "success": False,
            "error": f"Failed to get incomplete orders: {str(e)}"
        }


def handle_count_drivers(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute count drivers tool

    Args:
        tool_input: Dict with optional filter fields
        user_id: Authenticated user ID

    Returns:
        Driver count result with breakdown
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Build WHERE clause based on filters
    # IMPORTANT: Always filter by user_id FIRST
    where_clauses = ["user_id = %s"]
    params = [user_id]

    if "status" in tool_input:
        where_clauses.append("status = %s")
        params.append(tool_input["status"])

    if "vehicle_type" in tool_input:
        where_clauses.append("vehicle_type = %s")
        params.append(tool_input["vehicle_type"])

    where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""

    # Total count query
    count_query = f"SELECT COUNT(*) as total FROM drivers{where_sql}"

    # Breakdown by status query
    status_query = f"""
        SELECT status, COUNT(*) as count
        FROM drivers{where_sql}
        GROUP BY status
        ORDER BY count DESC
    """

    # Breakdown by vehicle type query
    vehicle_query = f"""
        SELECT vehicle_type, COUNT(*) as count
        FROM drivers{where_sql}
        GROUP BY vehicle_type
        ORDER BY count DESC
    """

    try:
        # Execute queries
        total_result = execute_query(count_query, tuple(params) if params else None)
        total = total_result[0]['total'] if total_result else 0

        status_result = execute_query(status_query, tuple(params) if params else None)
        vehicle_result = execute_query(vehicle_query, tuple(params) if params else None)

        # Format breakdown
        status_breakdown = {row['status']: row['count'] for row in status_result} if status_result else {}
        vehicle_breakdown = {row['vehicle_type']: row['count'] for row in vehicle_result if row['vehicle_type']} if vehicle_result else {}

        logger.info(f"Counted drivers: {total} total")

        return {
            "success": True,
            "total": total,
            "status_breakdown": status_breakdown,
            "vehicle_breakdown": vehicle_breakdown,
            "message": f"Found {total} driver(s)"
        }
    except Exception as e:
        logger.error(f"Database error counting drivers: {e}")
        return {
            "success": False,
            "error": f"Failed to count drivers: {str(e)}"
        }


def handle_fetch_drivers(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute fetch drivers tool

    Args:
        tool_input: Dict with filter, pagination, and sorting options
        user_id: ID of authenticated user (filters to only their drivers)

    Returns:
        List of drivers matching criteria (only user's drivers)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    # Extract pagination and sorting
    limit = min(tool_input.get("limit", 10), 100)  # Cap at 100
    offset = tool_input.get("offset", 0)
    sort_by = tool_input.get("sort_by", "name")
    sort_order = tool_input.get("sort_order", "ASC")

    # Build WHERE clause based on filters
    # IMPORTANT: Always filter by user_id FIRST for security
    where_clauses = ["user_id = %s"]
    params = [user_id]

    if "status" in tool_input:
        where_clauses.append("status = %s")
        params.append(tool_input["status"])

    if "vehicle_type" in tool_input:
        where_clauses.append("vehicle_type = %s")
        params.append(tool_input["vehicle_type"])

    where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""

    # Build query
    query = f"""
        SELECT
            driver_id, name, phone, email,
            current_lat, current_lng, current_address, last_location_update,
            status, vehicle_type, vehicle_plate,
            capacity_kg, capacity_m3, skills,
            created_at, updated_at
        FROM drivers
        {where_sql}
        ORDER BY {sort_by} {sort_order}
        LIMIT %s OFFSET %s
    """

    params.extend([limit, offset])

    try:
        results = execute_query(query, tuple(params))

        if not results:
            return {
                "success": True,
                "drivers": [],
                "count": 0,
                "message": "No drivers found matching criteria"
            }

        # Format drivers for readability
        drivers = []
        for row in results:
            # Parse skills JSON if present
            skills = []
            if row['skills']:
                try:
                    import json
                    skills = json.loads(row['skills']) if isinstance(row['skills'], str) else row['skills']
                except:
                    skills = []

            driver = {
                "driver_id": row['driver_id'],
                "name": row['name'],
                "contact": {
                    "phone": row['phone'],
                    "email": row['email']
                },
                "location": {
                    "latitude": float(row['current_lat']) if row['current_lat'] else None,
                    "longitude": float(row['current_lng']) if row['current_lng'] else None,
                    "address": row['current_address'],
                    "last_update": str(row['last_location_update']) if row['last_location_update'] else None
                },
                "status": row['status'],
                "vehicle": {
                    "type": row['vehicle_type'],
                    "plate": row['vehicle_plate'],
                    "capacity_kg": float(row['capacity_kg']) if row['capacity_kg'] else None,
                    "capacity_m3": float(row['capacity_m3']) if row['capacity_m3'] else None
                },
                "skills": skills,
                "timestamps": {
                    "created_at": str(row['created_at']),
                    "updated_at": str(row['updated_at']) if row['updated_at'] else None
                }
            }
            drivers.append(driver)

        logger.info(f"Fetched {len(drivers)} drivers")

        return {
            "success": True,
            "drivers": drivers,
            "count": len(drivers),
            "message": f"Retrieved {len(drivers)} driver(s)"
        }
    except Exception as e:
        logger.error(f"Database error fetching drivers: {e}")
        return {
            "success": False,
            "error": f"Failed to fetch drivers: {str(e)}"
        }


def handle_get_driver_details(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute get driver details tool

    Args:
        tool_input: Dict with driver_id
        user_id: Authenticated user ID

    Returns:
        Complete driver details
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    driver_id = tool_input.get("driver_id")

    if not driver_id:
        return {
            "success": False,
            "error": "driver_id is required"
        }

    query = """
        SELECT
            driver_id, name, phone, email,
            current_lat, current_lng, current_address, last_location_update,
            status, vehicle_type, vehicle_plate,
            capacity_kg, capacity_m3, skills,
            created_at, updated_at
        FROM drivers
        WHERE driver_id = %s AND user_id = %s
    """

    try:
        results = execute_query(query, (driver_id, user_id))

        if not results:
            return {
                "success": False,
                "error": f"Driver {driver_id} not found"
            }

        row = results[0]

        # Parse skills JSON if present
        skills = []
        if row['skills']:
            try:
                import json
                skills = json.loads(row['skills']) if isinstance(row['skills'], str) else row['skills']
            except:
                skills = []

        # Use stored address from database, or reverse geocode if not available
        location_address = row['current_address']
        if not location_address and row['current_lat'] and row['current_lng']:
            try:
                reverse_result = safe_reverse_geocode(
                    float(row['current_lat']),
                    float(row['current_lng'])
                )
                location_address = reverse_result.get('address', None)
                logger.info(f"Reverse geocoded driver location: {location_address}")
            except Exception as e:
                logger.warning(f"Failed to reverse geocode driver location: {e}")
                location_address = None

        driver = {
            "driver_id": row['driver_id'],
            "name": row['name'],
            "contact": {
                "phone": row['phone'],
                "email": row['email']
            },
            "location": {
                "latitude": float(row['current_lat']) if row['current_lat'] else None,
                "longitude": float(row['current_lng']) if row['current_lng'] else None,
                "address": location_address,
                "last_update": str(row['last_location_update']) if row['last_location_update'] else None
            },
            "status": row['status'],
            "vehicle": {
                "type": row['vehicle_type'],
                "plate": row['vehicle_plate'],
                "capacity_kg": float(row['capacity_kg']) if row['capacity_kg'] else None,
                "capacity_m3": float(row['capacity_m3']) if row['capacity_m3'] else None
            },
            "skills": skills,
            "timestamps": {
                "created_at": str(row['created_at']),
                "updated_at": str(row['updated_at']) if row['updated_at'] else None
            }
        }

        logger.info(f"Retrieved details for driver: {driver_id}")

        return {
            "success": True,
            "driver": driver,
            "message": f"Driver {driver_id} details retrieved"
        }
    except Exception as e:
        logger.error(f"Database error getting driver details: {e}")
        return {
            "success": False,
            "error": f"Failed to get driver details: {str(e)}"
        }


def handle_search_drivers(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute search drivers tool

    Args:
        tool_input: Dict with search_term
        user_id: Authenticated user ID

    Returns:
        List of matching drivers
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    search_term = tool_input.get("search_term", "").strip()

    if not search_term:
        return {
            "success": False,
            "error": "search_term is required"
        }

    query = """
        SELECT
            driver_id, name, phone, email,
            current_lat, current_lng, current_address,
            vehicle_type, vehicle_plate, status, skills, created_at
        FROM drivers
        WHERE
            user_id = %s AND (
                driver_id ILIKE %s OR
                name ILIKE %s OR
                email ILIKE %s OR
                phone ILIKE %s OR
                vehicle_plate ILIKE %s
            )
        ORDER BY name ASC
        LIMIT 50
    """

    search_pattern = f"%{search_term}%"
    params = (user_id, search_pattern, search_pattern, search_pattern, search_pattern, search_pattern)

    try:
        results = execute_query(query, params)

        if not results:
            return {
                "success": True,
                "drivers": [],
                "count": 0,
                "message": f"No drivers found matching '{search_term}'"
            }

        drivers = []
        for row in results:
            # Parse skills JSON if present
            skills = []
            if row['skills']:
                try:
                    import json
                    skills = json.loads(row['skills']) if isinstance(row['skills'], str) else row['skills']
                except:
                    skills = []

            drivers.append({
                "driver_id": row['driver_id'],
                "name": row['name'],
                "phone": row['phone'],
                "email": row['email'],
                "location": {
                    "latitude": float(row['current_lat']) if row['current_lat'] else None,
                    "longitude": float(row['current_lng']) if row['current_lng'] else None,
                    "address": row['current_address']
                },
                "vehicle_type": row['vehicle_type'],
                "vehicle_plate": row['vehicle_plate'],
                "status": row['status'],
                "skills": skills,
                "created_at": str(row['created_at'])
            })

        logger.info(f"Search '{search_term}' found {len(drivers)} drivers")

        return {
            "success": True,
            "drivers": drivers,
            "count": len(drivers),
            "message": f"Found {len(drivers)} driver(s) matching '{search_term}'"
        }
    except Exception as e:
        logger.error(f"Database error searching drivers: {e}")
        return {
            "success": False,
            "error": f"Failed to search drivers: {str(e)}"
        }


def handle_get_available_drivers(tool_input: dict, user_id: str = None) -> dict:
    """
    Execute get available drivers tool

    Args:
        tool_input: Dict with optional limit
        user_id: Authenticated user ID

    Returns:
        List of available drivers (active or offline)
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    limit = min(tool_input.get("limit", 20), 100)

    query = """
        SELECT
            driver_id, name, phone, vehicle_type, vehicle_plate,
            current_lat, current_lng, current_address, last_location_update,
            status, capacity_kg, capacity_m3, skills
        FROM drivers
        WHERE user_id = %s AND status IN ('active', 'offline')
        ORDER BY
            CASE status
                WHEN 'active' THEN 1
                WHEN 'offline' THEN 2
            END,
            name ASC
        LIMIT %s
    """

    try:
        results = execute_query(query, (user_id, limit))

        if not results:
            return {
                "success": True,
                "drivers": [],
                "count": 0,
                "message": "No available drivers found"
            }

        drivers = []
        for row in results:
            # Parse skills JSON if present
            skills = []
            if row['skills']:
                try:
                    import json
                    skills = json.loads(row['skills']) if isinstance(row['skills'], str) else row['skills']
                except:
                    skills = []

            drivers.append({
                "driver_id": row['driver_id'],
                "name": row['name'],
                "phone": row['phone'],
                "location": {
                    "latitude": float(row['current_lat']) if row['current_lat'] else None,
                    "longitude": float(row['current_lng']) if row['current_lng'] else None,
                    "address": row['current_address'],
                    "last_update": str(row['last_location_update']) if row['last_location_update'] else None
                },
                "status": row['status'],
                "vehicle": {
                    "type": row['vehicle_type'],
                    "plate": row['vehicle_plate'],
                    "capacity_kg": float(row['capacity_kg']) if row['capacity_kg'] else None,
                    "capacity_m3": float(row['capacity_m3']) if row['capacity_m3'] else None
                },
                "skills": skills
            })

        logger.info(f"Retrieved {len(drivers)} available drivers")

        return {
            "success": True,
            "drivers": drivers,
            "count": len(drivers),
            "message": f"Found {len(drivers)} available driver(s)"
        }
    except Exception as e:
        logger.error(f"Database error getting available drivers: {e}")
        return {
            "success": False,
            "error": f"Failed to get available drivers: {str(e)}"
        }


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

def handle_create_assignment(tool_input: dict, user_id: str = None) -> dict:
    """
    Create assignment (assign order to driver)

    Validates order and driver status, calculates route, creates assignment record,
    and updates order/driver statuses.

    Args:
        tool_input: Dict with order_id and driver_id
        user_id: Authenticated user ID

    Returns:
        Assignment creation result with route data
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    from datetime import datetime, timedelta

    order_id = (tool_input.get("order_id") or "").strip()
    driver_id = (tool_input.get("driver_id") or "").strip()

    if not order_id or not driver_id:
        return {
            "success": False,
            "error": "Both order_id and driver_id are required"
        }

    logger.info(f"Creating assignment: order={order_id}, driver={driver_id}")

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Step 1: Validate order exists, belongs to user, and status is "pending"
        cursor.execute("""
            SELECT status, delivery_lat, delivery_lng, delivery_address, assigned_driver_id
            FROM orders
            WHERE order_id = %s AND user_id = %s
        """, (order_id, user_id))

        order_row = cursor.fetchone()
        if not order_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Order not found: {order_id}"
            }

        order_status = order_row['status']
        delivery_lat = order_row['delivery_lat']
        delivery_lng = order_row['delivery_lng']
        delivery_address = order_row['delivery_address']
        current_driver = order_row['assigned_driver_id']

        if order_status != "pending":
            cursor.close()
            conn.close()

            # Provide helpful error message based on current status
            if order_status == "assigned" and current_driver:
                # Get current driver name for better error message
                cursor2 = get_db_connection().cursor()
                cursor2.execute("SELECT name FROM drivers WHERE driver_id = %s", (current_driver,))
                driver_row = cursor2.fetchone()
                driver_name = driver_row['name'] if driver_row else current_driver
                cursor2.close()

                return {
                    "success": False,
                    "error": f"Order {order_id} is already assigned to driver {driver_name}. Use 'unassign_order' first to reassign to a different driver."
                }
            else:
                return {
                    "success": False,
                    "error": f"Order must be in 'pending' status to be assigned. Current status: '{order_status}'"
                }

        if not delivery_lat or not delivery_lng:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Order does not have delivery location coordinates"
            }

        # Step 2: Validate driver exists, belongs to user, and status is "active"
        cursor.execute("""
            SELECT status, current_lat, current_lng, vehicle_type, name
            FROM drivers
            WHERE driver_id = %s AND user_id = %s
        """, (driver_id, user_id))

        driver_row = cursor.fetchone()
        if not driver_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Driver not found: {driver_id}"
            }

        driver_status = driver_row['status']
        driver_lat = driver_row['current_lat']
        driver_lng = driver_row['current_lng']
        vehicle_type = driver_row['vehicle_type']
        driver_name = driver_row['name']

        if driver_status not in ["active", "available"]:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Driver must be 'active' or 'available'. Current status: {driver_status}"
            }

        if not driver_lat or not driver_lng:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Driver does not have current location"
            }

        # Step 3: Check if order already has active assignment
        cursor.execute("""
            SELECT assignment_id, driver_id
            FROM assignments
            WHERE order_id = %s AND status IN ('active', 'in_progress')
        """, (order_id,))

        existing_assignment = cursor.fetchone()
        if existing_assignment:
            cursor.close()
            conn.close()
            existing_asn_id = existing_assignment['assignment_id']
            existing_driver_id = existing_assignment['driver_id']

            # Get driver name for better error message
            cursor2 = get_db_connection().cursor()
            cursor2.execute("SELECT name FROM drivers WHERE driver_id = %s", (existing_driver_id,))
            driver_row = cursor2.fetchone()
            existing_driver_name = driver_row['name'] if driver_row else existing_driver_id
            cursor2.close()

            return {
                "success": False,
                "error": f"Order {order_id} is already assigned to driver {existing_driver_name} (Assignment: {existing_asn_id}). Use 'unassign_order' first to reassign."
            }

        # Step 4: Calculate route from driver location to delivery location
        logger.info(f"Calculating route: ({driver_lat},{driver_lng}) -> ({delivery_lat},{delivery_lng})")

        route_result = handle_calculate_route({
            "origin": f"{driver_lat},{driver_lng}",
            "destination": f"{delivery_lat},{delivery_lng}",
            "vehicle_type": vehicle_type or "car",
            "alternatives": False,
            "include_steps": True  # Get turn-by-turn directions
        })

        if not route_result.get("success"):
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Route calculation failed: {route_result.get('error', 'Unknown error')}"
            }

        # Step 5: Generate assignment ID
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
        assignment_id = f"ASN-{timestamp}"

        # Step 6: Calculate estimated arrival
        duration_seconds = route_result.get("duration_in_traffic", {}).get("seconds", 0)
        estimated_arrival = datetime.now() + timedelta(seconds=duration_seconds)

        # Step 7: Create assignment record
        import json

        # Extract route directions (turn-by-turn steps)
        route_directions = route_result.get("steps", [])
        route_directions_json = json.dumps(route_directions) if route_directions else None

        cursor.execute("""
            INSERT INTO assignments (
                assignment_id, order_id, driver_id, user_id,
                route_distance_meters, route_duration_seconds, route_duration_in_traffic_seconds,
                route_summary, route_confidence, route_directions,
                driver_start_location_lat, driver_start_location_lng,
                delivery_location_lat, delivery_location_lng, delivery_address,
                estimated_arrival, vehicle_type, traffic_delay_seconds,
                status
            ) VALUES (
                %s, %s, %s, %s,
                %s, %s, %s,
                %s, %s, %s,
                %s, %s,
                %s, %s, %s,
                %s, %s, %s,
                %s
            )
        """, (
            assignment_id, order_id, driver_id, user_id,
            route_result.get("distance", {}).get("meters", 0),
            route_result.get("duration", {}).get("seconds", 0),
            route_result.get("duration_in_traffic", {}).get("seconds", 0),
            route_result.get("route_summary", ""),
            route_result.get("confidence", ""),
            route_directions_json,
            driver_lat, driver_lng,
            delivery_lat, delivery_lng, delivery_address,
            estimated_arrival, vehicle_type,
            route_result.get("traffic_delay", {}).get("seconds", 0),
            "active"
        ))

        # Step 8: Update order status and assigned driver
        cursor.execute("""
            UPDATE orders
            SET status = 'assigned', assigned_driver_id = %s
            WHERE order_id = %s
        """, (driver_id, order_id))

        # Step 9: Update driver status to busy
        cursor.execute("""
            UPDATE drivers
            SET status = 'busy'
            WHERE driver_id = %s
        """, (driver_id,))

        conn.commit()
        cursor.close()
        conn.close()

        logger.info(f"Assignment created successfully: {assignment_id}")

        return {
            "success": True,
            "assignment_id": assignment_id,
            "order_id": order_id,
            "driver_id": driver_id,
            "driver_name": driver_name,
            "route": {
                "distance": route_result.get("distance", {}).get("text", ""),
                "duration": route_result.get("duration", {}).get("text", ""),
                "duration_in_traffic": route_result.get("duration_in_traffic", {}).get("text", ""),
                "traffic_delay": route_result.get("traffic_delay", {}).get("text", ""),
                "summary": route_result.get("route_summary", ""),
                "directions": route_directions  # Turn-by-turn navigation steps
            },
            "estimated_arrival": estimated_arrival.isoformat(),
            "status": "active",
            "message": f"Order {order_id} assigned to driver {driver_name} ({driver_id})"
        }

    except Exception as e:
        logger.error(f"Failed to create assignment: {e}")
        return {
            "success": False,
            "error": f"Failed to create assignment: {str(e)}"
        }


def handle_auto_assign_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Automatically assign order to nearest available driver (distance + validation based).

    Selection criteria:
    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

    Args:
        tool_input: Dict with order_id
        user_id: Authenticated user ID

    Returns:
        Assignment details with selected driver info and distance
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    order_id = (tool_input.get("order_id") or "").strip()

    if not order_id:
        return {
            "success": False,
            "error": "Missing required field: order_id"
        }

    try:
        conn = get_db_connection()
        cursor = conn.cursor(cursor_factory=RealDictCursor)

        # Step 1: Get order details with ALL requirements (filtered by user_id)
        cursor.execute("""
            SELECT
                order_id, customer_name, delivery_address,
                delivery_lat, delivery_lng, status,
                weight_kg, volume_m3, is_fragile,
                requires_cold_storage, requires_signature,
                priority, assigned_driver_id
            FROM orders
            WHERE order_id = %s AND user_id = %s
        """, (order_id, user_id))

        order = cursor.fetchone()

        if not order:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Order not found: {order_id}"
            }

        if order['status'] != 'pending':
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Order must be 'pending' to auto-assign. Current status: {order['status']}"
            }

        if not order['delivery_lat'] or not order['delivery_lng']:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Order missing delivery coordinates. Cannot calculate routes."
            }

        # Extract order requirements
        required_weight_kg = order['weight_kg'] or 0
        required_volume_m3 = order['volume_m3'] or 0
        needs_fragile_handling = order['is_fragile'] or False
        needs_cold_storage = order['requires_cold_storage'] or False

        # Step 2: Get all active drivers with valid locations (filtered by user_id)
        cursor.execute("""
            SELECT
                driver_id, name, phone, current_lat, current_lng,
                vehicle_type, capacity_kg, capacity_m3, skills
            FROM drivers
            WHERE user_id = %s
                AND status = 'active'
                AND current_lat IS NOT NULL
                AND current_lng IS NOT NULL
        """, (user_id,))

        active_drivers = cursor.fetchall()

        if not active_drivers:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "No active drivers available with valid location"
            }

        # Step 3: Filter and score each driver
        suitable_drivers = []

        for driver in active_drivers:
            # Validate capacity (weight and volume)
            driver_capacity_kg = driver['capacity_kg'] or 0
            driver_capacity_m3 = driver['capacity_m3'] or 0

            if driver_capacity_kg < required_weight_kg:
                logger.info(f"Driver {driver['driver_id']} ({driver['name']}) - Insufficient weight capacity: {driver_capacity_kg}kg < {required_weight_kg}kg")
                continue

            if driver_capacity_m3 < required_volume_m3:
                logger.info(f"Driver {driver['driver_id']} ({driver['name']}) - Insufficient volume capacity: {driver_capacity_m3}m³ < {required_volume_m3}m³")
                continue

            # Validate skills
            driver_skills = driver['skills'] or []

            if needs_fragile_handling and "fragile_handler" not in driver_skills:
                logger.info(f"Driver {driver['driver_id']} ({driver['name']}) - Missing fragile_handler skill")
                continue

            if needs_cold_storage and "refrigerated" not in driver_skills:
                logger.info(f"Driver {driver['driver_id']} ({driver['name']}) - Missing refrigerated skill")
                continue

            # Step 4: Calculate real-time route distance
            route_result = handle_calculate_route({
                "origin": f"{driver['current_lat']},{driver['current_lng']}",
                "destination": f"{order['delivery_lat']},{order['delivery_lng']}",
                "vehicle_type": driver['vehicle_type'],
                "include_steps": False  # We don't need turn-by-turn for scoring
            })

            if not route_result.get("success"):
                logger.warning(f"Driver {driver['driver_id']} ({driver['name']}) - Route calculation failed: {route_result.get('error')}")
                continue

            # Extract distance
            distance_meters = route_result.get('distance_meters', 999999)
            duration_seconds = route_result.get('duration_in_traffic_seconds', 0)

            suitable_drivers.append({
                "driver": driver,
                "distance_meters": distance_meters,
                "distance_km": distance_meters / 1000,
                "duration_seconds": duration_seconds,
                "duration_minutes": duration_seconds / 60,
                "route_data": route_result
            })

        if not suitable_drivers:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "No suitable drivers found. All active drivers failed capacity or skill requirements."
            }

        # Step 5: Sort by distance (nearest first)
        suitable_drivers.sort(key=lambda x: x['distance_meters'])

        # Step 6: Select nearest driver
        best_match = suitable_drivers[0]
        selected_driver = best_match['driver']

        logger.info(f"Auto-assign: Selected driver {selected_driver['driver_id']} ({selected_driver['name']}) - {best_match['distance_km']:.2f}km away")

        cursor.close()
        conn.close()

        # Step 7: Create assignment using existing function
        assignment_result = handle_create_assignment({
            "order_id": order_id,
            "driver_id": selected_driver['driver_id']
        }, user_id=user_id)

        if not assignment_result.get("success"):
            return assignment_result

        # Step 8: Return enhanced response with selection info
        return {
            "success": True,
            "assignment_id": assignment_result['assignment_id'],
            "method": "auto_assignment",
            "order_id": order_id,
            "driver_id": selected_driver['driver_id'],
            "driver_name": selected_driver['name'],
            "driver_phone": selected_driver['phone'],
            "driver_vehicle_type": selected_driver['vehicle_type'],
            "selection_reason": "Nearest available driver meeting all requirements",
            "distance_km": round(best_match['distance_km'], 2),
            "distance_meters": best_match['distance_meters'],
            "estimated_duration_minutes": round(best_match['duration_minutes'], 1),
            "candidates_evaluated": len(active_drivers),
            "suitable_candidates": len(suitable_drivers),
            "route_summary": assignment_result.get('route_summary'),
            "estimated_arrival": assignment_result.get('estimated_arrival'),
            "assignment_details": assignment_result
        }

    except Exception as e:
        logger.error(f"Failed to auto-assign order: {e}")
        return {
            "success": False,
            "error": f"Failed to auto-assign order: {str(e)}"
        }


def handle_intelligent_assign_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Intelligently assign order using Gemini AI to analyze all parameters.

    Uses Google's Gemini AI to evaluate:
    - Order characteristics (priority, weight, fragility, time constraints)
    - All available drivers (location, capacity, skills, vehicle type)
    - Real-time routing data (distance, traffic, weather)
    - Complex tradeoffs and optimal matching

    Returns assignment with AI reasoning explaining the selection.

    Args:
        tool_input: Dict with order_id
        user_id: Authenticated user ID

    Returns:
        Assignment details with AI reasoning and selected driver info
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    import os
    import json
    import google.generativeai as genai
    from datetime import datetime

    order_id = (tool_input.get("order_id") or "").strip()

    if not order_id:
        return {
            "success": False,
            "error": "Missing required field: order_id"
        }

    # Check for Gemini API key
    gemini_api_key = os.getenv("GOOGLE_API_KEY")
    if not gemini_api_key:
        return {
            "success": False,
            "error": "GOOGLE_API_KEY environment variable not set. Required for intelligent assignment."
        }

    try:
        conn = get_db_connection()
        cursor = conn.cursor(cursor_factory=RealDictCursor)

        # Step 1: Get complete order details (filtered by user_id)
        cursor.execute("""
            SELECT
                order_id, customer_name, customer_phone, customer_email,
                delivery_address, delivery_lat, delivery_lng,
                pickup_address, pickup_lat, pickup_lng,
                time_window_start, time_window_end, expected_delivery_time,
                priority, weight_kg, volume_m3, order_value,
                is_fragile, requires_cold_storage, requires_signature,
                payment_status, special_instructions, status,
                created_at, sla_grace_period_minutes
            FROM orders
            WHERE order_id = %s AND user_id = %s
        """, (order_id, user_id))

        order = cursor.fetchone()

        if not order:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Order not found: {order_id}"
            }

        if order['status'] != 'pending':
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Order must be 'pending' to assign. Current status: {order['status']}"
            }

        if not order['delivery_lat'] or not order['delivery_lng']:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Order missing delivery coordinates. Cannot calculate routes."
            }

        # Step 2: Get all active drivers with complete details (filtered by user_id)
        cursor.execute("""
            SELECT
                driver_id, name, phone, email,
                current_lat, current_lng, last_location_update,
                vehicle_type, vehicle_plate, capacity_kg, capacity_m3,
                skills, status, created_at, updated_at
            FROM drivers
            WHERE user_id = %s
                AND status = 'active'
                AND current_lat IS NOT NULL
                AND current_lng IS NOT NULL
        """, (user_id,))

        active_drivers = cursor.fetchall()

        if not active_drivers:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "No active drivers available with valid location"
            }

        # Step 3: Calculate routing data for each driver
        drivers_with_routes = []

        for driver in active_drivers:
            # Calculate route with traffic
            route_result = handle_calculate_route({
                "origin": f"{driver['current_lat']},{driver['current_lng']}",
                "destination": f"{order['delivery_lat']},{order['delivery_lng']}",
                "vehicle_type": driver['vehicle_type'],
                "include_steps": False
            })

            # Get weather-aware routing if available
            try:
                intelligent_route = handle_calculate_intelligent_route({
                    "origin": f"{driver['current_lat']},{driver['current_lng']}",
                    "destination": f"{order['delivery_lat']},{order['delivery_lng']}",
                    "vehicle_type": driver['vehicle_type']
                })
                weather_data = intelligent_route.get('weather', {})
            except:
                weather_data = {}

            if route_result.get("success"):
                drivers_with_routes.append({
                    "driver_id": driver['driver_id'],
                    "name": driver['name'],
                    "phone": driver['phone'],
                    "vehicle_type": driver['vehicle_type'],
                    "vehicle_plate": driver['vehicle_plate'],
                    "capacity_kg": float(driver['capacity_kg']) if driver['capacity_kg'] else 0,
                    "capacity_m3": float(driver['capacity_m3']) if driver['capacity_m3'] else 0,
                    "skills": driver['skills'] or [],
                    "current_location": {
                        "lat": float(driver['current_lat']),
                        "lng": float(driver['current_lng'])
                    },
                    "route_to_delivery": {
                        "distance_km": round(route_result.get('distance_meters', 0) / 1000, 2),
                        "distance_meters": route_result.get('distance_meters', 0),
                        "duration_minutes": round(route_result.get('duration_in_traffic_seconds', 0) / 60, 1),
                        "traffic_delay_seconds": route_result.get('traffic_delay_seconds', 0),
                        "route_summary": route_result.get('route_summary', ''),
                        "has_tolls": route_result.get('has_tolls', False)
                    },
                    "weather_conditions": weather_data
                })

        if not drivers_with_routes:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Unable to calculate routes for any active drivers"
            }

        cursor.close()
        conn.close()

        # Step 4: Build comprehensive context for Gemini
        order_context = {
            "order_id": order['order_id'],
            "customer": {
                "name": order['customer_name'],
                "phone": order['customer_phone']
            },
            "delivery": {
                "address": order['delivery_address'],
                "coordinates": {"lat": float(order['delivery_lat']), "lng": float(order['delivery_lng'])}
            },
            "time_constraints": {
                "expected_delivery_time": str(order['expected_delivery_time']) if order['expected_delivery_time'] else None,
                "time_window_start": str(order['time_window_start']) if order['time_window_start'] else None,
                "time_window_end": str(order['time_window_end']) if order['time_window_end'] else None,
                "sla_grace_period_minutes": order['sla_grace_period_minutes'],
                "created_at": str(order['created_at'])
            },
            "package": {
                "weight_kg": float(order['weight_kg']) if order['weight_kg'] else 0,
                "volume_m3": float(order['volume_m3']) if order['volume_m3'] else 0,
                "value": float(order['order_value']) if order['order_value'] else 0,
                "is_fragile": order['is_fragile'] or False,
                "requires_cold_storage": order['requires_cold_storage'] or False,
                "requires_signature": order['requires_signature'] or False
            },
            "priority": order['priority'],
            "payment_status": order['payment_status'],
            "special_instructions": order['special_instructions']
        }

        # Step 5: Call Gemini AI for intelligent decision
        genai.configure(api_key=gemini_api_key)
        model = genai.GenerativeModel('gemini-2.0-flash-exp')

        prompt = f"""You are an intelligent fleet management AI. Analyze the following delivery order and available drivers to select the BEST driver for this assignment.

**ORDER DETAILS:**
{json.dumps(order_context, indent=2)}

**AVAILABLE DRIVERS ({len(drivers_with_routes)}):**
{json.dumps(drivers_with_routes, indent=2)}

**CURRENT TIME:** {datetime.now().isoformat()}

**YOUR TASK:**
Analyze ALL parameters comprehensively:
1. **Distance & Route Efficiency**: Consider route distance, traffic delays, tolls
2. **Vehicle Matching**: Match vehicle type and capacity to package requirements
3. **Skills Requirements**: Ensure driver has necessary skills (fragile handling, cold storage)
4. **Time Constraints**: Evaluate ability to meet expected delivery time
5. **Priority Level**: Factor in order priority (urgent > express > standard)
6. **Weather Conditions**: Consider weather impact on delivery safety and speed
7. **Special Requirements**: Account for signature requirements, special instructions
8. **Cost Efficiency**: Consider fuel costs, toll roads, driver utilization

**RESPONSE FORMAT (JSON only, no markdown):**
{{
  "selected_driver_id": "DRV-XXXXXXXXX",
  "confidence_score": 0.95,
  "reasoning": {{
    "primary_factors": ["Nearest driver (5.2km)", "Has fragile_handler skill", "Sufficient capacity"],
    "trade_offs_considered": ["Driver A was 1km closer but lacked required skills", "Driver B had larger capacity but 15min further"],
    "risk_assessment": "Low risk - clear weather, light traffic, experienced driver",
    "decision_summary": "Selected Driver X because they offer the best balance of proximity (5.2km), required skills (fragile_handler), and adequate capacity (10kg) for this urgent fragile delivery."
  }},
  "alternatives": [
    {{"driver_id": "DRV-YYY", "reason_not_selected": "Missing fragile_handler skill"}},
    {{"driver_id": "DRV-ZZZ", "reason_not_selected": "15 minutes further away"}}
  ]
}}

**IMPORTANT:** Return ONLY valid JSON. Do not include markdown formatting, code blocks, or explanatory text outside the JSON."""

        # Call Gemini with timeout protection (30 seconds max)
        try:
            future = _blocking_executor.submit(model.generate_content, prompt)
            response = future.result(timeout=30)
        except FuturesTimeoutError:
            logger.error("Gemini AI call timed out after 30 seconds")
            return {
                "success": False,
                "error": "AI assignment timed out. Please try auto_assign_order instead."
            }
        response_text = response.text.strip()

        # Clean response (remove markdown code blocks if present)
        if response_text.startswith("```json"):
            response_text = response_text[7:]
        if response_text.startswith("```"):
            response_text = response_text[3:]
        if response_text.endswith("```"):
            response_text = response_text[:-3]
        response_text = response_text.strip()

        # Parse Gemini response
        try:
            ai_decision = json.loads(response_text)
        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse Gemini response: {e}")
            logger.error(f"Response text: {response_text}")
            return {
                "success": False,
                "error": f"Failed to parse AI response. Invalid JSON returned by Gemini: {str(e)}"
            }

        selected_driver_id = ai_decision.get("selected_driver_id")

        if not selected_driver_id:
            return {
                "success": False,
                "error": "AI did not select a driver"
            }

        # Validate selected driver is still available
        selected_driver = next((d for d in drivers_with_routes if d["driver_id"] == selected_driver_id), None)

        if not selected_driver:
            return {
                "success": False,
                "error": f"AI selected driver {selected_driver_id} but driver not found in available list"
            }

        # Step 6: Create assignment using existing function
        logger.info(f"Intelligent-assign: AI selected driver {selected_driver_id} ({selected_driver['name']})")

        assignment_result = handle_create_assignment({
            "order_id": order_id,
            "driver_id": selected_driver_id
        }, user_id=user_id)

        if not assignment_result.get("success"):
            return assignment_result

        # Step 7: Return enhanced response with AI reasoning
        return {
            "success": True,
            "assignment_id": assignment_result['assignment_id'],
            "method": "intelligent_assignment",
            "ai_provider": "Google Gemini 2.0 Flash",
            "ai_model": "gemini-2.0-flash-exp",
            "order_id": order_id,
            "driver_id": selected_driver_id,
            "driver_name": selected_driver['name'],
            "driver_phone": selected_driver['phone'],
            "driver_vehicle_type": selected_driver['vehicle_type'],
            "distance_km": selected_driver['route_to_delivery']['distance_km'],
            "estimated_duration_minutes": selected_driver['route_to_delivery']['duration_minutes'],
            "ai_reasoning": ai_decision.get('reasoning', {}),
            "confidence_score": ai_decision.get('confidence_score', 0),
            "alternatives_considered": ai_decision.get('alternatives', []),
            "candidates_evaluated": len(drivers_with_routes),
            "route_summary": assignment_result.get('route_summary'),
            "estimated_arrival": assignment_result.get('estimated_arrival'),
            "assignment_details": assignment_result
        }

    except Exception as e:
        logger.error(f"Failed to intelligently assign order: {e}")
        return {
            "success": False,
            "error": f"Failed to intelligently assign order: {str(e)}"
        }


def handle_get_assignment_details(tool_input: dict, user_id: str = None) -> dict:
    """
    Get assignment details

    Can query by assignment_id, order_id, or driver_id.
    Returns assignment with route data and related order/driver info.

    Args:
        tool_input: Dict with assignment_id, order_id, or driver_id
        user_id: Authenticated user ID

    Returns:
        Assignment details or list of assignments
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    assignment_id = (tool_input.get("assignment_id") or "").strip()
    order_id = (tool_input.get("order_id") or "").strip()
    driver_id = (tool_input.get("driver_id") or "").strip()

    if not assignment_id and not order_id and not driver_id:
        return {
            "success": False,
            "error": "Provide at least one of: assignment_id, order_id, or driver_id"
        }

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Build query based on provided parameters (filtered by user_id)
        query = """
            SELECT
                a.assignment_id, a.order_id, a.driver_id, a.status,
                a.assigned_at, a.updated_at, a.estimated_arrival, a.actual_arrival,
                a.route_distance_meters, a.route_duration_seconds, a.route_duration_in_traffic_seconds,
                a.route_summary, a.route_confidence, a.traffic_delay_seconds, a.route_directions,
                a.driver_start_location_lat, a.driver_start_location_lng,
                a.delivery_location_lat, a.delivery_location_lng, a.delivery_address,
                a.vehicle_type, a.sequence_number, a.notes, a.failure_reason,
                o.customer_name, o.status as order_status,
                d.name as driver_name, d.status as driver_status, d.phone as driver_phone
            FROM assignments a
            LEFT JOIN orders o ON a.order_id = o.order_id
            LEFT JOIN drivers d ON a.driver_id = d.driver_id
            WHERE a.user_id = %s
        """

        params = [user_id]

        if assignment_id:
            query += " AND a.assignment_id = %s"
            params.append(assignment_id)

        if order_id:
            query += " AND a.order_id = %s"
            params.append(order_id)

        if driver_id:
            query += " AND a.driver_id = %s"
            params.append(driver_id)

        query += " ORDER BY a.assigned_at DESC"

        cursor.execute(query, params)
        rows = cursor.fetchall()

        cursor.close()
        conn.close()

        if not rows:
            return {
                "success": False,
                "error": "No assignments found matching criteria"
            }

        # Format results
        assignments = []
        for row in rows:
            assignment = {
                "assignment_id": row['assignment_id'],
                "order_id": row['order_id'],
                "driver_id": row['driver_id'],
                "status": row['status'],
                "assigned_at": row['assigned_at'].isoformat() if row['assigned_at'] else None,
                "updated_at": row['updated_at'].isoformat() if row['updated_at'] else None,
                "estimated_arrival": row['estimated_arrival'].isoformat() if row['estimated_arrival'] else None,
                "actual_arrival": row['actual_arrival'].isoformat() if row['actual_arrival'] else None,
                "route": {
                    "distance_meters": row['route_distance_meters'],
                    "distance_km": round(row['route_distance_meters'] / 1000, 2) if row['route_distance_meters'] else 0,
                    "duration_seconds": row['route_duration_seconds'],
                    "duration_minutes": round(row['route_duration_seconds'] / 60, 1) if row['route_duration_seconds'] else 0,
                    "duration_in_traffic_seconds": row['route_duration_in_traffic_seconds'],
                    "duration_in_traffic_minutes": round(row['route_duration_in_traffic_seconds'] / 60, 1) if row['route_duration_in_traffic_seconds'] else 0,
                    "summary": row['route_summary'],
                    "confidence": row['route_confidence'],
                    "traffic_delay_seconds": row['traffic_delay_seconds'],
                    "traffic_delay_minutes": round(row['traffic_delay_seconds'] / 60, 1) if row['traffic_delay_seconds'] else 0,
                    "directions": row['route_directions']  # Turn-by-turn navigation steps
                },
                "driver_start_location": {
                    "lat": float(row['driver_start_location_lat']) if row['driver_start_location_lat'] else None,
                    "lng": float(row['driver_start_location_lng']) if row['driver_start_location_lng'] else None
                },
                "delivery_location": {
                    "lat": float(row['delivery_location_lat']) if row['delivery_location_lat'] else None,
                    "lng": float(row['delivery_location_lng']) if row['delivery_location_lng'] else None,
                    "address": row['delivery_address']
                },
                "vehicle_type": row['vehicle_type'],
                "sequence_number": row['sequence_number'],
                "notes": row['notes'],
                "failure_reason": row['failure_reason'],
                "order": {
                    "customer_name": row['customer_name'],
                    "status": row['order_status']
                },
                "driver": {
                    "name": row['driver_name'],
                    "status": row['driver_status'],
                    "phone": row['driver_phone']
                }
            }
            assignments.append(assignment)

        if assignment_id and len(assignments) == 1:
            # Single assignment query
            return {
                "success": True,
                "assignment": assignments[0]
            }
        else:
            # Multiple assignments
            return {
                "success": True,
                "count": len(assignments),
                "assignments": assignments
            }

    except Exception as e:
        logger.error(f"Failed to get assignment details: {e}")
        return {
            "success": False,
            "error": f"Failed to get assignment details: {str(e)}"
        }


def handle_update_assignment(tool_input: dict, user_id: str = None) -> dict:
    """
    Update assignment status

    Allows updating assignment status and actual metrics.
    Manages cascading updates to order and driver statuses.

    Args:
        tool_input: Dict with assignment_id, status (optional), actual_arrival (optional), notes (optional)
        user_id: Authenticated user ID

    Returns:
        Update result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    from datetime import datetime

    assignment_id = (tool_input.get("assignment_id") or "").strip()
    new_status = (tool_input.get("status") or "").strip().lower()
    actual_arrival = tool_input.get("actual_arrival")
    notes = (tool_input.get("notes") or "").strip()

    if not assignment_id:
        return {
            "success": False,
            "error": "assignment_id is required"
        }

    if not new_status and not actual_arrival and not notes:
        return {
            "success": False,
            "error": "Provide at least one field to update: status, actual_arrival, or notes"
        }

    # Validate status if provided
    valid_statuses = ["active", "in_progress", "completed", "failed", "cancelled"]
    if new_status and new_status not in valid_statuses:
        return {
            "success": False,
            "error": f"Invalid status. Must be one of: {', '.join(valid_statuses)}"
        }

    logger.info(f"Updating assignment: {assignment_id}, status={new_status}")

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Get current assignment details (filtered by user_id)
        cursor.execute("""
            SELECT status, order_id, driver_id
            FROM assignments
            WHERE assignment_id = %s AND user_id = %s
        """, (assignment_id, user_id))

        assignment_row = cursor.fetchone()
        if not assignment_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Assignment not found: {assignment_id}"
            }

        current_status = assignment_row['status']
        order_id = assignment_row['order_id']
        driver_id = assignment_row['driver_id']

        # Validate status transitions
        if new_status:
            # Cannot go backwards
            if current_status == "completed" and new_status in ["active", "in_progress"]:
                cursor.close()
                conn.close()
                return {
                    "success": False,
                    "error": "Cannot change status from 'completed' back to 'active' or 'in_progress'"
                }

            if current_status == "failed" and new_status != "failed":
                cursor.close()
                conn.close()
                return {
                    "success": False,
                    "error": "Cannot change status from 'failed'"
                }

            if current_status == "cancelled" and new_status != "cancelled":
                cursor.close()
                conn.close()
                return {
                    "success": False,
                    "error": "Cannot change status from 'cancelled'"
                }

        # Build update query
        updates = []
        params = []

        if new_status:
            updates.append("status = %s")
            params.append(new_status)

        if actual_arrival:
            updates.append("actual_arrival = %s")
            params.append(actual_arrival)

        if notes:
            updates.append("notes = %s")
            params.append(notes)

        params.append(assignment_id)

        # Update assignment
        cursor.execute(f"""
            UPDATE assignments
            SET {', '.join(updates)}
            WHERE assignment_id = %s
        """, params)

        # Handle cascading updates based on new status
        if new_status:
            if new_status in ["completed", "failed", "cancelled"]:
                # Update order status
                if new_status == "completed":
                    cursor.execute("""
                        UPDATE orders
                        SET status = 'delivered'
                        WHERE order_id = %s
                    """, (order_id,))

                elif new_status == "failed":
                    cursor.execute("""
                        UPDATE orders
                        SET status = 'failed'
                        WHERE order_id = %s
                    """, (order_id,))

                elif new_status == "cancelled":
                    cursor.execute("""
                        UPDATE orders
                        SET status = 'cancelled', assigned_driver_id = NULL
                        WHERE order_id = %s
                    """, (order_id,))

                # Check if driver has other active assignments
                cursor.execute("""
                    SELECT COUNT(*) as count
                    FROM assignments
                    WHERE driver_id = %s AND status IN ('active', 'in_progress') AND assignment_id != %s
                """, (driver_id, assignment_id))

                other_assignments_count = cursor.fetchone()['count']

                # If no other active assignments, set driver back to active
                if other_assignments_count == 0:
                    cursor.execute("""
                        UPDATE drivers
                        SET status = 'active'
                        WHERE driver_id = %s
                    """, (driver_id,))

        conn.commit()
        cursor.close()
        conn.close()

        logger.info(f"Assignment updated successfully: {assignment_id}")

        return {
            "success": True,
            "assignment_id": assignment_id,
            "updated_fields": {
                "status": new_status if new_status else current_status,
                "actual_arrival": actual_arrival if actual_arrival else "not updated",
                "notes": notes if notes else "not updated"
            },
            "message": f"Assignment {assignment_id} updated successfully"
        }

    except Exception as e:
        logger.error(f"Failed to update assignment: {e}")
        return {
            "success": False,
            "error": f"Failed to update assignment: {str(e)}"
        }


def handle_unassign_order(tool_input: dict, user_id: str = None) -> dict:
    """
    Unassign order (delete assignment)

    Removes assignment and reverts order/driver to original states.

    Args:
        tool_input: Dict with order_id or assignment_id, and confirm flag
        user_id: Authenticated user ID

    Returns:
        Unassignment result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    order_id = (tool_input.get("order_id") or "").strip()
    assignment_id = (tool_input.get("assignment_id") or "").strip()
    confirm = tool_input.get("confirm", False)

    if not order_id and not assignment_id:
        return {
            "success": False,
            "error": "Provide either order_id or assignment_id"
        }

    if not confirm:
        return {
            "success": False,
            "error": "Unassignment requires confirm=true for safety"
        }

    logger.info(f"Unassigning: order_id={order_id}, assignment_id={assignment_id}")

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Find assignment (filtered by user_id)
        if assignment_id:
            cursor.execute("""
                SELECT order_id, driver_id, status
                FROM assignments
                WHERE assignment_id = %s AND user_id = %s
            """, (assignment_id, user_id))
        else:
            cursor.execute("""
                SELECT assignment_id, driver_id, status
                FROM assignments
                WHERE order_id = %s AND user_id = %s AND status IN ('active', 'in_progress')
                ORDER BY assigned_at DESC
                LIMIT 1
            """, (order_id, user_id))

        assignment_row = cursor.fetchone()
        if not assignment_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "No active assignment found"
            }

        if assignment_id:
            found_order_id = assignment_row['order_id']
            driver_id = assignment_row['driver_id']
            status = assignment_row['status']
        else:
            assignment_id = assignment_row['assignment_id']
            driver_id = assignment_row['driver_id']
            status = assignment_row['status']
            found_order_id = order_id

        # Validate status (cannot unassign if in_progress without force)
        if status == "in_progress":
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Cannot unassign order with 'in_progress' status. Complete or fail the delivery first."
            }

        # Delete assignment
        cursor.execute("""
            DELETE FROM assignments
            WHERE assignment_id = %s
        """, (assignment_id,))

        # Revert order status to pending and clear assigned driver
        cursor.execute("""
            UPDATE orders
            SET status = 'pending', assigned_driver_id = NULL
            WHERE order_id = %s
        """, (found_order_id,))

        # Check if driver has other active assignments
        cursor.execute("""
            SELECT COUNT(*)
            FROM assignments
            WHERE driver_id = %s AND status IN ('active', 'in_progress')
        """, (driver_id,))

        other_assignments_count = cursor.fetchone()[0]

        # If no other active assignments, set driver back to active
        if other_assignments_count == 0:
            cursor.execute("""
                UPDATE drivers
                SET status = 'active'
                WHERE driver_id = %s
            """, (driver_id,))

        conn.commit()
        cursor.close()
        conn.close()

        logger.info(f"Assignment removed successfully: {assignment_id}")

        return {
            "success": True,
            "assignment_id": assignment_id,
            "order_id": found_order_id,
            "driver_id": driver_id,
            "message": f"Order {found_order_id} unassigned from driver {driver_id}. Order status reverted to 'pending'."
        }

    except Exception as e:
        logger.error(f"Failed to unassign order: {e}")
        return {
            "success": False,
            "error": f"Failed to unassign order: {str(e)}"
        }


def handle_complete_delivery(tool_input: dict, user_id: str = None) -> dict:
    """
    Complete a delivery and automatically update driver location

    Marks delivery as completed, updates order/driver statuses, and moves
    driver location to the delivery address.

    Args:
        tool_input: Dict with assignment_id, confirm flag, and optional fields
        user_id: Authenticated user ID

    Returns:
        Completion result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    from datetime import datetime

    assignment_id = (tool_input.get("assignment_id") or "").strip()
    confirm = tool_input.get("confirm", False)
    actual_distance_meters = tool_input.get("actual_distance_meters")
    notes = (tool_input.get("notes") or "").strip()

    if not assignment_id:
        return {
            "success": False,
            "error": "assignment_id is required"
        }

    if not confirm:
        return {
            "success": False,
            "error": "Delivery completion requires confirm=true for safety"
        }

    logger.info(f"Completing delivery: assignment_id={assignment_id}")

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Get assignment and order details including timing fields (filtered by user_id)
        cursor.execute("""
            SELECT
                a.status, a.order_id, a.driver_id,
                a.delivery_location_lat, a.delivery_location_lng, a.delivery_address,
                o.customer_name, o.expected_delivery_time, o.sla_grace_period_minutes,
                d.name as driver_name
            FROM assignments a
            JOIN orders o ON a.order_id = o.order_id
            JOIN drivers d ON a.driver_id = d.driver_id
            WHERE a.assignment_id = %s AND a.user_id = %s
        """, (assignment_id, user_id))

        assignment_row = cursor.fetchone()
        if not assignment_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Assignment not found: {assignment_id}"
            }

        status = assignment_row['status']
        order_id = assignment_row['order_id']
        driver_id = assignment_row['driver_id']
        delivery_lat = assignment_row['delivery_location_lat']
        delivery_lng = assignment_row['delivery_location_lng']
        delivery_address = assignment_row['delivery_address']
        customer_name = assignment_row['customer_name']
        driver_name = assignment_row['driver_name']
        expected_delivery_time = assignment_row['expected_delivery_time']
        sla_grace_period_minutes = assignment_row['sla_grace_period_minutes'] or 15

        # Validate status
        if status not in ["active", "in_progress"]:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Cannot complete delivery: assignment status is '{status}'. Must be 'active' or 'in_progress'."
            }

        # Validate delivery location exists
        if not delivery_lat or not delivery_lng:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": "Cannot complete delivery: delivery location coordinates are missing"
            }

        # Current timestamp for completion
        completion_time = datetime.now()

        # Step 1: Update assignment to completed
        update_fields = ["status = %s", "actual_arrival = %s", "updated_at = %s"]
        params = ["completed", completion_time, completion_time]

        if actual_distance_meters:
            update_fields.append("actual_distance_meters = %s")
            params.append(actual_distance_meters)

        if notes:
            update_fields.append("notes = %s")
            params.append(notes)

        params.append(assignment_id)

        cursor.execute(f"""
            UPDATE assignments
            SET {', '.join(update_fields)}
            WHERE assignment_id = %s
        """, tuple(params))

        # Step 2: Update driver location to delivery address (including address text)
        cursor.execute("""
            UPDATE drivers
            SET current_lat = %s,
                current_lng = %s,
                current_address = %s,
                last_location_update = %s,
                updated_at = %s
            WHERE driver_id = %s
        """, (delivery_lat, delivery_lng, delivery_address, completion_time, completion_time, driver_id))

        logger.info(f"Driver {driver_id} location updated to delivery address: {delivery_address} ({delivery_lat}, {delivery_lng})")

        # Step 3: Calculate delivery performance status
        delivery_status = "on_time"  # Default
        timing_info = {
            "expected_delivery_time": expected_delivery_time.isoformat() if expected_delivery_time else None,
            "actual_delivery_time": completion_time.isoformat(),
            "sla_grace_period_minutes": sla_grace_period_minutes
        }

        if expected_delivery_time:
            # Calculate grace period deadline
            from datetime import timedelta
            grace_deadline = expected_delivery_time + timedelta(minutes=sla_grace_period_minutes)

            if completion_time <= expected_delivery_time:
                delivery_status = "on_time"
                timing_info["status"] = "On-time delivery"
                timing_info["delay_minutes"] = 0
            elif completion_time <= grace_deadline:
                delivery_status = "late"
                delay_minutes = int((completion_time - expected_delivery_time).total_seconds() / 60)
                timing_info["status"] = f"Late (within grace period)"
                timing_info["delay_minutes"] = delay_minutes
            else:
                delivery_status = "very_late"
                delay_minutes = int((completion_time - expected_delivery_time).total_seconds() / 60)
                timing_info["status"] = f"Very late (SLA violation)"
                timing_info["delay_minutes"] = delay_minutes

        # Step 4: Update order status to delivered with timing info
        cursor.execute("""
            UPDATE orders
            SET status = 'delivered',
                delivered_at = %s,
                delivery_status = %s,
                updated_at = %s
            WHERE order_id = %s
        """, (completion_time, delivery_status, completion_time, order_id))

        logger.info(f"Order {order_id} marked as delivered with status '{delivery_status}'")

        # Step 4: Check if driver has other active assignments
        cursor.execute("""
            SELECT COUNT(*) as count FROM assignments
            WHERE driver_id = %s AND status IN ('active', 'in_progress')
            AND assignment_id != %s
        """, (driver_id, assignment_id))

        other_assignments_count = cursor.fetchone()['count']

        # Step 5: If no other active assignments, set driver to active
        cascading_actions = []
        if other_assignments_count == 0:
            cursor.execute("""
                UPDATE drivers
                SET status = 'active', updated_at = %s
                WHERE driver_id = %s
            """, (completion_time, driver_id))
            cascading_actions.append(f"Driver {driver_name} set to 'active' (no other assignments)")
        else:
            cascading_actions.append(f"Driver {driver_name} remains 'busy' ({other_assignments_count} other active assignment(s))")

        conn.commit()
        cursor.close()
        conn.close()

        logger.info(f"Delivery completed successfully: {assignment_id}")

        return {
            "success": True,
            "assignment_id": assignment_id,
            "order_id": order_id,
            "driver_id": driver_id,
            "customer_name": customer_name,
            "driver_name": driver_name,
            "completed_at": completion_time.isoformat(),
            "delivery_status": delivery_status,
            "timing": timing_info,
            "delivery_location": {
                "lat": float(delivery_lat),
                "lng": float(delivery_lng),
                "address": delivery_address
            },
            "driver_updated": {
                "new_location": f"{delivery_lat}, {delivery_lng}",
                "location_updated_at": completion_time.isoformat()
            },
            "cascading_actions": cascading_actions,
            "message": f"Delivery completed! Order {order_id} delivered by {driver_name}. Status: {timing_info.get('status', delivery_status)}. Driver location updated to delivery address."
        }

    except Exception as e:
        logger.error(f"Failed to complete delivery: {e}")
        return {
            "success": False,
            "error": f"Failed to complete delivery: {str(e)}"
        }


def handle_fail_delivery(tool_input: dict, user_id: str = None) -> dict:
    """
    Mark delivery as failed with mandatory location and reason

    Driver must provide current GPS location and failure reason.
    Updates driver location to reported coordinates and sets statuses accordingly.

    Args:
        tool_input: Dict with assignment_id, current_lat, current_lng, failure_reason,
                   confirm flag, and optional notes
        user_id: Authenticated user ID

    Returns:
        Failure recording result
    """
    # Authentication check - allow dev mode (only in non-production environments)
    if not user_id:
        # SECURITY: Only allow SKIP_AUTH in development environments
        env = os.getenv("ENV", "production").lower()
        skip_auth = os.getenv("SKIP_AUTH", "false").lower() == "true"

        if skip_auth and env != "production":
            user_id = "dev-user"
        else:
            return {
                "success": False,
                "error": "Authentication required. Please login first.",
                "auth_required": True
            }

    from datetime import datetime

    assignment_id = (tool_input.get("assignment_id") or "").strip()
    current_address = (tool_input.get("current_address") or "").strip()
    current_lat = tool_input.get("current_lat")
    current_lng = tool_input.get("current_lng")
    failure_reason = (tool_input.get("failure_reason") or "").strip()
    confirm = tool_input.get("confirm", False)
    notes = (tool_input.get("notes") or "").strip()

    # Validation
    if not assignment_id:
        return {
            "success": False,
            "error": "assignment_id is required"
        }

    if not confirm:
        return {
            "success": False,
            "error": "Delivery failure requires confirm=true for safety"
        }

    if not current_address or current_lat is None or current_lng is None:
        return {
            "success": False,
            "error": "Driver must provide current location (current_address, current_lat, and current_lng required)"
        }

    if not failure_reason:
        return {
            "success": False,
            "error": "Failure reason is required. Valid reasons: customer_not_available, wrong_address, refused_delivery, damaged_goods, payment_issue, vehicle_breakdown, access_restricted, weather_conditions, other"
        }

    # Validate failure_reason is one of the allowed values
    valid_reasons = [
        "customer_not_available",
        "wrong_address",
        "refused_delivery",
        "damaged_goods",
        "payment_issue",
        "vehicle_breakdown",
        "access_restricted",
        "weather_conditions",
        "other"
    ]

    if failure_reason not in valid_reasons:
        return {
            "success": False,
            "error": f"Invalid failure_reason '{failure_reason}'. Must be one of: {', '.join(valid_reasons)}"
        }

    # Validate coordinates are valid
    try:
        current_lat = float(current_lat)
        current_lng = float(current_lng)
        if not (-90 <= current_lat <= 90) or not (-180 <= current_lng <= 180):
            return {
                "success": False,
                "error": "Invalid GPS coordinates. Latitude must be -90 to 90, longitude must be -180 to 180"
            }
    except (ValueError, TypeError):
        return {
            "success": False,
            "error": "current_lat and current_lng must be valid numbers"
        }

    logger.info(f"Failing delivery: assignment_id={assignment_id}, reason={failure_reason}")

    try:
        conn = get_db_connection()
        cursor = conn.cursor()

        # Get assignment and order details including timing fields (filtered by user_id)
        cursor.execute("""
            SELECT
                a.status, a.order_id, a.driver_id,
                a.delivery_address,
                o.customer_name, o.expected_delivery_time, o.sla_grace_period_minutes,
                d.name as driver_name
            FROM assignments a
            JOIN orders o ON a.order_id = o.order_id
            JOIN drivers d ON a.driver_id = d.driver_id
            WHERE a.assignment_id = %s AND a.user_id = %s
        """, (assignment_id, user_id))

        assignment_row = cursor.fetchone()
        if not assignment_row:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Assignment not found: {assignment_id}"
            }

        status = assignment_row['status']
        order_id = assignment_row['order_id']
        driver_id = assignment_row['driver_id']
        delivery_address = assignment_row['delivery_address']
        customer_name = assignment_row['customer_name']
        driver_name = assignment_row['driver_name']
        expected_delivery_time = assignment_row['expected_delivery_time']
        sla_grace_period_minutes = assignment_row['sla_grace_period_minutes'] or 15

        # Validate status
        if status not in ["active", "in_progress"]:
            cursor.close()
            conn.close()
            return {
                "success": False,
                "error": f"Cannot fail delivery: assignment status is '{status}'. Must be 'active' or 'in_progress'."
            }

        # Current timestamp for failure
        failure_time = datetime.now()

        # Step 1: Update assignment to failed
        update_fields = [
            "status = %s",
            "failure_reason = %s",
            "actual_arrival = %s",
            "updated_at = %s"
        ]
        params = ["failed", failure_reason, failure_time, failure_time]

        if notes:
            update_fields.append("notes = %s")
            params.append(notes)

        params.append(assignment_id)

        cursor.execute(f"""
            UPDATE assignments
            SET {', '.join(update_fields)}
            WHERE assignment_id = %s
        """, tuple(params))

        # Step 2: Update driver location to reported current location (address provided by user)
        cursor.execute("""
            UPDATE drivers
            SET current_lat = %s,
                current_lng = %s,
                current_address = %s,
                last_location_update = %s,
                updated_at = %s
            WHERE driver_id = %s
        """, (current_lat, current_lng, current_address, failure_time, failure_time, driver_id))

        logger.info(f"Driver {driver_id} location updated to reported position: {current_address} ({current_lat}, {current_lng})")

        # Step 3: Calculate delivery performance status for failure
        delivery_status = "failed_on_time"  # Default - failed but before deadline
        timing_info = {
            "expected_delivery_time": expected_delivery_time.isoformat() if expected_delivery_time else None,
            "failure_time": failure_time.isoformat(),
            "sla_grace_period_minutes": sla_grace_period_minutes
        }

        if expected_delivery_time:
            if failure_time <= expected_delivery_time:
                delivery_status = "failed_on_time"
                timing_info["status"] = "Failed before deadline (attempted delivery on time)"
            else:
                delivery_status = "failed_late"
                delay_minutes = int((failure_time - expected_delivery_time).total_seconds() / 60)
                timing_info["status"] = f"Failed after deadline (late attempt)"
                timing_info["delay_minutes"] = delay_minutes

        # Step 4: Update order status to failed with timing info
        cursor.execute("""
            UPDATE orders
            SET status = 'failed',
                delivered_at = %s,
                delivery_status = %s,
                updated_at = %s
            WHERE order_id = %s
        """, (failure_time, delivery_status, failure_time, order_id))

        logger.info(f"Order {order_id} marked as failed with status '{delivery_status}'")

        # Step 4: Check if driver has other active assignments
        cursor.execute("""
            SELECT COUNT(*) as count FROM assignments
            WHERE driver_id = %s AND status IN ('active', 'in_progress')
            AND assignment_id != %s
        """, (driver_id, assignment_id))

        other_assignments_count = cursor.fetchone()['count']

        # Step 5: If no other active assignments, set driver to active
        cascading_actions = []
        if other_assignments_count == 0:
            cursor.execute("""
                UPDATE drivers
                SET status = 'active', updated_at = %s
                WHERE driver_id = %s
            """, (failure_time, driver_id))
            cascading_actions.append(f"Driver {driver_name} set to 'active' (no other assignments)")
        else:
            cascading_actions.append(f"Driver {driver_name} remains 'busy' ({other_assignments_count} other active assignment(s))")

        conn.commit()
        cursor.close()
        conn.close()

        logger.info(f"Delivery marked as failed: {assignment_id}")

        # Format failure reason for display
        reason_display = failure_reason.replace("_", " ").title()

        return {
            "success": True,
            "assignment_id": assignment_id,
            "order_id": order_id,
            "driver_id": driver_id,
            "customer_name": customer_name,
            "driver_name": driver_name,
            "failed_at": failure_time.isoformat(),
            "failure_reason": failure_reason,
            "failure_reason_display": reason_display,
            "delivery_status": delivery_status,
            "timing": timing_info,
            "delivery_address": delivery_address,
            "driver_location": {
                "lat": current_lat,
                "lng": current_lng,
                "address": current_address,
                "updated_at": failure_time.isoformat()
            },
            "cascading_actions": cascading_actions,
            "message": f"Delivery failed for order {order_id}. Reason: {reason_display}. Timing: {timing_info.get('status', delivery_status)}. Driver {driver_name} location updated to {current_address or f'({current_lat}, {current_lng})'}."
        }

    except Exception as e:
        logger.error(f"Failed to record delivery failure: {e}")
        return {
            "success": False,
            "error": f"Failed to record delivery failure: {str(e)}"
        }


def get_tools_list() -> list:
    """Get list of available tools"""
    return [tool["name"] for tool in TOOLS_SCHEMA]


def get_tool_description(tool_name: str) -> str:
    """Get description for a specific tool"""
    for tool in TOOLS_SCHEMA:
        if tool["name"] == tool_name:
            return tool["description"]
    return ""