File size: 156,181 Bytes
cba5a66
af226a7
3c9f801
d6fab25
 
 
 
 
 
 
 
 
 
 
 
cba5a66
 
 
d6fab25
3123910
cba5a66
d6fab25
 
5a91767
 
d6fab25
cba5a66
5a91767
cba5a66
5a91767
cba5a66
 
 
 
 
 
 
d6fab25
 
cba5a66
 
52e8e7a
 
030303e
cba5a66
 
dbe879e
cba5a66
d6fab25
 
 
 
 
 
 
 
 
 
 
dbe879e
0e4a811
dbe879e
 
46b58d7
61c709c
fd44c51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61c709c
 
 
 
850db0e
 
fd44c51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850db0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b6d98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370041e
4b6d98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb59e59
628312d
eb59e59
 
 
 
 
 
628312d
eb59e59
 
 
628312d
 
 
 
 
 
eb59e59
 
 
 
 
628312d
 
 
 
 
eb59e59
 
 
 
 
628312d
 
 
 
 
eb59e59
 
 
 
 
628312d
 
 
 
 
 
 
eb59e59
 
628312d
eb59e59
 
 
628312d
 
 
 
eb59e59
 
 
 
 
628312d
 
 
 
eb59e59
 
628312d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb59e59
 
 
 
 
567fa26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c70b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628312d
 
 
5c70b17
 
 
 
628312d
 
 
 
5c70b17
 
 
628312d
5c70b17
 
 
628312d
5c70b17
 
 
 
628312d
5c70b17
 
 
628312d
5c70b17
 
628312d
5c70b17
 
628312d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c70b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde9594
 
 
 
 
 
 
 
 
 
 
 
 
 
5c70b17
628312d
 
 
 
 
 
5c70b17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb59e59
 
567fa26
eb59e59
 
567fa26
eb59e59
 
567fa26
eb59e59
567fa26
eb59e59
567fa26
eb59e59
 
 
 
 
 
 
 
 
 
5c70b17
 
 
 
 
 
850db0e
61c709c
628312d
c082084
 
 
 
628312d
c082084
 
628312d
 
 
c082084
 
 
 
 
61c709c
 
 
 
 
 
 
dbe879e
d6fab25
cba5a66
d6fab25
567fa26
d6fab25
 
 
 
 
 
 
 
 
 
 
5a91767
 
 
 
 
46b58d7
 
 
 
5a91767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6fab25
 
 
e8ece8a
5a91767
52e8e7a
 
 
 
 
5a91767
d547805
5a91767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6fab25
 
 
 
 
 
 
 
 
 
 
cba5a66
 
d6fab25
cba5a66
567fa26
cba5a66
 
567fa26
 
 
cba5a66
 
 
 
 
d6fab25
cba5a66
d6fab25
 
 
 
cba5a66
 
 
 
 
f20d300
d6fab25
f20d300
 
 
 
 
cba5a66
f20d300
cba5a66
f20d300
 
 
 
 
 
cba5a66
f20d300
cba5a66
f20d300
cba5a66
 
 
d6fab25
d0069f8
 
0e4a811
 
 
 
 
 
 
d0069f8
 
 
0e4a811
 
 
 
d0069f8
0e4a811
d0069f8
 
 
0e4a811
d0069f8
 
 
 
 
 
 
 
 
 
 
 
 
 
0e4a811
 
d0069f8
 
 
 
0e4a811
d0069f8
 
0e4a811
d0069f8
0e4a811
d0069f8
 
 
0e4a811
 
d0069f8
0e4a811
d0069f8
0e4a811
d0069f8
 
d6fab25
d0069f8
 
 
 
 
d6fab25
 
 
d0069f8
 
 
 
 
 
 
 
 
d6fab25
 
 
 
 
 
 
 
 
 
d0069f8
d6fab25
 
 
 
 
 
 
 
 
 
 
18d3583
 
 
 
 
 
 
 
 
d6fab25
18d3583
 
d6fab25
 
 
 
 
 
18d3583
 
 
05120d5
d6fab25
 
 
 
 
 
 
9b99c4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87269c3
 
9b99c4f
 
 
d6fab25
9b99c4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6fab25
9b99c4f
cba5a66
52e8e7a
d6fab25
52e8e7a
 
 
 
 
 
 
 
 
 
 
87269c3
 
6f7b8a9
87269c3
6f7b8a9
 
 
 
 
 
 
87269c3
6f7b8a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87269c3
6f7b8a9
d6fab25
52e8e7a
d6fab25
852ee83
d6fab25
79de83d
 
d6fab25
79de83d
 
 
61c709c
 
 
 
 
79de83d
 
 
7b86bd0
 
 
 
 
bc9bce5
c082084
 
 
 
 
 
bc9bce5
 
 
 
 
79de83d
 
 
 
 
 
 
 
 
61c709c
e8ece8a
79de83d
50df459
 
 
 
 
 
 
 
 
d6fab25
 
 
 
 
 
50df459
d6fab25
52e8e7a
 
 
 
 
 
 
 
d6fab25
bc9bce5
 
 
 
 
d6fab25
79de83d
 
50df459
 
 
79de83d
50df459
 
 
 
 
 
79de83d
 
 
 
 
 
 
50df459
 
 
 
 
 
 
 
 
 
 
 
 
79de83d
50df459
 
79de83d
 
d6fab25
 
 
 
 
 
 
 
 
 
bc9bce5
d6fab25
 
 
 
 
 
cba5a66
 
 
 
 
d6fab25
 
 
cba5a66
 
 
d6fab25
 
b2f6cec
d6fab25
cba5a66
 
 
d6fab25
 
 
cba5a66
 
d6fab25
5396710
 
 
 
d6fab25
 
3c9f801
d6fab25
 
 
 
 
 
 
 
cba5a66
d6fab25
5396710
cba5a66
d6fab25
 
 
 
cba5a66
 
b2f6cec
cba5a66
 
 
 
b2f6cec
3c9f801
dbe879e
b2f6cec
 
 
 
cba5a66
 
 
fd79e98
 
 
 
 
 
 
 
 
 
 
3123910
 
 
 
 
dbe879e
 
 
 
 
3123910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe879e
3eb35e9
dbe879e
1e10395
 
 
 
 
 
 
18d3583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05120d5
18d3583
 
 
05120d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d3583
 
05120d5
18d3583
 
 
 
05120d5
 
 
 
 
 
18d3583
 
 
 
 
 
05120d5
18d3583
05120d5
 
 
 
 
 
 
 
 
 
18d3583
05120d5
18d3583
dbe879e
1e10395
 
dbe879e
 
1e10395
 
dbe879e
1e10395
 
 
6efae71
1e10395
 
 
 
 
 
6efae71
1e10395
 
6efae71
1e10395
 
 
 
 
6efae71
1e10395
 
 
 
dbe879e
 
1e10395
dbe879e
1e10395
dbe879e
 
 
 
 
 
 
3eb35e9
dbe879e
 
 
 
 
 
 
 
 
 
 
 
 
 
1e10395
 
 
dbe879e
 
1e10395
dbe879e
 
 
 
 
 
 
 
3eb35e9
 
 
 
 
 
 
 
 
4a525e8
 
 
 
 
3eb35e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e10395
 
 
3eb35e9
1e10395
3eb35e9
 
1e10395
 
 
 
3eb35e9
1e10395
 
 
 
628312d
1e10395
 
 
 
3eb35e9
1e10395
 
 
 
628312d
 
 
 
3eb35e9
 
 
 
 
 
 
628312d
3eb35e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe879e
 
 
 
 
 
 
 
 
 
0e4a811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe879e
 
 
 
 
 
 
61c709c
 
 
fd44c51
 
 
 
 
 
 
 
 
 
 
 
61c709c
 
 
 
 
 
 
 
fd44c51
 
 
 
 
61c709c
fd44c51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61c709c
 
 
 
 
 
 
 
 
dbe879e
 
 
1e10395
 
 
 
 
dbe879e
6efae71
1e10395
6efae71
dbe879e
 
 
 
 
 
 
 
 
 
3123910
959633e
 
 
 
 
 
dbe879e
 
61c709c
 
 
 
 
 
e4002ce
61c709c
 
 
 
 
 
 
 
 
 
 
370041e
61c709c
 
 
 
 
 
 
e4002ce
959633e
 
 
 
c082084
dbe879e
 
959633e
 
 
 
 
dbe879e
e8ece8a
 
 
 
 
959633e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe879e
959633e
 
 
 
 
c082084
dbe879e
 
 
 
959633e
 
 
 
 
dbe879e
 
 
959633e
d6fab25
 
 
 
 
 
5396710
cba5a66
d6fab25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e8e7a
d6fab25
 
 
b2f6cec
d6fab25
 
 
cba5a66
d6fab25
030303e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6fab25
 
 
 
 
 
52e8e7a
d6fab25
52e8e7a
d6fab25
 
 
bc9bce5
d6fab25
 
 
cba5a66
d6fab25
852ee83
cba5a66
 
f8ccb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e4a811
 
 
 
 
f8ccb74
 
 
 
 
 
6c168d6
 
f8ccb74
 
6c168d6
 
 
 
f8ccb74
6c168d6
 
f8ccb74
6c168d6
f8ccb74
 
 
 
6c168d6
f8ccb74
 
 
 
 
 
 
 
 
 
 
6c168d6
f8ccb74
6c168d6
f8ccb74
 
 
 
 
6c168d6
 
 
 
 
f8ccb74
 
6c168d6
 
 
f8ccb74
6c168d6
 
 
f8ccb74
6c168d6
f8ccb74
 
 
6c168d6
f8ccb74
 
 
6c168d6
 
 
 
 
f8ccb74
 
 
 
 
 
 
6c168d6
 
 
 
f8ccb74
6c168d6
 
 
 
 
 
f8ccb74
6c168d6
f8ccb74
 
6c168d6
 
 
f8ccb74
6c168d6
 
 
f8ccb74
 
 
fd44c51
 
 
 
 
 
 
 
 
 
f8ccb74
 
 
 
 
 
 
 
 
 
 
 
 
 
fd44c51
f8ccb74
 
 
e9b2d8c
 
 
 
f8ccb74
 
 
 
 
 
e9b2d8c
 
8b74ef8
e9b2d8c
dbe879e
acfb205
f8ccb74
 
 
 
 
 
 
850db0e
61c709c
f8ccb74
 
 
 
 
 
 
 
 
 
 
61c709c
f8ccb74
 
 
e38d3be
f8ccb74
 
 
 
 
 
e38d3be
f8ccb74
eb59e59
 
 
f8ccb74
 
 
 
 
 
 
 
 
 
5c70b17
f8ccb74
5c70b17
 
 
f8ccb74
 
 
 
 
 
 
 
 
 
eb59e59
f8ccb74
850db0e
 
f8ccb74
 
 
 
 
 
acfb205
fd44c51
61c709c
 
f8ccb74
 
fd44c51
f8ccb74
 
 
fd44c51
 
 
 
 
 
 
 
 
 
 
 
f8ccb74
61c709c
f8ccb74
61c709c
 
f8ccb74
 
 
 
 
 
61c709c
f8ccb74
 
 
 
 
e9b2d8c
f8ccb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c168d6
 
 
 
f8ccb74
 
 
6c168d6
f8ccb74
 
 
6c168d6
f8ccb74
 
e9b2d8c
f8ccb74
 
 
 
 
 
 
a8a6287
 
f8ccb74
 
 
 
 
 
 
 
 
 
 
 
 
 
fd44c51
f8ccb74
 
fd44c51
f8ccb74
 
a8a6287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd44c51
 
 
a8a6287
fd44c51
 
a8a6287
 
 
fd44c51
 
a8a6287
 
 
 
 
 
 
f8ccb74
a8a6287
 
 
f8ccb74
 
a8a6287
 
 
f8ccb74
fd44c51
f8ccb74
e9b2d8c
f8ccb74
 
 
 
1e10395
f8ccb74
 
1e10395
 
 
 
e9b2d8c
1e10395
e9b2d8c
dbe879e
e9b2d8c
dbe879e
e9b2d8c
f8ccb74
e9b2d8c
f8ccb74
e9b2d8c
 
05120d5
 
18d3583
05120d5
 
 
e9b2d8c
05120d5
 
1e10395
18d3583
 
 
1e10395
e9b2d8c
 
dbe879e
e9b2d8c
f8ccb74
1e10395
18d3583
 
 
 
 
 
 
 
1e10395
18d3583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e10395
 
 
18d3583
 
1e10395
 
 
 
18d3583
 
 
 
 
 
 
 
 
e9b2d8c
f8ccb74
 
 
 
18d3583
f8ccb74
1e10395
f8ccb74
e9b2d8c
f8ccb74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9b2d8c
 
 
5a91767
cba5a66
5a91767
 
 
b2f6cec
cba5a66
f20d300
 
 
cba5a66
 
f20d300
 
 
 
 
 
 
 
cba5a66
f20d300
 
 
 
 
 
 
 
 
 
 
 
 
 
cba5a66
f20d300
 
d6fab25
 
5a91767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0dd18b
 
d6fab25
5a91767
 
 
c0dd18b
 
d6fab25
 
c0dd18b
d6fab25
c0dd18b
d6fab25
c0dd18b
 
d6fab25
 
 
c0dd18b
d6fab25
 
5a91767
c0dd18b
 
 
 
5a91767
c0dd18b
 
 
 
 
 
 
 
5a91767
d6fab25
c0dd18b
 
 
 
 
 
 
5a91767
c0dd18b
 
 
 
5a91767
c0dd18b
 
 
 
 
 
 
d6fab25
 
 
df959f2
c0dd18b
5a91767
 
c0dd18b
 
 
 
5a91767
 
bbeb85a
c0dd18b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d547805
 
 
 
 
c0dd18b
d6fab25
d547805
 
 
 
 
c0dd18b
 
d547805
 
 
 
c0dd18b
 
5a91767
c0dd18b
 
 
 
 
 
 
 
 
 
 
 
 
 
5a91767
c0dd18b
61c709c
 
5a91767
c0dd18b
 
 
5a91767
61c709c
 
 
c0dd18b
5a91767
46b58d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0dd18b
 
 
 
 
5a91767
 
c0dd18b
 
 
 
 
 
 
 
5a91767
c0dd18b
 
 
f20d300
c0dd18b
d547805
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a91767
d547805
 
 
 
d6fab25
 
 
 
d547805
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bcb970
 
d547805
4bcb970
 
 
 
 
 
 
 
 
d547805
4bcb970
 
 
 
 
 
 
 
 
 
 
d547805
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0dd18b
d6fab25
5a91767
 
 
c0dd18b
 
d6fab25
 
 
 
 
 
 
 
5a91767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b58d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a91767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61c709c
3c9f801
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
"""
Khalifa University Library AI Agent
MCP-style tool-calling backend with RAG, PRIMO, PubMed, Google Scholar, Consensus

Tools:
  - search_primo: Search KU Library catalog
  - search_pubmed: Search biomedical literature
  - search_scholar: Search Google Scholar
  - search_consensus: Search Consensus (research papers)
  - get_library_info: RAG from KU library knowledge base

Environment variables (HF Space Secrets):
  OPENAI_API_KEY      β€” required (embeddings + ChatGPT)
  ANTHROPIC_API_KEY   β€” optional (Claude answers)
  PRIMO_API_KEY       β€” required (PRIMO search)
"""

import os
import json
import re
import glob
import time
import sqlite3
import hashlib
import secrets
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel

from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document

import httpx

# ===== CONFIG =====
KNOWLEDGE_DIR = "knowledge"
# Use /data for persistence across HF Space restarts β€” fall back to local if /data unavailable
FAISS_INDEX_PATH = "/data/faiss_index" if os.path.exists("/data") else "faiss_index"
DB_PATH = "/data/analytics.db" if os.path.exists("/data") else "analytics.db"
CHUNK_SIZE = 800
CHUNK_OVERLAP = 100
TOP_K = 7

# ===== MEDICAL TOPIC DETECTION =====
MEDICAL_KEYWORDS = [
    'medicine','medical','health','clinical','nursing','pharmacy','biomedical',
    'anatomy','physiology','epidemiology','oncology','cardiology','neuroscience',
    'genomics','pathology','surgery','mental health','nutrition','public health',
    'disease','therapy','treatment','diagnosis','patient','drug','pharmaceutical',
    'hospital','cancer','diabetes','heart','brain','cell biology','immunology',
    'biochemistry','microbiology','virology','pediatric','psychiatric','dental',
    'ophthalmology','radiology','anesthesia','emergency medicine','geriatric'
]

CURRENT_INFO_RE = re.compile(r"\b(current|currently|latest|today|recent|recently|now|this week|this month|news|update|updated|president|prime minister|ceo|minister|king|ruler|who won)\b", re.IGNORECASE)
RESEARCH_CUE_RE = re.compile(r"\b(find|search|look for|show me|get me|give me|locate|recommend|suggest|articles?|papers?|books?|journals?|studies|literature|research|systematic review|evidence|sources|database|databases|peer reviewed|open access|advances?|approach(es)?|method(s|ology)?|technique[s]?|application[s]?|framework[s]?|model[s]?|algorithm[s]?|publication[s]?|recent work|current state|state of the art)\b", re.IGNORECASE)
LIBRARY_CUE_RE = re.compile(r"\b(library|librarian|borrow|loan|renew|fine|study room|room booking|reserve a room|account|my library|interlibrary|ill|khazna|orcid|open access|apc|refworks|libkey|hours|location|contact|visitor|alumni|database access|off campus|remote access)\b", re.IGNORECASE)
MEDICAL_SEARCH_RE = re.compile(r"\b(pubmed|embase|cinahl|clinicalkey|cochrane|uptodate|medline|systematic review|clinical trial|biomedical literature|medical literature)\b", re.IGNORECASE)
SOCIAL_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening|how are you|how old are you|who are you|what are you|are you a bot|are you a robot|what can you do|thanks|thank you|ok|okay|bye|goodbye|lol|haha|hehe|you are silly|are you silly|are you dumb|stupid bot|dumb bot|idiot bot|joke|tell me a joke)\b", re.IGNORECASE)
PURE_GREETING_RE = re.compile(r"^(hi|hello|hey|good morning|good afternoon|good evening)[!.\s]*$", re.IGNORECASE)
HOURS_RE = re.compile(
    r"\b("
    r"library hours?|opening hours?|closing hours?|open hours?|"
    r"open today|open tomorrow|open now|open on|open this|"
    r"closed today|closed tomorrow|closed on|closed this|"
    r"when.*open|when.*close|when.*does.*library|"
    r"what time.*open|what time.*close|what time.*library|"
    r"opening time|closing time|"
    r"is.*library.*open|is.*campus.*library|is.*habshan.*open|is.*san.*open|"
    r"is.*library.*closed|will.*library.*open|will.*it.*open|"
    r"does.*library.*open|library.*open.*today|library.*close.*today|"
    r"habshan.*open|san.*open|main campus.*open|"
    r"ramadan hours?|weekend hours?|friday hours?|saturday hours?|sunday hours?|"
    r"library.*schedule|schedule.*library|"
    r"what.*hours|till.*when|until.*when|"
    r"what day.*open|which day.*open|what day.*closed|which day.*closed"
    r")\b",
    re.IGNORECASE
)
KU_GENERAL_RE = re.compile(r"\b(khalifa university|ku)\b.*\b(admission|admissions|program|programs|degree|degrees|college|colleges|school|schools|tuition|fees|scholarship|scholarships|hostel|housing|transport|ranking|rankings|president|vice president|chancellor|application|apply|registrar|academic calendar|semester dates|campus map)\b|\b(admission|admissions|program|programs|degree|degrees|college|colleges|school|schools|tuition|fees|scholarship|scholarships|hostel|housing|transport|ranking|rankings|president|vice president|chancellor|application|apply|registrar|academic calendar|semester dates|campus map)\b.*\b(khalifa university|ku)\b", re.IGNORECASE)
LIBRARY_HOURS_URL = "https://library.ku.ac.ae/hours"
KU_MAIN_URL = "https://www.ku.ac.ae/"

GREETING_FOLLOWUP_RE = re.compile(r"^(yes|yes please|yes check|sure|okay|ok|yeah|yep|please do|go ahead)$", re.IGNORECASE)

# Campus / location questions β€” always answered with hardcoded text, never from web
KU_CAMPUS_RE = re.compile(
    r"\b("
    r"where is the library|where is.*library|library.*location|location.*library|"
    r"which building|what building|which floor|"
    r"main campus library|san campus library|habshan library|sas al nakhl library|"
    r"arzanah library|"
    r"library.*address|address.*library|"
    r"how to get to.*library|how.*reach.*library|how.*find.*library|"
    r"library.*campus(es)?|campus(es)?.*library|"
    r"how many.*librar|how many.*branch|library.*branch(es)?|branch(es)?.*library|"
    r"which campus.*library|library.*which campus|"
    r"library.*map|map.*library"
    r")\b",
    re.IGNORECASE
)

def _last_assistant_message(history):
    if not history:
        return ""
    for m in reversed(history):
        if m.get("role") == "assistant":
            return m.get("content", "") or ""
    return ""

def _is_greeting_menu_followup(question: str, history) -> bool:
    q = (question or "").strip()
    if not GREETING_FOLLOWUP_RE.match(q):
        return False
    last = _last_assistant_message(history).lower()
    return (
        "i’m <strong>libbee</strong>" in last
        or "i'm <strong>libbee</strong>" in last
        or "are you looking for one of these" in last
        or "khalifa university library ai assistant" in last
    )

def _greeting_menu_clarify_answer() -> str:
    return (
        "Sure β€” what would you like help with?<br><br>"
        "You can choose one of these or type your question directly:<br>"
        "β€’ Find articles and books<br>"
        "β€’ Get full text for an article<br>"
        "β€’ Submit an Interlibrary Loan (ILL) request<br>"
        "β€’ Contact a librarian<br>"
        "β€’ Check library hours"
    )


def _normalize_social_text(text: str) -> str:
    t = (text or "").strip().lower()
    t = re.sub(r"[^\w\s]", "", t)
    t = re.sub(r"\s+", " ", t).strip()
    return t


def _fixed_social_answer(question: str) -> str | None:
    q = _normalize_social_text(question)

    if re.fullmatch(r"(how are you|hows it going|how are you doing|how do you do)", q):
        return (
            "I’m doing well, thank you. I’m <strong>LibBee</strong>, the Khalifa University Library AI Assistant, "
            "and I’m here to help with articles, books, databases, full text, and library services."
        )

    if re.fullmatch(r"(who are you|what are you|tell me about yourself)", q):
        return (
            "I’m <strong>LibBee</strong>, the Khalifa University Library AI Assistant. "
            "I can help you find articles and books, search databases, get full text, "
            "answer library service questions, and guide you to the right librarian when needed."
        )

    if re.fullmatch(r"(what can you do|what do you do|how can you help|what help can you provide)", q):
        return (
            "I can help you search for articles and books, suggest databases, find full text, "
            "answer questions about library services, and connect you with the right Khalifa University Library staff member."
        )

    if re.fullmatch(r"(are you a bot|are you a robot|are you ai|are you an ai)", q):
        return (
            "Yes β€” I’m an AI assistant for Khalifa University Library. "
            "My job is to help with library research, databases, articles, books, full text, and library services."
        )

    if re.fullmatch(r"(thank you|thanks|thx)", q):
        return "You’re welcome. I’m happy to help."

    if re.fullmatch(r"(bye|goodbye|see you)", q):
        return "Goodbye. If you need help later, I’ll be here."

    return None

STAFF_DIRECTORY = [
    # ── Library Leadership ───────────────────────────────────────────
    {
        "full_name": "Dr. Abdulla Al Hefeiti",
        "role": "Library Director / Assistant Provost, Libraries",
        "details": "He can help with strategic and institutional matters, library leadership, and partnerships. Email: abdulla.alhefeiti@ku.ac.ae | Phone: +971 2 312 3331",
        "tokens": ["abdulla", "hefeiti", "abdulla al hefeiti", "al hefeiti"],
    },
    # ── Specialist Librarians ────────────────────────────────────────
    {
        "full_name": "Nikesh Narayanan",
        "role": "Research & Access Services Librarian",
        "details": (
            "He can help with research support, Khazna institutional repository, ORCID, "
            "SciVal, Scopus, research impact, AI tools for research, bibliometrics, "
            "scholarly communication, and LibGuides. "
            "Email: nikesh.narayanan@ku.ac.ae | Phone: +971 2 312 3980"
        ),
        "tokens": ["nikesh", "narayanan", "nikesh narayanan"],
    },
    {
        "full_name": "Rani Anand",
        "role": "E-Resources Librarian",
        "details": (
            "She can help with database access problems, e-resources troubleshooting, "
            "remote access, vendor issues, patents, e-books, and bibliometrics. "
            "Email: rani.anand@ku.ac.ae | Phone: +971 2 312 3935"
        ),
        "tokens": ["rani", "anand", "rani anand"],
    },
    {
        "full_name": "Jason Fetty",
        "role": "Medical Librarian",
        "details": (
            "He can help with medical and health sciences research, systematic reviews, "
            "PubMed, Embase, CINAHL, UpToDate, and clinical databases. "
            "Email: jason.fetty@ku.ac.ae | Phone: +971 2 312 4722"
        ),
        "tokens": ["jason", "fetty", "jason fetty"],
    },
    {
        "full_name": "Walter Brian Hall",
        "role": "Digital & Technology Services Librarian / Systems Librarian",
        "details": (
            "He can help with library website, systems, technology, digital infrastructure, "
            "ORCID, STEAM, coding, Open Access publishing, APC funding, "
            "general library services, and public services. "
            "Email: walter.hall@ku.ac.ae | Open Access: openaccess@ku.ac.ae | "
            "Phone: +971 2 312 3163 | Mobile: 052-905-1491"
        ),
        "tokens": ["walter", "brian", "hall", "walter brian hall", "walter hall", "brian hall"],
    },
    # ── Managers ────────────────────────────────────────────────────
    {
        "full_name": "Alia Al-Harrasi",
        "role": "Manager, Technical Services",
        "details": (
            "She can help with cataloguing, metadata, acquisitions processing, and technical services. "
            "Email: alia.alharrasi@ku.ac.ae | Phone: +971 2 312 3180"
        ),
        "tokens": ["alia", "harrasi", "al-harrasi", "alia al harrasi", "alia al-harrasi"],
    },
    {
        "full_name": "Muna Ahmad Mohammad Al Blooshi",
        "role": "Manager, Public Services",
        "details": (
            "She can help with circulation, general library services on Main Campus, and public services. "
            "Email: muna.alblooshi@ku.ac.ae | Phone: +971 2 312 4212"
        ),
        "tokens": ["muna", "blooshi", "al blooshi", "al-blooshi", "muna al blooshi"],
    },
    # ── Library Information Senior Specialists / Specialists ─────────
    {
        "full_name": "Suaad Al Jneibi",
        "role": "Library Information Senior Specialist",
        "details": (
            "She can help with Interlibrary Loan (ILL) requests, document delivery, "
            "and general library questions. "
            "Email: suaad.aljneibi@ku.ac.ae | Phone: +971 2 312 4278 | "
            "Location: SAN Habshan Building, GF Room 5017AWS01"
        ),
        "tokens": [
            "suaad", "jneibi", "al jneibi", "suaad al jneibi",
            "suuad", "suaad jneibi",
        ],
    },
    {
        "full_name": "Shamsa Saeed Salem Alhosani",
        "role": "Library Information Senior Specialist",
        "details": (
            "She can help with library cataloguing and general library assistance. "
            "Email: shamsa.alhosani@ku.ac.ae | Phone: +971 2 312 3156 | "
            "Location: SAN Habshan Building, GF Room 5013WS04"
        ),
        "tokens": [
            "shamsa", "alhosani", "shamsa alhosani",
            "shamsa saeed", "shamsa salem", "shamsa saeed salem alhosani",
        ],
    },
    {
        "full_name": "William Nathaniel Hutchinson III",
        "role": "Library Information Senior Specialist",
        "details": (
            "He can help with library cataloguing and general library assistance. "
            "Email: william.hutchinsoniii@ku.ac.ae | Phone: +971 2 312 3966"
        ),
        "tokens": [
            "william", "hutchinson", "william hutchinson",
            "william nathaniel", "hutchinson iii", "william hutchinson iii",
        ],
    },
    {
        "full_name": "Shaikha Mohamed Saleem Almenhali",
        "role": "Library Information Specialist",
        "details": (
            "She can help with general library assistance. "
            "Email: shaikha.almenhali@ku.ac.ae | Phone: +971 2 312 5874"
        ),
        "tokens": [
            "shaikha", "almenhali", "shaikha almenhali",
            "shaikha mohamed", "shaikha saleem", "shaikha mohamed saleem almenhali",
        ],
    },
    {
        "full_name": "Wilfredo Arcilla",
        "role": "Library Information Specialist",
        "details": (
            "He can help with general library assistance. "
            "Email: wilfredo.arcilla@ku.ac.ae | Phone: +971 2 312 3323 | "
            "Location: SAN Habshan Building, GF Room 5011WS05"
        ),
        "tokens": [
            "wilfredo", "arcilla", "wilfredo arcilla",
        ],
    },
    {
        "full_name": "Zainab Al Ali",
        "role": "Library Information Senior Specialist",
        "details": (
            "She can help with general library assistance. "
            "Email: zainab.alali@ku.ac.ae | Phone: +971 2 312 4321 | "
            "Location: SAN Habshan Building, GF Room 5017AWS02"
        ),
        "tokens": [
            "zainab", "al ali", "zainab al ali", "alali", "zainab alali",
        ],
    },
    {
        "full_name": "Khawla Alhemeiri",
        "role": "Library Information Senior Specialist",
        "details": (
            "She can help with general library assistance. "
            "Email: khawla.alhemeiri@ku.ac.ae | Phone: +971 2 312 3959 | "
            "Location: Main E Building, 1st Floor, Room E01035"
        ),
        "tokens": [
            "khawla", "alhemeiri", "khawla alhemeiri",
        ],
    },
    {
        "full_name": "Meera K. Alnaqbi",
        "role": "Library Information Specialist",
        "details": (
            "She can help with acquisitions, new title requests, collection development, "
            "and general library assistance. "
            "Email: meera.alnaqbi@ku.ac.ae | Phone: +971 2 312 3375"
        ),
        "tokens": [
            "meera", "alnaqbi", "meera alnaqbi", "meera k alnaqbi",
        ],
    },
]

def _normalize_name_query(text: str):
    return [t for t in re.sub(r"[^a-z0-9 ]+", " ", (text or "").lower()).split() if t]

def _dedupe_keep_order(items):
    seen = set()
    out = []
    for item in items:
        if item and item not in seen:
            seen.add(item)
            out.append(item)
    return out

def _title_case_name(name: str) -> str:
    return re.sub(r"\s+", " ", (name or "").strip()).title()

def _build_staff_tokens(full_name: str):
    honorifics = {"dr", "mr", "mrs", "ms", "prof"}
    raw_tokens = _normalize_name_query(full_name)
    core_tokens = [t for t in raw_tokens if t not in honorifics]
    token_lists = [raw_tokens, core_tokens]
    variants = []
    for toks in token_lists:
        if not toks:
            continue
        variants.extend(toks)
        variants.append(" ".join(toks))
        for n in (2, 3, 4):
            if len(toks) >= n:
                for i in range(len(toks) - n + 1):
                    variants.append(" ".join(toks[i:i+n]))
    return _dedupe_keep_order(variants)

def _parse_staff_directory_text(text: str):
    staff_entries = []
    if not text:
        return staff_entries

    lines = [line.rstrip() for line in text.splitlines()]
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        is_name_line = (
            line
            and line == line.upper()
            and not line.startswith("===")
            and not line.startswith("SOURCE:")
            and not line.startswith("TITLE:")
            and any(ch.isalpha() for ch in line)
            and len(line.split()) <= 10
        )
        if not is_name_line:
            i += 1
            continue

        name_line = line
        block = []
        i += 1
        while i < len(lines):
            nxt = lines[i].strip()
            next_is_name = (
                nxt
                and nxt == nxt.upper()
                and not nxt.startswith("===")
                and not nxt.startswith("SOURCE:")
                and not nxt.startswith("TITLE:")
                and any(ch.isalpha() for ch in nxt)
                and len(nxt.split()) <= 10
            )
            if next_is_name:
                break
            block.append(nxt)
            i += 1

        role = ""
        email = ""
        phone = ""
        mobile = ""
        location = ""
        best_for = ""
        schedule = ""
        extra_bits = []
        for raw in block:
            if not raw or raw.startswith("==="):
                continue
            low = raw.lower()
            if raw.startswith("Title:"):
                role = raw.split(":", 1)[1].strip()
            elif raw.startswith("Email:"):
                email = raw.split(":", 1)[1].strip()
            elif raw.startswith("Phone:") or raw.startswith("Work Phone:"):
                phone = raw.split(":", 1)[1].strip()
            elif raw.startswith("Mobile:"):
                mobile = raw.split(":", 1)[1].strip()
            elif raw.startswith("Location:"):
                location = raw.split(":", 1)[1].strip()
            elif raw.startswith("Best for:"):
                best_for = raw.split(":", 1)[1].strip()
            elif raw.startswith("Schedule appointment:"):
                schedule = raw.split(":", 1)[1].strip()
            elif any(low.startswith(prefix) for prefix in ["linkedin:", "orcid:"]):
                extra_bits.append(raw)
            else:
                extra_bits.append(raw)

        details_parts = []
        if best_for:
            details_parts.append(f"Best for: {best_for}")
        if email:
            details_parts.append(f"Email: {email}")
        if phone:
            details_parts.append(f"Phone: {phone}")
        if mobile:
            details_parts.append(f"Mobile: {mobile}")
        if location:
            details_parts.append(f"Location: {location}")
        if schedule:
            details_parts.append(f"Schedule appointment: {schedule}")
        details_parts.extend(extra_bits)

        full_name = _title_case_name(name_line)
        staff_entries.append({
            "full_name": full_name,
            "role": role or "Library staff member",
            "details": " | ".join(_dedupe_keep_order(details_parts)),
            "tokens": _build_staff_tokens(full_name),
            "source_title": "Khalifa University Library Staff Directory and Contacts",
            "source": "https://library.ku.ac.ae/librarystaff",
        })

    return staff_entries

def _load_staff_directory_from_kb():
    entries = []
    try:
        for filepath in glob.glob(os.path.join(KNOWLEDGE_DIR, "*.txt")):
            name = os.path.basename(filepath).lower()
            if "staff" not in name and "contact" not in name:
                continue
            with open(filepath, "r", encoding="utf-8") as f:
                content = f.read()
            if "staff directory" not in content.lower() and "library staff" not in content.lower():
                continue
            entries.extend(_parse_staff_directory_text(content))
    except Exception as e:
        print(f"Staff KB parse error: {e}")

    deduped = []
    seen = set()
    for entry in entries:
        key = entry.get("full_name", "").lower()
        if key and key not in seen:
            seen.add(key)
            deduped.append(entry)
    return deduped

def _staff_lookup_candidates():
    return kb_staff_directory or STAFF_DIRECTORY

def _role_key(name: str) -> str:
    return re.sub(r"[^a-z0-9]+", " ", (name or "").lower()).strip()

def _build_role_aliases(staff: dict):
    role = (staff.get("role") or "").strip()
    details = (staff.get("details") or "").strip()
    full_name = staff.get("full_name", "")
    key = _role_key(full_name)

    aliases = []
    if role:
        aliases.append(role)
        role_l = role.lower()
        parts = [p.strip() for p in re.split(r"[\/,]|\band\b", role_l) if p.strip()]
        aliases.extend(parts)
        if "manager" in role_l:
            mgr_tail = re.sub(r"^manager\s*,?\s*", "", role_l).strip()
            if mgr_tail:
                aliases.extend([
                    mgr_tail,
                    f"{mgr_tail} librarian",
                    f"{mgr_tail.rstrip('s')} librarian",
                    f"{mgr_tail} manager",
                ])
        if "librarian" in role_l:
            base = role_l.replace("librarian", "").replace("/", " ").strip(" ,")
            if base:
                aliases.extend([
                    base,
                    f"{base} librarian",
                    f"{base.rstrip('s')} librarian",
                ])

    best_for = ""
    m = re.search(r"Best for:\s*([^|]+)", details, re.IGNORECASE)
    if m:
        best_for = m.group(1).strip()
    if best_for:
        aliases.extend([p.strip() for p in best_for.split(",") if p.strip()])

    manual = {
        "nikesh narayanan": [
            "research librarian", "access services librarian", "research and access services librarian",
            "research access librarian", "orcid librarian",
            "research impact librarian", "bibliometrics librarian", "scholarly communication librarian",
            "khazna librarian", "scival librarian",
        ],
        "walter brian hall": [
            "systems librarian", "system librarian", "library systems librarian",
            "digital services librarian", "technology services librarian", "website librarian",
            "technology librarian", "digital librarian",
            "open access librarian", "open access", "oa librarian",
            "apc librarian", "article processing charge",
            "general librarian", "public services librarian",
        ],
        "rani anand": [
            "e resources librarian", "e-resources librarian", "electronic resources librarian",
            "database librarian", "database access librarian", "resource access librarian",
        ],
        "jason fetty": [
            "medical librarian", "health sciences librarian", "clinical librarian",
            "systematic review librarian", "pubmed librarian",
        ],
        "alia al harrasi": [
            "acquisitions librarian", "acquisition librarian", "technical services librarian",
            "technical service librarian", "collection development librarian", "cataloguing librarian",
            "metadata librarian",
        ],
        "muna ahmad mohammad al blooshi": [
            "public services librarian", "public service librarian", "circulation librarian",
            "access services manager", "service desk librarian",
        ],
        "dr abdulla al hefeiti": [
            "library director", "director of library", "director libraries", "assistant provost libraries",
        ],
        "abdulla al hefeiti": [
            "library director", "director of library", "director libraries", "assistant provost libraries",
        ],
        # ── New staff role aliases ──────────────────────────────────
        "suaad al jneibi": [
            "ill librarian", "interlibrary loan librarian", "ill specialist",
            "ill contact", "document delivery", "ill staff",
        ],
        "shamsa saeed salem alhosani": [
            "cataloguing specialist", "cataloging specialist", "cataloguer",
            "library cataloguing", "library cataloging",
        ],
        "william nathaniel hutchinson iii": [
            "cataloguing specialist", "cataloging specialist", "cataloguer",
            "library cataloguing", "library cataloging",
        ],
        "meera k alnaqbi": [
            "acquisitions specialist", "acquisitions staff", "acquisition specialist",
            "new title request", "book request", "purchase request",
            "collection development specialist",
        ],
        "meera k. alnaqbi": [
            "acquisitions specialist", "acquisitions staff", "acquisition specialist",
            "new title request", "book request", "purchase request",
            "collection development specialist",
        ],
    }
    aliases.extend(manual.get(key, []))

    normalized = []
    for a in aliases:
        a = re.sub(r"[^a-z0-9&/ +()-]+", " ", (a or "").lower())
        a = re.sub(r"\s+", " ", a).strip(" ,")
        if a:
            normalized.append(a)
            if a.endswith(" services"):
                normalized.append(a[:-1])
            if a.endswith(" service"):
                normalized.append(a + " librarian")
            if a.endswith(" resources"):
                normalized.append(a[:-1])
    return _dedupe_keep_order(normalized)

def _match_staff_role(question: str):
    ql = re.sub(r"[^a-z0-9 ]+", " ", (question or "").lower())
    ql = re.sub(r"\s+", " ", ql).strip()
    if not ql:
        return None

    # Staff role lookup only makes sense for short questions asking WHO/CONTACT
    # Long research questions (>12 words) should never trigger this
    if len(ql.split()) > 12:
        return None

    # Also exclude questions that are clearly research searches, not staff lookups
    research_intent_re = re.compile(
        r"\b(i need|find me|looking for|search for|show me|give me|"
        r"articles?|papers?|books?|literature|how effective|how does|"
        r"what are|what is the|impact of|effect of|based on|published)\b"
    )
    if research_intent_re.search(ql):
        return None

    role_trigger_re = re.compile(
        r"\b(librarian|library director|director|manager|services?|service|systems?|technology|website|"
        r"research|access|open access|orcid|bibliometric|bibliometrics|public services?|"
        r"technical services?|acquisitions?|collection development|catalogu(?:e|ing)|metadata|"
        r"database|e resources|e-resources|electronic resources|medical|clinical|systematic review|"
        r"circulation|interlibrary loan|ill|document delivery|"
        r"cataloging|cataloguer|general library|general service)\b"
    )
    if not role_trigger_re.search(ql):
        return None

    best = None
    best_score = 0
    for staff in _staff_lookup_candidates():
        score = 0
        for alias in _build_role_aliases(staff):
            if not alias:
                continue
            alias_words = alias.split()
            if alias in ql:
                score = max(score, 100 + len(alias_words))
            elif len(alias_words) >= 2 and all(w in ql.split() for w in alias_words):
                score = max(score, 70 + len(alias_words))
            else:
                overlap = sum(1 for w in alias_words if len(w) > 2 and w in ql.split())
                if overlap >= 2:
                    score = max(score, 40 + overlap)
        role_words = _normalize_name_query(staff.get("role", ""))
        if role_words:
            overlap = sum(1 for w in role_words if len(w) > 2 and w in ql.split())
            if overlap >= 2:
                score = max(score, 20 + overlap)
        if score > best_score:
            best_score = score
            best = staff

    return best if best_score >= 42 else None

def _match_staff_name(question: str):
    tokens = _normalize_name_query(question)
    if not tokens or len(tokens) > 5:
        return None
    ql = (question or "").strip().lower()
    blocked = ["who is", "who handles", "who can help", "contact", "librarian", "library"]
    if any(b in ql for b in blocked):
        return None
    for staff in _staff_lookup_candidates():
        staff_tokens = set()
        for tok in staff.get("tokens", []):
            staff_tokens.update(_normalize_name_query(tok))
            staff_tokens.add(" ".join(_normalize_name_query(tok)))
        if all(tok in staff_tokens for tok in tokens):
            return staff
    return None

def _staff_name_answer(staff: dict, partial: str) -> str:
    return (
        f"Did you mean <strong>{staff['full_name']}</strong>?<br><br>"
        f"<strong>{staff['full_name']}</strong> is the <strong>{staff['role']}</strong>. {staff['details']}"
    )

def _staff_role_answer(staff: dict, question: str) -> str:
    return (
        f"For <strong>{question}</strong>, the best match is <strong>{staff['full_name']}</strong> β€” "
        f"<strong>{staff['role']}</strong>.<br><br>{staff['details']}"
    )


GROUNDED_LIBRARY_MAP = {
    "ill": "interlibrary loan ILL document delivery request article request book unavailable not in collection borrow from another library Suaad Al Jneibi",
    "fulltext": "full text libkey nomad article access pdf article not available no full text get full text request article",
    "primo": "PRIMO discovery catalog holdings publication finder library has this journal books articles search catalog",
    "circulation": "borrowing circulation renew renewal loan period due date hold request fines fees my library account checked out overdue",
    "research_help": "Ask a Librarian research consultation reference help subject guides research skills instruction tours workshops",
    "orcid_oa": "ORCID open access APC publishing research impact Scopus SciVal bibliometrics Walter Brian Hall openaccess@ku.ac.ae",
    "database_access": "database access e-resources remote access off campus login vendor issue Rani Anand e-books patents",
    "medical_help": "medical librarian Jason Fetty PubMed Embase CINAHL Cochrane UpToDate systematic review clinical databases",
    "systems_help": "Walter Brian Hall systems website technology digital services library systems coding STEAM open access APC",
    "acquisitions": "Alia Al-Harrasi Meera Alnaqbi acquisitions request title suggest a book collection development technical services cataloguing metadata",
    "cataloguing": "Shamsa Alhosani William Hutchinson Alia Al-Harrasi cataloguing cataloging metadata technical services",
    "rooms": "study room reserve a room room booking group study rooms libcal book room room reservation",
    "visitors_alumni": "visitors visitor registration alumni alumni services external visitors access policy",
    "printing": "printing scanning photocopying printers scanner copy services",
    "refworks": "RefWorks citation manager reference management citations bibliography write n cite",
    "hours_locations": "library hours opening hours closing hours locations main campus Habshan SAN Sas Al Nakhl",
    "standards": "ASTM Compass IEEE standards ASME ASCE engineering standards",
    "theses": "ProQuest Dissertations theses Khazna institutional repository dissertations theses",
    "metrics": "impact factor journal citation reports JCR CiteScore Scopus SciVal metrics",
    "chemistry": "ACS SciFindern RSC Reaxys chemistry database",
    "physics": "APS AIP IOPScience physics database",
    "engineering": "IEEE Xplore ACM ASCE ASME Knovel engineering databases",
}

# ===== GLOBALS =====
vectorstore = None
http_client = None
kb_staff_directory = []


# ===== ANALYTICS DB =====
def init_db():
    conn = sqlite3.connect(DB_PATH)
    conn.execute('''CREATE TABLE IF NOT EXISTS queries (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        timestamp TEXT, question TEXT, tool_used TEXT,
        model TEXT, response_time REAL, result_count INTEGER,
        error TEXT
    )''')
    conn.execute('''CREATE TABLE IF NOT EXISTS bot_config (
        key TEXT PRIMARY KEY,
        value TEXT,
        updated_at TEXT
    )''')
    conn.execute('''CREATE TABLE IF NOT EXISTS feedback (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        timestamp TEXT, question TEXT, feedback TEXT, answer_excerpt TEXT, intent TEXT
    )''')
    # Set defaults if not exist
    defaults = {
        "welcome_message": "Hi! I'm the Khalifa University Library AI Assistant. I can help you find articles, books, databases, and answer questions about library services. How can I help you today?",
        "bot_personality": "You are a helpful, friendly, and knowledgeable library assistant at Khalifa University, Abu Dhabi, UAE. KU = Khalifa University, NOT Kuwait University. Be concise (2-4 sentences). Always include relevant URLs.",
        "custom_instructions": "",
        "announcement": "",
        "max_results": "5",
        "default_model": "gpt",
        "maintenance_mode": "false",
        "maintenance_message": "The library chatbot is currently undergoing maintenance. Please try again later.",
    }
    for k, v in defaults.items():
        conn.execute(
            "INSERT OR IGNORE INTO bot_config (key, value, updated_at) VALUES (?, ?, ?)",
            (k, v, datetime.utcnow().isoformat())
        )
    conn.commit()
    conn.close()

def get_config(key, default=""):
    try:
        conn = sqlite3.connect(DB_PATH)
        row = conn.execute("SELECT value FROM bot_config WHERE key=?", (key,)).fetchone()
        conn.close()
        return row[0] if row else default
    except:
        return default

def set_config(key, value):
    conn = sqlite3.connect(DB_PATH)
    conn.execute(
        "INSERT OR REPLACE INTO bot_config (key, value, updated_at) VALUES (?, ?, ?)",
        (key, value, datetime.utcnow().isoformat())
    )
    conn.commit()
    conn.close()


# ===== ADMIN AUTH =====
# ADMIN_PASSWORD must be set as HF Space Secret β€” no insecure fallback
ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "")
if not ADMIN_PASSWORD:
    import warnings
    warnings.warn("ADMIN_PASSWORD secret is not set. Admin dashboard will be inaccessible until configured.")
admin_sessions = {}  # token -> expiry timestamp
START_TIME = time.time()  # for uptime tracking

def create_session():
    token = secrets.token_hex(32)
    admin_sessions[token] = time.time() + 86400  # 24 hour session
    return token

def verify_session(request: Request):
    token = request.cookies.get("admin_session")
    if not token or token not in admin_sessions:
        return False
    if time.time() > admin_sessions[token]:
        del admin_sessions[token]
        return False
    return True

def log_query(question, tool, model, response_time, result_count=0, error=None):
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            'INSERT INTO queries (timestamp,question,tool_used,model,response_time,result_count,error) VALUES (?,?,?,?,?,?,?)',
            (datetime.utcnow().isoformat(), question, tool, model, response_time, result_count, error)
        )
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Log error: {e}")


# ===== RAG SETUP =====
def load_documents():
    global kb_staff_directory
    docs = []
    files = glob.glob(os.path.join(KNOWLEDGE_DIR, "*.txt"))
    kb_staff_directory = _load_staff_directory_from_kb()
    if kb_staff_directory:
        print(f"Loaded {len(kb_staff_directory)} staff entries from KB")
    for filepath in files:
        try:
            with open(filepath, "r", encoding="utf-8") as f:
                content = f.read()
            lines = content.split("\n", 3)
            source, title, text = "", "", content
            for line in lines[:2]:
                if line.startswith("SOURCE:"): source = line.replace("SOURCE:", "").strip()
                elif line.startswith("TITLE:"): title = line.replace("TITLE:", "").strip()
            if source or title: text = "\n".join(lines[2:]).strip()
            docs.append(Document(page_content=text, metadata={"source": source, "title": title}))
        except Exception as e:
            print(f"Error loading {filepath}: {e}")
    print(f"Loaded {len(docs)} documents")
    return docs

def build_vectorstore(docs, force_rebuild=False):
    embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
    index_file = os.path.join(FAISS_INDEX_PATH, "index.faiss")

    # On startup: load existing index if available (saves cost + time)
    if not force_rebuild and os.path.exists(index_file):
        print(f"Loading existing FAISS index from {FAISS_INDEX_PATH}")
        store = FAISS.load_local(FAISS_INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
        print(f"Loaded existing index with {store.index.ntotal} chunks")
        return store

    # Force rebuild: always re-embed all documents from scratch
    print(f"Building new FAISS index from {len(docs)} documents...")
    splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
    chunks = splitter.split_documents(docs)
    print(f"Split into {len(chunks)} chunks, embedding now...")
    store = FAISS.from_documents(chunks, embeddings)
    os.makedirs(FAISS_INDEX_PATH, exist_ok=True)
    store.save_local(FAISS_INDEX_PATH)
    print(f"FAISS index saved with {store.index.ntotal} chunks")
    return store


# ===== TOOL: SEARCH PRIMO =====
def _boolean_to_primo_params(boolean_query: str) -> str:
    """
    Convert Boolean string to PRIMO REST API multi-query format.
    PRIMO API uses q= (not query=) and requires %20 encoded spaces.

    ("AI" OR "ML") AND ("cancer") AND ("deep learning")
    β†’ q=any,contains,AI%20OR%20ML,AND&q=any,contains,cancer,AND&q=any,contains,deep%20learning

    Single concept: q=any,contains,machine%20learning
    """
    from urllib.parse import quote

    # If no Boolean operators β€” simple single query
    if not (re.search(r'\bAND\b', boolean_query) and '(' in boolean_query):
        clean = boolean_query.replace('"', '').strip()
        return f"q=any,contains,{quote(clean)}"

    # Split on top-level AND
    groups = []
    depth = 0
    chunk = ""
    for char in boolean_query:
        if char == '(':
            depth += 1
            chunk += char
        elif char == ')':
            depth -= 1
            chunk += char
        else:
            chunk += char
        if depth == 0 and chunk.upper().endswith(' AND '):
            groups.append(chunk[:-5].strip())
            chunk = ""
    if chunk.strip():
        groups.append(chunk.strip())
    if not groups:
        clean = boolean_query.replace('"', '').strip()
        return f"q=any,contains,{quote(clean)}"

    primo_params = []
    for i, group in enumerate(groups):
        g = group.strip()
        # Remove outer parentheses
        if g.startswith('(') and g.endswith(')'):
            g = g[1:-1].strip()
        # Remove double quotes
        g = g.replace('"', '')
        # Normalise OR spacing
        g = re.sub(r'\s+OR\s+', ' OR ', g).strip()
        if not g:
            continue
        # URL encode properly β€” spaces become %20
        encoded = quote(g)
        suffix = ',AND' if i < len(groups) - 1 else ''
        primo_params.append(f"q=any,contains,{encoded}{suffix}")

    return '&'.join(primo_params) if primo_params else f"q=any,contains,{quote(boolean_query.replace(chr(34), '').strip())}"


async def tool_search_primo(query, limit=5, peer_reviewed=False, open_access=False, year_from=None, year_to=None):
    """
    query can be either:
    - a Boolean string: ("AI" OR "ML") AND ("cancer") β€” converted to multi-query PRIMO format
    - a plain keyword string: "machine learning cancer" β€” sent as single query
    """
    api_key = os.environ.get("PRIMO_API_KEY")
    if not api_key: return {"error": "PRIMO_API_KEY not configured", "results": []}

    # Build PRIMO query params β€” multi-query format preserves all concepts
    if re.search(r'\b(AND|OR)\b', query) and '(' in query:
        # Boolean string β€” convert to multi-query format
        query_params = _boolean_to_primo_params(query)
    else:
        # Plain keywords β€” single query, URL encoded
        from urllib.parse import quote
        query_params = f"query=any,contains,{quote(query.strip())}"

    vid = "971KUOSTAR_INST:KU"
    facets = ""
    if peer_reviewed: facets += "&qInclude=facet_tlevel,exact,peer_reviewed"
    if open_access: facets += "&qInclude=facet_tlevel,exact,open_access"
    if year_from or year_to:
        yf = year_from or "1900"
        yt = year_to or str(datetime.now().year)
        facets += f"&multiFacets=facet_searchcreationdate,include,{yf}%7C,%7C{yt}"

    base = "https://api-eu.hosted.exlibrisgroup.com/primo/v1/search"
    qs = f"?vid={vid}&tab=Everything&scope=MyInst_and_CI&{query_params}&lang=en&sort=rank&limit={limit}&offset=0&mode=advanced&apikey={api_key}{facets}"

    async with httpx.AsyncClient(timeout=15) as client:
        for region in ["api-eu", "api-na", "api-ap"]:
            url = base.replace("api-eu", region) + qs
            try:
                r = await client.get(url, headers={"Accept": "application/json"})
                if r.status_code == 200:
                    data = r.json()
                    total = data.get("info", {}).get("total", 0)
                    results = []
                    for doc in data.get("docs", []):
                        pnx = doc.get("pnx", {})
                        d = pnx.get("display", {})
                        a = pnx.get("addata", {})
                        s = pnx.get("search", {})
                        c = pnx.get("control", {})
                        l = pnx.get("links", {})
                        record_id = (c.get("recordid") or [None])[0]
                        title = (d.get("title") or ["Untitled"])[0]
                        primo_url = _build_primo_search_link(title, record_id)
                        results.append({
                            "record_id": record_id,
                            "title": title,
                            "creator": "; ".join(d.get("creator") or d.get("contributor") or []) or "Unknown",
                            "date": (s.get("creationdate") or a.get("risdate") or a.get("date") or [""])[0],
                            "type": (d.get("type") or [""])[0],
                            "source": (d.get("source") or a.get("jtitle") or [""])[0],
                            "description": ((d.get("description") or [""])[0] or "")[:400],
                            "doi": (a.get("doi") or [None])[0],
                            "primo_url": primo_url,
                            "link": ((l.get("openurl") or l.get("linktorsrc") or [None])[0]) or primo_url,
                            "open_access": (d.get("oa") or [""])[0] == "free_for_read",
                            "_source": "PRIMO",
                        })
                    return {"total": total, "results": results, "source": "PRIMO"}
            except Exception:
                continue
    return {"error": "PRIMO API unavailable", "results": [], "source": "PRIMO"}


# ===== MCP HELPER =====
async def _call_mcp(api_key, prompt, mcp_url, mcp_name, timeout=30):
    """Call Anthropic API with an MCP server. Returns text content or raises."""
    async with httpx.AsyncClient(timeout=timeout) as client:
        r = await client.post(
            "https://api.anthropic.com/v1/messages",
            headers={
                "Content-Type": "application/json",
                "x-api-key": api_key,
                "anthropic-version": "2023-06-01",
                "anthropic-beta": "mcp-client-2025-04-04",
            },
            json={
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 2000,
                "messages": [{"role": "user", "content": prompt}],
                "mcp_servers": [{"type": "url", "url": mcp_url, "name": mcp_name}],
            },
        )
        if r.status_code != 200:
            raise Exception(f"Anthropic API: {r.status_code}")
        data = r.json()
        parts = []
        for block in data.get("content", []):
            if block.get("type") == "text":
                parts.append(block["text"])
            elif block.get("type") == "mcp_tool_result":
                for item in block.get("content", []):
                    if item.get("type") == "text":
                        parts.append(item["text"])
        return "\n".join(parts)


async def _parse_results(api_key, raw_text, source_name, limit=5):
    """Parse raw MCP results into structured JSON."""
    async with httpx.AsyncClient(timeout=20) as client:
        r = await client.post(
            "https://api.anthropic.com/v1/messages",
            headers={"Content-Type": "application/json", "x-api-key": api_key, "anthropic-version": "2023-06-01"},
            json={
                "model": "claude-sonnet-4-20250514", "max_tokens": 2000,
                "messages": [{"role": "user", "content": f"""Extract search results into a JSON array. Each item: title, creator, date, source, doi, link, description, type. Return ONLY valid JSON array. No markdown. If none, return [].

Text:
{raw_text[:3000]}"""}],
            },
        )
        if r.status_code != 200: return []
        text = "".join(b["text"] for b in r.json().get("content", []) if b.get("type") == "text").strip()
        if text.startswith("```"): text = text.split("\n", 1)[1].rsplit("```", 1)[0].strip()
        results = json.loads(text)
        for item in results:
            item["_source"] = source_name
            if item.get("doi") and not item.get("link"): item["link"] = f"https://doi.org/{item['doi']}"
        return results[:limit]


# ===== TOOL: SEARCH PUBMED (direct NCBI E-utilities β€” free, reliable) =====
async def tool_search_pubmed(query, limit=5):
    base = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            r = await client.get(f"{base}/esearch.fcgi?db=pubmed&term={query}&retmax={limit}&retmode=json&sort=relevance")
            if r.status_code != 200: return {"error": "PubMed search failed", "results": [], "source": "PubMed"}
            ids = r.json().get("esearchresult", {}).get("idlist", [])
            if not ids: return {"total": 0, "results": [], "source": "PubMed"}
            r2 = await client.get(f"{base}/esummary.fcgi?db=pubmed&id={','.join(ids)}&retmode=json")
            if r2.status_code != 200: return {"error": "PubMed fetch failed", "results": [], "source": "PubMed"}
            data = r2.json().get("result", {})
            results = []
            for pid in ids:
                rec = data.get(pid, {})
                if not isinstance(rec, dict): continue
                authors = ", ".join(a.get("name", "") for a in rec.get("authors", [])[:3])
                if len(rec.get("authors", [])) > 3: authors += " et al."
                results.append({
                    "title": rec.get("title", ""), "creator": authors, "date": rec.get("pubdate", ""),
                    "source": rec.get("fulljournalname", rec.get("source", "")),
                    "doi": rec.get("elocationid", "").replace("doi: ", "") if "doi:" in rec.get("elocationid", "") else None,
                    "pmid": pid, "link": f"https://pubmed.ncbi.nlm.nih.gov/{pid}/",
                    "type": "Journal Article", "_source": "PubMed",
                })
            total = int(r.json().get("esearchresult", {}).get("count", 0))
            return {"total": total, "results": results, "source": "PubMed"}
    except Exception as e:
        return {"error": f"PubMed: {str(e)}", "results": [], "source": "PubMed"}

# ===== TOOL: SEARCH CONSENSUS (via Semantic Scholar with consensus framing) =====
async def tool_search_consensus(query, limit=5):
    """
    Consensus.app requires OAuth so we can't call it directly.
    Instead we search Semantic Scholar with the same query and return
    results alongside a direct Consensus deep-link so the user can
    also check the AI-synthesized answer there.
    """
    scholar = await tool_search_scholar(query, limit)
    scholar["source"] = "Consensus / Semantic Scholar"
    scholar["consensus_url"] = f"https://consensus.app/results/?q={query}"
    scholar["message"] = "Results from Semantic Scholar. For AI-synthesized consensus, click the Consensus link."
    return scholar


# ===== TOOL: SEARCH SEMANTIC SCHOLAR (direct API β€” free, no auth) =====
async def tool_search_scholar(query, limit=5):
    """Search 200M+ papers via Semantic Scholar API. Free, no API key needed."""
    url = "https://api.semanticscholar.org/graph/v1/paper/search/bulk"
    params = {
        "query": query,
        "limit": min(limit, 20),
        "fields": "title,authors,year,venue,externalIds,abstract,citationCount,openAccessPdf,publicationTypes",
    }
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            r = await client.get(url, params=params, headers={"Accept": "application/json"})
            if r.status_code != 200:
                return {"error": f"Semantic Scholar API: {r.status_code}", "results": [], "source": "Semantic Scholar"}

            data = r.json()
            total = data.get("total", 0)
            results = []
            for paper in data.get("data", [])[:limit]:
                authors = ", ".join(a.get("name", "") for a in (paper.get("authors") or [])[:3])
                if len(paper.get("authors") or []) > 3:
                    authors += " et al."
                ext_ids = paper.get("externalIds") or {}
                doi = ext_ids.get("DOI")
                link = None
                if paper.get("openAccessPdf", {}).get("url"):
                    link = paper["openAccessPdf"]["url"]
                elif doi:
                    link = f"https://doi.org/{doi}"
                else:
                    s2_id = paper.get("paperId")
                    if s2_id:
                        link = f"https://www.semanticscholar.org/paper/{s2_id}"

                results.append({
                    "title": paper.get("title", ""),
                    "creator": authors,
                    "date": str(paper.get("year", "")),
                    "source": paper.get("venue", ""),
                    "description": ((paper.get("abstract") or "")[:400]),
                    "doi": doi,
                    "link": link,
                    "citations": paper.get("citationCount", 0),
                    "type": (paper.get("publicationTypes") or ["Article"])[0] if paper.get("publicationTypes") else "Article",
                    "open_access": bool(paper.get("openAccessPdf")),
                    "_source": "Semantic Scholar",
                })
            return {"total": total, "results": results, "source": "Semantic Scholar"}
    except Exception as e:
        return {"error": f"Semantic Scholar: {str(e)}", "results": [], "source": "Semantic Scholar"}

async def tool_library_info(question, history=None, model="gpt"):
    if not vectorstore:
        return {"answer": "Knowledge base not initialized.", "sources": [], "has_answer": False}

    # Build search query β€” use question + history context
    base_query = question
    if history:
        history_text = "\n".join(f"{'User' if m['role']=='user' else 'Assistant'}: {m['content']}" for m in history[-3:])
        base_query = f"{history_text}\n{question}"

    # ── Semantic query expansion via lightweight LLM interpreter + grounded institutional map ──
    interp = await _interpret_semantics(question, history or [])
    grounding_text = " ".join(GROUNDED_LIBRARY_MAP.get(k, "") for k in interp.get("grounding_keys", []))
    canonical_text = " ".join(interp.get("canonical_terms", []))
    expanded_query = " ".join(x for x in [base_query, canonical_text, grounding_text] if x).strip()

    # ── FAISS scored search ──
    docs_with_scores = vectorstore.similarity_search_with_score(expanded_query, k=TOP_K)
    if not docs_with_scores:
        return {"answer": "", "sources": [], "has_answer": False}

    best_score = min(score for _, score in docs_with_scores)
    print(f"RAG best_score={best_score:.3f} for: {question[:60]}")

    # More forgiving threshold for library-service questions; still reject clearly unrelated queries
    score_threshold = 1.45
    if interp.get("intent_hint") == "library_info":
        score_threshold = 1.7
    if best_score > score_threshold:
        print(f"RAG skipped β€” score {best_score:.3f} exceeds {score_threshold:.2f} threshold")
        return {"answer": "", "sources": [], "has_answer": False}

    docs = [doc for doc, _ in docs_with_scores]
    context = "\n\n".join(d.page_content for d in docs)

    # If score is moderate (0.8–1.4), the match may be close but not exact.
    # Instruct the LLM to add a "Did you mean...?" clarification if it interprets the question loosely.
    moderate_match = 0.8 < best_score <= 1.4
    did_you_mean_instruction = """
- If you are answering a question that uses different wording from what's in the context
  (e.g. user asked "research librarian" but context says "Research and Access Services Librarian"),
  start your answer with: "Did you mean [exact title from context]? If so, here is the information:"
  then give the answer.""" if moderate_match else ""

    prompt = f"""You are the Khalifa University Library AI Assistant in Abu Dhabi, UAE.
KU means Khalifa University, NOT Kuwait University.

RULES β€” follow exactly:
1. Answer ONLY using the context provided below.
2. If the context has relevant information β†’ answer in 2-4 sentences, include URLs if present.{did_you_mean_instruction}
3. If the context does NOT contain the answer β†’ output the single word: NO_LIBRARY_ANSWER
   - Do NOT write "I'm sorry"
   - Do NOT write "I don't have information"
   - Do NOT suggest contacting the library
   - Do NOT apologise
   - ONLY output: NO_LIBRARY_ANSWER

Context:
{context}

Question: {question}

Answer:"""

    # Respect the model selection β€” use Claude if requested, GPT otherwise
    use_claude = model == "claude" and os.environ.get("ANTHROPIC_API_KEY")
    if use_claude:
        from langchain_anthropic import ChatAnthropic
        llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0.2, max_tokens=500)
    else:
        llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.2, max_tokens=500)

    response = llm.invoke(prompt)
    answer = response.content.strip()

    # LLM signalled it couldn't answer from context
    if answer == "NO_LIBRARY_ANSWER" or answer.startswith("NO_LIBRARY_ANSWER"):
        return {"answer": "", "sources": [], "has_answer": False}

    # Catch cases where LLM ignored the NO_LIBRARY_ANSWER instruction
    # and generated a polite "I don't have info" response instead
    # Normalise smart/curly apostrophes to straight before pattern matching
    answer_normalised = answer.lower().replace("’", "'").replace("β€˜", "'").replace("β€œ", '"').replace("”", '"')

    no_info_patterns = [
        "i don't have",
        "i do not have",
        "i'm sorry",
        "i am sorry",
        "i apologize",
        "i apologise",
        "no specific information",
        "not available in",
        "not in the context",
        "context does not contain",
        "context doesn't contain",
        "i cannot find",
        "i could not find",
        "don't have information",
        "do not have information",
        "unable to find",
        "unable to provide",
        "not found in",
        "no information",
        "for further inquiries",
        "for more information, please contact",
        "please visit ask",
        "please contact the library",
        "recommend checking",
        "i'd suggest",
        "i would suggest contacting",
    ]
    if any(p in answer_normalised for p in no_info_patterns):
        print(f"RAG no-info pattern matched: '{answer_normalised[:80]}'")
        return {"answer": "", "sources": [], "has_answer": False}

    sources = []
    seen = set()
    for d in docs:
        src = d.metadata.get("source", "")
        title = d.metadata.get("title", "")
        key = src or title
        if key and key not in seen:
            seen.add(key)
            sources.append({"title": title, "source": src})

    return {"answer": answer, "sources": sources, "has_answer": True}


# ===== DETECT MEDICAL TOPIC =====
def is_medical_topic(text):
    lower = text.lower()
    return any(kw in lower for kw in MEDICAL_KEYWORDS)


# ===== STARTUP =====
@asynccontextmanager
async def lifespan(app: FastAPI):
    global vectorstore, http_client
    print("=== Starting KU Library AI Agent ===")
    init_db()
    docs = load_documents()
    if docs:
        vectorstore = build_vectorstore(docs)
        print(f"Vector store ready with {vectorstore.index.ntotal} vectors")
    http_client = httpx.AsyncClient(timeout=15)
    yield
    await http_client.aclose()
    print("Shutting down...")


# ===== FASTAPI =====
app = FastAPI(title="KU Library AI Agent", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])


# ===== MODELS =====
class ChatMessage(BaseModel):
    role: str
    content: str

class SearchRequest(BaseModel):
    query: str
    source: str = "primo"  # primo, pubmed, scholar, consensus, all
    model: str = "gpt"
    limit: int = 5
    peer_reviewed: bool = False
    open_access: bool = False
    year_from: str | None = None
    year_to: str | None = None

class RAGRequest(BaseModel):
    question: str
    model: str = "gpt"
    history: list[ChatMessage] = []

class AgentRequest(BaseModel):
    question: str
    model: str = "gpt"
    history: list[ChatMessage] = []


# ===== ENDPOINTS =====
@app.get("/")
def health():
    return {
        "status": "ok",
        "vectorstore_ready": vectorstore is not None,
        "tools": ["search_primo", "search_pubmed", "search_scholar", "search_consensus", "get_library_info"],
        "endpoints": ["/rag", "/search", "/agent", "/general", "/config", "/year"],
        "models": {
            "gpt": bool(os.environ.get("OPENAI_API_KEY")),
            "claude": bool(os.environ.get("ANTHROPIC_API_KEY")),
        },
    }


# Fix 6: authoritative server-side year β€” frontend uses this instead of client device clock
@app.get("/year")
def get_year():
    now = datetime.utcnow()
    return {
        "year": now.year,
        "month": now.month,
        "date": now.strftime("%Y-%m-%d"),
    }


# ---- Spell correction + Boolean building (uses HF Space OpenAI β€” separate quota from Cloudflare) ----
class CorrectRequest(BaseModel):
    query: str
    year: int = 2026

def _extract_json_object(text: str) -> dict:
    s, e = text.find("{"), text.rfind("}")
    if s == -1 or e == -1 or e <= s:
        raise ValueError("No JSON object found")
    return json.loads(text[s:e+1])

def _make_boolean(text: str) -> str:
    """Build a basic Boolean from text by extracting meaningful phrase groups."""
    import re as re2
    stop = re2.compile(
        r'^(of|on|in|the|a|an|and|or|for|to|with|by|from|at|is|are|was|were|be|been|'
        r'being|have|has|had|do|does|did|will|would|could|should|may|its|this|that|'
        r'these|those|about|impact|effect|role|influence|importance|use|application|'
        r'study|analysis|review|what|how|why|when|where|which)$', re2.IGNORECASE
    )
    words = text.split()
    concepts, phrase = [], []
    for w in words:
        clean = w.strip("'\"")
        if not stop.match(clean) and len(clean) > 2:
            phrase.append(clean)
        else:
            if phrase:
                concepts.append(' '.join(phrase))
                phrase = []
    if phrase:
        concepts.append(' '.join(phrase))
    if len(concepts) >= 2:
        return ' AND '.join(f'"{c}"' for c in concepts)
    if len(concepts) == 1:
        return f'"{concepts[0]}"'
    return f'"{text}"'

def _clean_database_keywords(boolean_query: str) -> str:
    return re.sub(r'\s+', ' ', re.sub(r'\b(AND|OR|NOT)\b|[()"]', ' ', boolean_query, flags=re.IGNORECASE)).strip()

def _light_strip_retrieval_boilerplate(text: str) -> str:
    cleaned = re.sub(r'^\s*(please\s+)?(?:can you|could you|would you)\s+', '', (text or '').strip(), flags=re.IGNORECASE)
    cleaned = re.sub(r'^\s*(please\s+)?help me\s+', '', cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r'^\s*please\s+', '', cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r'\s+(please|thanks|thank you|asap)$', '', cleaned, flags=re.IGNORECASE)
    return re.sub(r'\s+', ' ', cleaned).strip()


def _build_primo_search_link(title: str, record_id: str | None = None) -> str | None:
    base = 'https://khalifa.primo.exlibrisgroup.com/discovery'
    if record_id:
        return f"{base}/fulldisplay?docid={quote(str(record_id))}&vid=971KUOSTAR_INST:KU"
    clean_title = (title or '').strip()
    if not clean_title:
        return None
    return f"{base}/search?query=any,contains,{quote(clean_title)}&tab=Everything&search_scope=MyInst_and_CI&vid=971KUOSTAR_INST:KU&lang=en"


def _parse_year_value(value) -> int | None:
    m = re.search(r'(19|20)\d{2}', str(value or ''))
    return int(m.group(0)) if m else None


def _is_article_like(result: dict) -> bool:
    type_text = str(result.get('type') or '').lower()
    source_text = str(result.get('source') or '').lower()
    if any(k in type_text for k in ['article', 'journal', 'review', 'paper', 'study']):
        return True
    return bool(source_text)


def _normalize_result_links(result: dict) -> dict:
    result = dict(result or {})
    record_id = result.get('record_id') or result.get('id')
    title = result.get('title') or ''
    primo_url = result.get('primo_url') or _build_primo_search_link(title, record_id if result.get('_source') == 'PRIMO' else None)
    if primo_url:
        result['primo_url'] = primo_url
    if result.get('_source') == 'PRIMO' and not result.get('link'):
        result['link'] = primo_url
    return result


def _choose_verified_article(results: list[dict], year_from=None, year_to=None) -> dict | None:
    candidates = []
    y_from = int(year_from) if str(year_from or '').isdigit() else None
    y_to = int(year_to) if str(year_to or '').isdigit() else None
    for raw in results or []:
        r = _normalize_result_links(raw)
        yr = _parse_year_value(r.get('date'))
        if y_from and yr and yr < y_from:
            continue
        if y_to and yr and yr > y_to:
            continue
        if not _is_article_like(r):
            continue
        if not (r.get('title') and (r.get('primo_url') or r.get('link') or r.get('doi'))):
            continue
        score = 0
        if r.get('_source') == 'PRIMO':
            score += 4
        if r.get('description'):
            score += 3
        if r.get('doi'):
            score += 1
        if r.get('link'):
            score += 1
        if yr:
            score += 1
        candidates.append((score, r))
    candidates.sort(key=lambda item: item[0], reverse=True)
    if not candidates or candidates[0][0] < 5:
        return None
    return candidates[0][1]


async def _summarize_verified_article(question: str, article: dict, behavior: str, use_claude: bool) -> str:
    title = article.get('title', 'Untitled')
    creators = article.get('creator', 'Unknown')
    year = article.get('date', '')
    source = article.get('source', '')
    primo_url = article.get('primo_url') or _build_primo_search_link(title, article.get('record_id')) or 'Not available'
    direct_url = article.get('link') or ('https://doi.org/' + article['doi'] if article.get('doi') else 'Not available')
    abstract = (article.get('description') or '').strip()

    def _compose(sections: dict | None = None) -> str:
        sections = sections or {}
        lines = [
            'Recommended article',
            f'{title} ({year})' if year else title,
            '',
            'Authors',
            creators,
            '',
            'Source',
            source or 'Not clearly stated in the retrieved metadata.',
            '',
            'Open in PRIMO',
            primo_url,
        ]
        if direct_url and direct_url != 'Not available':
            lines += ['', 'Direct link', direct_url]
        lines += [
            '',
            'Verification note',
            'This answer is grounded only in the retrieved metadata and abstract/description. It does not assume access to the full text unless a direct full-text link is shown.',
            '',
            'Main research question',
            sections.get('Main research question') or (abstract or 'Not clearly stated in the retrieved abstract/metadata.'),
            '',
            'Methodology',
            sections.get('Methodology') or 'Not clearly stated in the retrieved abstract/metadata.',
            '',
            'Key findings',
            sections.get('Key findings') or (abstract or 'Not clearly stated in the retrieved abstract/metadata.'),
            '',
            'Strengths of the evidence',
            sections.get('Strengths of the evidence') or 'Not clearly stated in the retrieved abstract/metadata.',
            '',
            'Limitations of the evidence',
            sections.get('Limitations of the evidence') or 'Not clearly stated in the retrieved abstract/metadata.',
            '',
            'Contribution to current understanding',
            sections.get('Contribution to current understanding') or 'Not clearly stated in the retrieved abstract/metadata.',
        ]
        return '\n'.join(lines)

    if not abstract:
        return _compose()

    prompt = (
        f"{behavior}\n\n"
        'You are LibBee, the Khalifa University Library AI Assistant. '
        'Use ONLY the retrieved abstract or description below. '
        'Do NOT invent facts, titles, authors, links, journals, or years. '
        'If a section is not explicit, write exactly: Not clearly stated in the retrieved abstract/metadata.\n\n'
        'Return ONLY valid JSON with exactly these keys:\n'
        '{"Main research question":"...","Methodology":"...","Key findings":"...","Strengths of the evidence":"...","Limitations of the evidence":"...","Contribution to current understanding":"..."}\n\n'
        f"User request: {question}\n"
        f"Retrieved abstract/description: {abstract}\n"
    )

    try:
        if use_claude:
            from langchain_anthropic import ChatAnthropic
            llm = ChatAnthropic(model='claude-haiku-4-5-20251001', temperature=0, max_tokens=500)
        else:
            llm = ChatOpenAI(model='gpt-4o-mini', temperature=0, max_tokens=500)
        raw = llm.invoke(prompt).content.strip()
        data = _extract_json_object(raw)
        allowed = {
            'Main research question', 'Methodology', 'Key findings',
            'Strengths of the evidence', 'Limitations of the evidence',
            'Contribution to current understanding'
        }
        sections = {k: str(v).strip() for k, v in data.items() if k in allowed and str(v).strip()}
        return _compose(sections)
    except Exception:
        return _compose()

async def _build_search_plan(query: str, year: int = 2026) -> dict:
    raw_query = (query or "").strip()
    light_query = _light_strip_retrieval_boilerplate(raw_query) or raw_query
    prompt = f"""You are a search expert for Khalifa University Library.

The user typed a research request that may contain spelling issues or conversational phrasing.
Create THREE forms while preserving the user's full intent.

1. corrected: lightly edit the FULL request for spelling, grammar, and clarity.
   Preserve every substantive concept, constraint, and task.
   Do NOT collapse it into a short topic.

2. natural: write a natural-language research query for AI tools such as Consensus,
   Perplexity, Semantic Scholar, Scopus AI, PRIMO AI, and LeapSpace.
   Keep the full context and constraints, but you may remove only retrieval boilerplate
   such as "find an article", "show me", "get me", or "can you find".
   Keep constraints like one article vs many, peer reviewed, last five years,
   summarize, methodology, findings, strengths, limitations, and contribution.

3. boolean: write a PRIMO/PubMed Boolean query with AND/OR/parentheses that preserves
   the main topical concepts and important search constraints.

Examples:
Input: "Find one peer-reviewed article from the last five years on climate change and biodiversity. Summarize the methodology and findings."
β†’ corrected:"Find one peer-reviewed article from the last five years on climate change and biodiversity. Summarize the methodology and findings."
β†’ natural:"Peer-reviewed article from the last five years on climate change and biodiversity. Summarize the methodology and findings."
β†’ boolean:("climate change" OR "global warming") AND (biodiversity OR ecosystems)

Input: "impuct glubal waming on biodiversty"
β†’ corrected:"impact of global warming on biodiversity"
β†’ natural:"impact of global warming on biodiversity"
β†’ boolean:("global warming" OR "climate change") AND biodiversity

Return ONLY valid JSON:
{{"corrected":"full polished request","natural":"full natural-language research query","boolean":"(A OR B) AND (C OR D)","year_from":"","year_to":"","peer_reviewed":false,"open_access":false}}

Query: "{light_query}"""
    try:
        llm = ChatOpenAI(model="gpt-4o-mini", temperature=0, max_tokens=300)
        response = llm.invoke(prompt)
        result = _extract_json_object(response.content.strip())
        corrected = result.get("corrected", query).strip() or query
        natural = result.get("natural", corrected).strip() or corrected
        boolean = (result.get("boolean") or "").strip()
        has_operators = bool(re.search(r'\b(AND|OR)\b', boolean)) if boolean else False
        has_parens = "(" in boolean if boolean else False
        if not has_operators or not has_parens:
            boolean = _make_boolean(corrected)
        return {
            "corrected": corrected,
            "natural": natural,
            "boolean": boolean,
            "database_query": _clean_database_keywords(boolean),
            "year_from": result.get("year_from", "") or "",
            "year_to": result.get("year_to", "") or "",
            "peer_reviewed": bool(result.get("peer_reviewed", False)),
            "open_access": bool(result.get("open_access", False)),
        }
    except Exception:
        boolean = _make_boolean(raw_query)
        corrected = raw_query.strip() or raw_query
        natural = _light_strip_retrieval_boilerplate(raw_query) or corrected
        return {
            "corrected": corrected,
            "natural": natural,
            "boolean": boolean,
            "database_query": _clean_database_keywords(boolean),
            "year_from": "",
            "year_to": "",
            "peer_reviewed": False,
            "open_access": False,
        }



def get_behavior_instructions() -> str:
    base = get_config("bot_personality", "You are a helpful, friendly, and knowledgeable library assistant at Khalifa University, Abu Dhabi, UAE. KU = Khalifa University, NOT Kuwait University. Be concise (2-4 sentences). Always include relevant URLs.")
    extra = get_config("custom_instructions", "")
    return (base + ("\n" + extra if extra else "")).strip()


def _looks_social_or_greeting(question: str) -> bool:
    # SOCIAL_RE is anchored with ^ so .match() is the correct call.
    # Using .search() with ^ worked most of the time but could silently
    # fail when the engine didn't treat ^ as start-of-string in search mode
    # with certain Unicode inputs β€” .match() is unambiguous.
    return bool(SOCIAL_RE.match((question or "").strip()))


async def _interpret_semantics(question: str, history=None) -> dict:
    q = (question or "").strip()
    ql = q.lower()
    canonical_terms = []
    grounding_keys = []
    social = False

    def add(key: str, *terms: str):
        if key and key not in grounding_keys:
            grounding_keys.append(key)
        for t in terms:
            if t and t not in canonical_terms:
                canonical_terms.append(t)

    if _looks_social_or_greeting(q):
        social = True
        return {"intent_hint": "general", "canonical_terms": canonical_terms, "grounding_keys": grounding_keys, "social": True}

    if _looks_library_hours_question(q):
        add("circulation", "library hours", "opening hours", "closing hours")
        return {"intent_hint": "library_info", "canonical_terms": canonical_terms, "grounding_keys": grounding_keys, "social": False}

    if _looks_nonlibrary_ku_question(q):
        return {"intent_hint": "general", "canonical_terms": canonical_terms, "grounding_keys": grounding_keys, "social": False}

    contact_or_support = bool(re.search(r"\b(who handles|who can help|who should i contact|contact for|email for|phone for|librarian for|help with access|access problem|login issue|remote access problem|vendor issue|technical issue|support)\b", ql))
    resource_or_search_task = bool(re.search(r"\b(best|which|recommend|suggest|compare|difference|find|search|articles?|papers?|books?|literature|study|studies|review|summariz(?:e|ing)|summaris(?:e|ing)|evaluate|critique|one article|single article|latest|recent|last \d+ years?)\b", ql))

    # Staff / role semantics
    if re.search(r"\b(systems? librarian|system librarian|website|digital services|library systems?|technology help)\b", ql) and contact_or_support:
        add("systems_help", "Walter Brian Hall", "Systems Librarian", "website", "technology")
    if re.search(r"\b(database access|e-?resources?|remote access|off campus|off-campus|login issue|access problem|vendor issue)\b", ql):
        if contact_or_support or re.search(r"\b(access problem|login issue|vendor issue|remote access problem|off campus access)\b", ql):
            add("database_access", "Rani Anand", "E-Resources", "database access")
        else:
            add("database_access", "databases", "e-resources", "remote access")
    if re.search(r"\b(orcid|open access|apc|article processing charge|research impact|bibliometric|bibliometrics|scival|scopus metrics?)\b", ql):
        if contact_or_support and not resource_or_search_task:
            add("orcid_oa", "Walter Brian Hall", "ORCID", "Open Access", "APC", "openaccess@ku.ac.ae")
        else:
            add("orcid_oa", "ORCID", "Open Access", "APC", "research impact")
    if re.search(r"\b(research support|research impact|bibliometrics|scival|khazna|scholarly communication|libguides)\b", ql):
        if contact_or_support and not resource_or_search_task:
            add("research_help", "Nikesh Narayanan", "research support", "bibliometrics", "Khazna")
        else:
            add("research_help", "research support", "bibliometrics", "Khazna")
    if re.search(r"\b(medical librarian|pubmed help|embase|cinahl|cochrane|uptodate|systematic review|clinical databases?)\b", ql):
        if contact_or_support and not resource_or_search_task:
            add("medical_help", "Jason Fetty", "Medical Librarian", "PubMed", "systematic review")
        else:
            add("medical_help", "PubMed", "Embase", "CINAHL", "Cochrane", "UpToDate")
    if re.search(r"\b(acquisitions?|collection development|suggest a book|request a title|new title request|purchase request|book request)\b", ql):
        add("acquisitions", "Alia Al-Harrasi", "Meera Alnaqbi", "Acquisitions", "collection development")
    if re.search(r"\b(catalogu(?:e|ing)|cataloging|metadata|cataloguer)\b", ql):
        add("cataloguing", "Shamsa Alhosani", "William Hutchinson", "cataloguing", "cataloging", "metadata")
    if re.search(r"\b(circulation|borrow|renew|due date|fine|hold request|my library account|public services?)\b", ql):
        add("circulation", "borrowing", "renewal", "My Library Account")
    if re.search(r"\b(ask a librarian|research help|research consultation|reference help|consultation)\b", ql):
        add("research_help", "Ask a Librarian", "research consultation")

    # Service / resource semantics
    if re.search(r"\b(inter\s*library loan|interlibrary loan|\bill\b|document delivery|full text unavailable|no full text|can't get (an )?article|cannot get (an )?article|article not available)\b", ql):
        add("ill", "Suaad Al Jneibi", "Interlibrary Loan", "ILL", "document delivery")
        add("fulltext", "full text", "LibKey Nomad", "article access")
    if re.search(r"\b(primo|catalog|discovery|holdings|publication finder|does the library have)\b", ql):
        add("primo", "PRIMO", "catalog", "Publication Finder")

    # Database recommendation semantics
    if re.search(r"\b(standards?|astm|ieee standards?|asme|asce)\b", ql):
        add("standards", "ASTM Compass", "IEEE standards", "ASME", "ASCE")
    if re.search(r"\b(dissertations?|theses|khazna)\b", ql):
        add("theses", "ProQuest Dissertations & Theses", "Khazna")
    if re.search(r"\b(impact factor|journal metrics?|jcr|citescore|sjr)\b", ql):
        add("metrics", "Journal Citation Reports", "CiteScore")
    if re.search(r"\b(chemistry|chemical)\b", ql):
        add("chemistry", "ACS", "SciFindern", "Reaxys")
    if re.search(r"\b(physics|optics?|photonics?)\b", ql):
        add("physics", "APS", "AIP", "IOPScience")
    if re.search(r"\b(engineering|civil engineering|mechanical engineering|electrical engineering|computer science|ai)\b", ql):
        add("engineering", "IEEE Xplore", "ACM", "Knovel", "ASCE", "ASME")

    # Name/title style library questions
    if re.search(r"\b(who is|who handles|who can help|whom should i contact|contact for)\b", ql) and (_looks_library_question(q) or grounding_keys):
        if not grounding_keys:
            add("research_help", "staff directory", "library staff")

    # Decide intent
    if _looks_medical_search(q):
        intent = "search_medical"
    elif _looks_research_question(q):
        intent = "search_academic"
    elif grounding_keys or _looks_library_question(q):
        intent = "library_info"
    elif _looks_current_question(q):
        intent = "general_recent"
    else:
        intent = "general"

    return {
        "intent_hint": intent,
        "canonical_terms": canonical_terms,
        "grounding_keys": grounding_keys,
        "social": social,
    }
def _looks_library_question(question: str) -> bool:
    return bool(LIBRARY_CUE_RE.search(question))

def _looks_current_question(question: str) -> bool:
    return bool(CURRENT_INFO_RE.search(question))

def _looks_research_question(question: str) -> bool:
    q = question.lower()
    if RESEARCH_CUE_RE.search(q):
        return True
    # Natural academic questions that don't use explicit search trigger words
    # e.g. "What are the recent advances in AI for cancer diagnosis?"
    # e.g. "How effective are mRNA vaccines in treating lung cancer?"
    # e.g. "What is the impact of climate change on water security in the UAE?"
    academic_patterns = re.compile(
        r"\b(impact of|effect[s]? of|role of|use of|application of|advance[s] in|"
        r"development[s] in|progress in|challenge[s] of|benefit[s] of|"
        r"causes? of|relationship between|comparison of|effectiveness of|"
        r"how (effective|efficient|useful|does|do|can|is|are)|"
        r"what (are the|is the) (recent|latest|current|new|emerging)|"
        r"published in the last|in the last \d+ years?|"
        r"systematic review|meta.?analysis|clinical trial[s]?|"
        r"literature on|survey of|overview of|state of the art)\b",
        re.IGNORECASE
    )
    return bool(academic_patterns.search(q))

def _looks_medical_search(question: str) -> bool:
    q = question.lower()
    if not is_medical_topic(q):
        return False
    return bool(MEDICAL_SEARCH_RE.search(q) or _looks_research_question(q))


def _looks_library_hours_question(question: str) -> bool:
    q = question.strip().lower()
    # Must match hours pattern AND have at least one library/time/open signal
    return bool(HOURS_RE.search(q)) and any(
        kw in q for kw in (
            'library', 'campus', 'habshan', 'san', 'hours', 'open', 'close',
            'schedule', 'till', 'until', 'today', 'tomorrow', 'friday',
            'saturday', 'sunday', 'week', 'ramadan'
        )
    )

def _looks_campus_question(question: str) -> bool:
    """Returns True for questions about KU library locations/branches/campuses."""
    return bool(KU_CAMPUS_RE.search(question))

def _looks_nonlibrary_ku_question(question: str) -> bool:
    q = question.strip().lower()
    if 'library' in q or 'librarian' in q or 'primo' in q or 'database' in q or 'book' in q or 'article' in q:
        return False
    return bool(KU_GENERAL_RE.search(question))

def _hours_redirect_answer() -> str:
    """
    Hardcoded library hours + always direct to the hours page.
    Hours are from the KB (ku_library_san_campus.txt). Always advise to check
    the link since times can change for exams, holidays, and Ramadan.
    """
    return (
        "Here are the current <strong>Khalifa University Library</strong> hours:<br><br>"
        "<strong>Habshan Library (SAN Campus):</strong><br>"
        "Sunday – Wednesday: 8:00 AM – 7:00 PM<br>"
        "Thursday: 8:00 AM – 4:00 PM<br>"
        "Friday: Closed<br>"
        "Saturday: 12:00 PM – 8:00 PM<br><br>"
        "⚠️ Hours may change during exam periods, public holidays, and Ramadan. "
        "Always check the official Library Hours page for the latest times:<br>"
        f"<a href=\"{LIBRARY_HOURS_URL}\" target=\"_blank\">{LIBRARY_HOURS_URL}</a>"
    )


def _ku_campus_answer() -> str:
    """
    Hardcoded answer for any question about KU library locations/campuses.
    Never answered from web β€” always this fixed text.
    """
    return (
        "Khalifa University Library has <strong>two branches</strong>:<br><br>"
        "<strong>1. Main Campus Library</strong><br>"
        "Location: E Building, Main Campus, Abu Dhabi<br>"
        "Phone: <a href=\"tel:+97123124604\">+971 2 312 4604</a><br><br>"
        "<strong>2. Habshan Library (SAN Campus)</strong><br>"
        "Location: Building 5, Ground Floor &amp; First Floor, Sas Al Nakhl (SAN) Campus, Abu Dhabi<br>"
        "Phone: <a href=\"tel:+97123123160\">+971 2 312 3160</a><br><br>"
        "For general library enquiries: "
        "<a href=\"https://library.ku.ac.ae/AskUs\" target=\"_blank\">Ask a Librarian</a> "
        "or email <a href=\"mailto:libse@ku.ac.ae\">libse@ku.ac.ae</a>."
    )

def _ku_general_redirect_answer() -> str:
    return (
        f"I’m <strong>LibBee</strong>, the Khalifa University <strong>Library</strong> AI Assistant, so I’m best for library resources, services, databases, research help, and staff contacts.<br><br>"
        f"For general Khalifa University questions, please visit the main KU website: <a href=\"{KU_MAIN_URL}\" target=\"_blank\">{KU_MAIN_URL}</a>. "
        "A broader university chatbot is available there for non-library questions."
    )

@app.post("/correct")
async def correct_query(req: CorrectRequest):
    """
    Build three query forms from the user's full request:
      - corrected: polished full request
      - natural: full natural-language AI-tool query
      - boolean: database-ready Boolean query
    Only light cleanup is applied before planning.
    """
    raw = req.query.strip()
    query_to_use = _light_strip_retrieval_boilerplate(raw) or raw
    plan = await _build_search_plan(query_to_use, req.year)
    return {
        "corrected": plan["corrected"],
        "boolean": plan["boolean"],
        "natural": plan["natural"],
        "database_query": plan["database_query"],
        "year_from": plan["year_from"],
        "year_to": plan["year_to"],
        "peer_reviewed": plan["peer_reviewed"],
        "open_access": plan["open_access"],
    }

# ---- General knowledge endpoint (uses HF Space OpenAI key β€” separate quota from Cloudflare) ----
class GeneralRequest(BaseModel):
    question: str
    history: list = []
    model: str = "gpt"

async def _answer_general(question: str, history=None) -> dict:
    """Answer general knowledge questions using live web search when available."""
    if _looks_library_hours_question(question):
        return {"answer": _hours_redirect_answer(), "sources": [], "model": "library-hours-redirect"}
    if _looks_nonlibrary_ku_question(question):
        return {"answer": _ku_general_redirect_answer(), "sources": [], "model": "ku-general-redirect"}
    if _looks_social_or_greeting(question):
        if PURE_GREETING_RE.match(question.strip()):
            guided = (
                "Hi! I’m <strong>LibBee</strong>, the Khalifa University Library AI Assistant.<br><br>"
                "I can help you with articles and books, databases, full text, Interlibrary Loan (ILL), "
                "library services, staff contacts, ORCID, RefWorks, and Open Access.<br><br>"
                "Are you looking for one of these? You can also type your question directly."
            )
            return {"answer": guided, "sources": [], "model": "libbee-greeting"}
        try:
            behavior = get_behavior_instructions()
            llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.4, max_tokens=220)
            msgs = []
            if behavior:
                msgs.append({"role": "system", "content": behavior + "\nFor social, greeting, or self-description questions, answer as LibBee in a warm, brief, natural way. Make it clear that you are LibBee, the Khalifa University Library AI Assistant, and that you help with books, articles, databases, library services, research support, and staff contacts. For questions like 'how are you', 'who are you', 'what are you', 'what can you do', 'are you a bot', playful teasing, or mild mockery, respond politely and briefly, without sounding defensive. If the question is not library-related, you may gently mention that you are specialized in library help. Match the language of the user question."})
            for m in (history or [])[-4:]:
                if m.get("role") in ("user", "assistant"):
                    msgs.append({"role": m["role"], "content": m.get("content", "")})
            msgs.append({"role": "user", "content": question})
            response = llm.invoke(msgs)
            return {"answer": response.content.strip(), "sources": [], "model": "gpt-4o-mini-social"}
        except Exception:
            return {"answer": "I’m <strong>LibBee</strong>, the Khalifa University Library chatbot. I’m here to help with library questions, books, articles, databases, full text, and library services. What would you like help with?", "sources": [], "model": "fallback-social"}
    try:
        import openai
        client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

        messages = []
        if history:
            for m in history[-5:]:
                role = m.get("role", "user")
                msg_content = m.get("content", "")
                if role in ("user", "assistant") and msg_content:
                    messages.append({"role": role, "content": msg_content})

        messages.append({"role": "user", "content": question})
        response = client.responses.create(
            model="gpt-4o-mini",
            tools=[{"type": "web_search_preview"}],
            input=messages,
        )

        answer = ""
        sources = []
        for block in response.output:
            if hasattr(block, "content"):
                for item in block.content:
                    if hasattr(item, "text"):
                        answer += item.text
                    if hasattr(item, "annotations"):
                        for ann in item.annotations:
                            if hasattr(ann, "url") and hasattr(ann, "title"):
                                sources.append({"url": ann.url, "title": ann.title})

        if not answer:
            answer = response.output_text if hasattr(response, "output_text") else ""
        return {"answer": answer.strip(), "sources": sources, "model": "gpt-4o-mini-web"}

    except Exception as e:
        print(f"Web search failed, falling back to plain GPT: {e}")
        try:
            llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.3, max_tokens=500)
            msgs = []
            for m in (history or [])[-5:]:
                if m.get("role") in ("user", "assistant"):
                    msgs.append({"role": m["role"], "content": m.get("content", "")})
            msgs.append({"role": "user", "content": question})
            response = llm.invoke(msgs)
            return {"answer": response.content.strip(), "sources": [], "model": "gpt-4o-mini"}
        except Exception as e2:
            return {"answer": "", "sources": [], "error": str(e2)}

@app.post("/general")
async def general_query(req: GeneralRequest):
    return await _answer_general(req.question, req.history)

# ---- Individual search endpoints ----
@app.post("/search")
async def search(req: SearchRequest):
    start = time.time()
    source = req.source.lower()
    result = {}

    try:
        if source == "primo":
            result = await tool_search_primo(req.query, req.limit, req.peer_reviewed, req.open_access, req.year_from, req.year_to)
        elif source == "pubmed":
            result = await tool_search_pubmed(req.query, req.limit)
        elif source == "scholar":
            result = await tool_search_scholar(req.query, req.limit)
        elif source == "consensus":
            result = await tool_search_consensus(req.query, req.limit)
        elif source == "all":
            import asyncio
            tasks = [
                tool_search_primo(req.query, req.limit, req.peer_reviewed, req.open_access, req.year_from, req.year_to),
                tool_search_pubmed(req.query, min(req.limit, 3)),
                tool_search_scholar(req.query, min(req.limit, 3)),
            ]
            results = await asyncio.gather(*tasks, return_exceptions=True)
            combined = []
            for r in results:
                if isinstance(r, dict) and "results" in r:
                    for item in r["results"]:
                        item["_source"] = r.get("source", "unknown")
                    combined.extend(r["results"])
            result = {"total": len(combined), "results": combined, "source": "Multiple"}
        else:
            result = {"error": f"Unknown source: {source}", "results": []}

        elapsed = time.time() - start
        # Logging handled by Cloudflare D1 via worker /log endpoint (single source of truth)
        result["response_time"] = round(elapsed, 2)
        result["is_medical"] = is_medical_topic(req.query)
        return result

    except Exception as e:
        elapsed = time.time() - start
        return {"error": str(e), "results": [], "response_time": round(elapsed, 2)}


# ---- Public log endpoint (frontend calls this for all queries) ----
class LogRequest(BaseModel):
    question: str
    tool: str = "unknown"
    model: str = "gpt"
    response_time: float = 0
    result_count: int = 0
    error: str | None = None

@app.post("/log")
async def log_endpoint(req: LogRequest):
    log_query(req.question, req.tool, req.model, req.response_time, req.result_count, req.error)
    return {"status": "ok"}


# ---- RAG endpoint (backward compatible) ----
@app.post("/rag")
async def rag_query(req: RAGRequest):
    start = time.time()
    try:
        history = [{"role": m.role, "content": m.content} for m in req.history] if req.history else None
        result = await tool_library_info(req.question, history, model=req.model)
        elapsed = time.time() - start
        # Logging handled by Cloudflare D1 via worker /log endpoint
        return {
            "answer": result["answer"],
            "sources": result["sources"],
            "has_answer": result.get("has_answer", True),
            "model_used": req.model,
            "response_time": round(elapsed, 2),
        }
    except Exception as e:
        elapsed = time.time() - start
        return {"answer": "", "sources": [], "has_answer": False, "error": str(e)}


# ===== LLM FIRST-GATE CLASSIFIER =====
#
# Architecture (executed in this order for every /agent request):
#
# Layer 0 β€” INSTANT free responses (no LLM, <1ms)
#   β€’ Pure greetings  β†’ hardcoded LibBee greeting
#   β€’ Exact social phrases β†’ _fixed_social_answer()
#   β€’ Staff name match    β†’ staff directory
#   β€’ Staff role match    β†’ staff directory
#   β€’ Greeting followup   β†’ clarify menu
#   β€’ Library hours       β†’ hours redirect
#   β€’ Non-library KU Q    β†’ KU website redirect
#
# Layer 1 β€” LLM CLASSIFIER (GPT-4o-mini, ~300ms, ~$0.000045/call)
#   ALL other messages hit this exactly once.
#   Returns: social | library_info | search_academic |
#            search_medical | general_recent | general
#   + optional casual_answer string for social intent
#
# Layer 2 β€” EXECUTE
#   social        β†’ _libbee_casual_response()
#   library_info  β†’ RAG pipeline (_interpret_semantics + tool_library_info)
#   search_*      β†’ PRIMO + PubMed/Scholar + RAG synthesis
#   general_recent β†’ _answer_general (web search)
#   general        β†’ _answer_general

_CLASSIFIER_SYSTEM = """You are the routing brain of LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE).
Your only job: read the user message and return a single JSON object routing it to the right handler.

INTENTS β€” pick exactly one:
  "social"         β€” casual chat, greetings, emotions, compliments, complaints, vague help requests
                     ("can you help me", "I'm frustrated", "you're great", "I give up", "help please",
                      "I don't know what to do", "I am fed up", "I need some guidance", "are you there",
                      jokes, small talk, anything with no library/research/academic content)
  "library_info"   β€” questions about KU Library services, hours, rooms, borrowing, fines, ILL, staff,
                     databases, ORCID, RefWorks, open access, APC, account, printing, remote access,
                     LibKey, acquisitions, Khazna, thesis submission, library policies, alumni access
  "search_academic"β€” user wants to FIND articles / papers / books / literature on a specific academic topic
                     (e.g. "find articles on renewable energy", "papers on machine learning in healthcare",
                      "I need books about civil engineering", "literature review on AI ethics")
  "search_medical" β€” same as search_academic but topic is medical/clinical/nursing/pharmacy/health sciences
  "general_recent" β€” questions about current events, news, latest info, who holds a position now,
                     real-time data (stock prices, today's weather, breaking news)
  "general"        β€” factual/knowledge question NOT about KU Library and NOT a research search
                     (explain a concept, historical facts, definitions, "what is quantum computing")

RULES:
  1. When in doubt between library_info and social, choose library_info if ANY library keyword is present.
  2. "I don't know how to search for articles" = library_info (has library task content).
  3. "I am fed up with searching" alone (no specific topic/database) = social (expressing frustration).
  4. "I need help finding articles on diabetes" = search_medical.
  5. KU = Khalifa University. Do NOT confuse with Kuwait University.
  6. ANY question asking about advances, approaches, methods, effectiveness, impact, or relationship
     on a specific academic/scientific topic = search_academic or search_medical. NOT library_info.
     e.g. "What are the recent advances in AI for predictive maintenance?" = search_academic
     e.g. "How effective are mRNA vaccines for cancer treatment?" = search_medical
     e.g. "What is the impact of climate change on food security?" = search_academic

For "social" intent ONLY: also include "casual_answer" β€” a warm 1-3 sentence LibBee response
(friendly librarian tone, no markdown, no bullet points). Offer to help with library services.
For all other intents: omit "casual_answer" entirely.

Respond ONLY with valid JSON, no preamble, no markdown fences.

Examples:
{"intent":"social","casual_answer":"Of course, I\'m here to help! I\'m LibBee, the KU Library AI Assistant. What would you like to find today?"}
{"intent":"social","casual_answer":"I completely understand that feeling β€” searching can be tricky at first. I\'m LibBee, the Khalifa University Library AI Assistant, and I can guide you through it step by step. What topic are you trying to research?"}
{"intent":"library_info"}
{"intent":"search_academic"}
{"intent":"search_medical"}
{"intent":"general_recent"}
{"intent":"general"}"""


async def _llm_classify(question: str, history: list) -> dict:
    """
    Single LLM call that classifies intent for ALL non-trivial messages.
    ~300ms latency, ~$0.000045 per call at GPT-4o-mini pricing.
    Returns: {"intent": str, "casual_answer": str}
    Never raises β€” falls back to {"intent":"general","casual_answer":""} on error.
    """
    # Build compact conversation context (last 2 turns, 100 chars each)
    ctx_parts = []
    for m in history[-4:]:
        role = m.get("role", "")
        text = (m.get("content") or "")[:100]
        if role in ("user", "assistant") and text:
            ctx_parts.append(f"{role}: {text}")
    ctx = " | ".join(ctx_parts) if ctx_parts else "none"

    user_msg = (
        "Message: " + question[:400] + "\n" + "Context: " + ctx + "\nJSON:"
    )

    try:
        llm = ChatOpenAI(model="gpt-4o-mini", temperature=0, max_tokens=150)
        response = llm.invoke([
            {"role": "system", "content": _CLASSIFIER_SYSTEM},
            {"role": "user",   "content": user_msg},
        ])
        raw = response.content.strip()
        if raw.startswith("```"):
            raw = raw.split("\n", 1)[1].rsplit("```", 1)[0].strip()
        result = json.loads(raw)
        intent = result.get("intent", "general")
        valid_intents = {"social","library_info","search_academic","search_medical","general_recent","general"}
        if intent not in valid_intents:
            intent = "general"
        return {"intent": intent, "casual_answer": result.get("casual_answer", "")}
    except Exception as e:
        print(f"[LibBee classifier error] {e} | question: {question[:80]}")
        return {"intent": "general", "casual_answer": ""}


async def _libbee_casual_response(question: str, history: list, model: str, hint: str = "") -> str:
    """
    Generate a warm, in-character LibBee response for social/casual messages.
    Uses the classifier hint when available (saves a second LLM call).
    Falls back to a hardcoded response on any error.
    """
    # Use the classifier's casual_answer hint if it's good enough
    if hint and len(hint.strip()) > 25:
        return hint.strip()

    behavior = get_behavior_instructions()
    sys_prompt = (
        f"{behavior}\n\n"
        "You are LibBee, the Khalifa University Library AI Assistant. "
        "The user has sent a casual, social, or emotional message. "
        "Respond warmly and naturally in 1-3 sentences as a friendly, knowledgeable librarian. "
        "Always identify yourself as LibBee and offer library help. "
        "If the user seems frustrated or confused, be empathetic and reassuring. "
        "If the user seems happy or is complimenting you, be cheerful and grateful. "
        "Never say \'I don\'t have information\'. Never use bullet points or markdown. "
        "Match the user\'s energy β€” if casual, be casual; if distressed, be warm and calm."
    )
    msgs = [{"role": "system", "content": sys_prompt}]
    for m in history[-4:]:
        if m.get("role") in ("user", "assistant"):
            msgs.append({"role": m["role"], "content": (m.get("content") or "")[:200]})
    msgs.append({"role": "user", "content": question})

    use_claude = model == "claude" and os.environ.get("ANTHROPIC_API_KEY")
    try:
        if use_claude:
            from langchain_anthropic import ChatAnthropic
            llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0.6, max_tokens=200)
        else:
            llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.6, max_tokens=200)
        return llm.invoke(msgs).content.strip()
    except Exception:
        return (
            "I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant β€” "
            "always happy to help! What can I find for you today?"
        )


def _make_agent_response(answer, intent, tools_used, search_results, sources,
                          model, elapsed, question, natural_query=None,
                          database_query=None, original_question=None,
                          is_follow_up=False, source_mode="", ask_librarian=None):
    """
    Helper to build the standard /agent response dict.

    ask_librarian controls whether the frontend appends the
    "Ask a Librarian" footer block:
      None  β†’ frontend decides based on intent + tools_used (default behaviour)
      True  β†’ always show footer
      False β†’ never show footer (e.g. hours/campus answers are self-contained)
    """
    return {
        "answer": answer,
        "intent": intent,
        "tools_used": tools_used or [],
        "search_results": search_results or [],
        "sources": sources or [],
        "model_used": model,
        "response_time": round(elapsed, 2),
        "corrected_query": question,
        "natural_query": natural_query or question,
        "database_query": database_query or question,
        "original_question": original_question or question,
        "is_follow_up": is_follow_up,
        "source_mode": source_mode,
        "ask_librarian": ask_librarian,  # None | True | False
    }


# ---- Agent endpoint (Batch 3: tool-calling agent) ----
@app.post("/agent")
async def agent_query(req: AgentRequest):
    """
    LLM-first multi-tool agent.

    Execution order:
      Layer 0: Instant free handlers (pure greetings, exact social, staff, hours, KU redirect)
      Layer 1: LLM classifier β†’ one GPT-4o-mini call for ALL other messages
      Layer 2: Execute the classified intent (social/library/search/general)
    """
    start = time.time()
    question = req.question.strip()
    history = [{"role": m.role, "content": m.content} for m in req.history] if req.history else []
    use_claude = req.model == "claude" and bool(os.environ.get("ANTHROPIC_API_KEY"))
    q_clean = question.strip()

    # ══════════════════════════════════════════════════════════════════
    # LAYER 0 β€” INSTANT FREE HANDLERS (no LLM call, < 1ms each)
    # Only for responses that are 100% deterministic and zero-cost.
    # ══════════════════════════════════════════════════════════════════

    # 0a. Pure greetings (hi / hello / hey / good morning …)
    if PURE_GREETING_RE.match(q_clean):
        elapsed = time.time() - start
        return _make_agent_response(
            answer=(
                "Hi! I'm <strong>LibBee</strong>, the Khalifa University Library AI Assistant.<br><br>"
                "I can help you find articles and books, search databases, access full text, "
                "request Interlibrary Loan (ILL), and answer questions about library services and staff.<br><br>"
                "Are you looking for one of these? You can also type your question directly."
            ),
            intent="social_greeting", tools_used=[], search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
            is_follow_up=False, source_mode="social",
        )

    # 0b. Exact social phrases (who are you, how are you, thanks, bye …)
    fixed = _fixed_social_answer(q_clean)
    if fixed:
        elapsed = time.time() - start
        return _make_agent_response(
            answer=fixed, intent="social_greeting",
            tools_used=[], search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
            is_follow_up=False, source_mode="social",
        )

    # 0c. Staff name direct lookup (e.g. "nikesh", "jason fetty")
    staff_match = _match_staff_name(question)
    if staff_match:
        elapsed = time.time() - start
        src_title = staff_match.get("source_title", "")
        src_url   = staff_match.get("source", "")
        return _make_agent_response(
            answer=_staff_name_answer(staff_match, question),
            intent="library_info", tools_used=["staff_name_match"],
            search_results=[],
            sources=([{"title": src_title, "source": src_url}] if src_title or src_url else []),
            model=req.model, elapsed=elapsed, question=question,
            source_mode="staff_kb" if kb_staff_directory else "staff_directory",
        )

    # 0d. Staff role lookup (e.g. "who is the medical librarian")
    staff_role_match = _match_staff_role(question)
    if staff_role_match:
        elapsed = time.time() - start
        src_title = staff_role_match.get("source_title", "")
        src_url   = staff_role_match.get("source", "")
        return _make_agent_response(
            answer=_staff_role_answer(staff_role_match, question),
            intent="library_info", tools_used=["staff_role_match"],
            search_results=[],
            sources=([{"title": src_title, "source": src_url}] if src_title or src_url else []),
            model=req.model, elapsed=elapsed, question=question,
            source_mode="staff_kb" if kb_staff_directory else "staff_directory",
        )

    # 0e. Greeting menu follow-up (yes / sure / okay after LibBee intro)
    if _is_greeting_menu_followup(question, history):
        elapsed = time.time() - start
        return _make_agent_response(
            answer=_greeting_menu_clarify_answer(),
            intent="social_greeting", tools_used=[], search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
            is_follow_up=True, source_mode="social",
        )

    # 0f. Library hours question (fast-path β€” hardcoded hours + link, never web)
    if _looks_library_hours_question(question):
        elapsed = time.time() - start
        return _make_agent_response(
            answer=_hours_redirect_answer(),
            intent="library_info", tools_used=["hours_hardcoded"],
            search_results=[],
            sources=[{"title": "Library Hours", "source": LIBRARY_HOURS_URL}],
            model=req.model, elapsed=elapsed, question=question,
            ask_librarian=False,   # hours answer is self-contained
        )

    # 0f2. Campus / library location question (hardcoded β€” never from web)
    if _looks_campus_question(question):
        elapsed = time.time() - start
        return _make_agent_response(
            answer=_ku_campus_answer(),
            intent="library_info", tools_used=["campus_hardcoded"],
            search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
            ask_librarian=False,   # answer already includes contact info
        )

    # 0g. Non-library KU question (admissions, programs, fees …)
    if _looks_nonlibrary_ku_question(question):
        elapsed = time.time() - start
        return _make_agent_response(
            answer=_ku_general_redirect_answer(),
            intent="general", tools_used=["ku_general_redirect"],
            search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
        )

    # ══════════════════════════════════════════════════════════════════
    # LAYER 1 β€” LLM CLASSIFIER
    # One GPT-4o-mini call classifies ALL messages that reached here.
    # Cost: ~$0.000045 per call. At 250 questions/day β‰ˆ $1/month.
    # ══════════════════════════════════════════════════════════════════

    cls_result = await _llm_classify(question, history)
    intent     = cls_result.get("intent", "general")
    casual_hint = cls_result.get("casual_answer", "")

    # ══════════════════════════════════════════════════════════════════
    # LAYER 2 β€” EXECUTE CLASSIFIED INTENT
    # ══════════════════════════════════════════════════════════════════

    # ── Social / casual ──────────────────────────────────────────────
    if intent == "social":
        casual = await _libbee_casual_response(question, history, req.model, casual_hint)
        elapsed = time.time() - start
        return _make_agent_response(
            answer=casual, intent="social_greeting",
            tools_used=["libbee_casual"], search_results=[], sources=[],
            model=req.model, elapsed=elapsed, question=question,
            is_follow_up=False, source_mode="social",
        )

    # ── Library info β€” RAG pipeline ───────────────────────────────────
    if intent == "library_info":
        # Use _interpret_semantics to enrich the query with canonical library terms
        enriched_question = question
        try:
            interp = await _interpret_semantics(question, history)
            if interp.get("grounding_keys"):
                resolved = " ".join(
                    [question]
                    + interp.get("canonical_terms", [])
                    + [GROUNDED_LIBRARY_MAP.get(k, "")
                       for k in interp.get("grounding_keys", [])
                       if GROUNDED_LIBRARY_MAP.get(k)]
                )
                enriched_question = re.sub(r"\s+", " ", resolved).strip()
        except Exception:
            pass

        rag = await tool_library_info(enriched_question, history[-5:] if history else None, model=req.model)
        tools_used = ["get_library_info"]

        if rag.get("has_answer") and rag.get("answer"):
            # Good RAG answer β€” synthesise and return
            context_parts = [f"Library Knowledge Base:\n{rag['answer']}"]
            behavior = get_behavior_instructions()
            synthesis_prompt = (
                f"{behavior}\n\n"
                "You are the Khalifa University Library AI Assistant (Abu Dhabi, UAE). KU = Khalifa University.\n"
                "Answer in 2-4 sentences. Include URLs from the context when relevant.\n"
                "Answer ONLY from the provided context. Do not add information not present in the context.\n\n"
                f"Context:\n{chr(10).join(context_parts)}\n\n"
                f"Question: {question}\nAnswer:"
            )
            try:
                if use_claude:
                    from langchain_anthropic import ChatAnthropic
                    synth_llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0.2, max_tokens=500)
                else:
                    synth_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.2, max_tokens=500)
                answer = synth_llm.invoke(synthesis_prompt).content.strip()
            except Exception:
                answer = rag["answer"]
            elapsed = time.time() - start
            return _make_agent_response(
                answer=answer, intent="library_info", tools_used=tools_used,
                search_results=[], sources=rag.get("sources", []),
                model=req.model, elapsed=elapsed, question=question,
                ask_librarian=False,  # RAG answer from trusted KB β€” no footer needed
            )
        else:
            # ── RAG miss β€” three-tier fallback for library questions ──
            #
            # Tier 1: Strict KU-library-only LLM prompt (no hallucination risk β€”
            #         LLM is told to say it doesn't know rather than invent).
            # Tier 2: If tier 1 is vague/empty β†’ web search scoped to library.ku.ac.ae
            #         so all facts come from the real KU library website.
            # Tier 3: Always append "Ask a Librarian" + library homepage link.
            #
            # General web search (_answer_general) is NOT used here β€” that's only
            # for intent==general/general_recent where unrestricted search is correct.

            # ── Tier 1: Strict KU-only LLM ──
            ku_only_prompt = (
                "You are LibBee, the Khalifa University Library AI Assistant (Abu Dhabi, UAE). "
                "KU = Khalifa University.\n\n"
                "STRICT RULES:\n"
                "1. Answer ONLY using your knowledge of Khalifa University Library services, "
                "databases, policies, staff, and resources.\n"
                "2. Be concise (2-4 sentences). Include real KU library URLs when relevant "
                "(e.g. https://library.ku.ac.ae/AskUs, https://library.ku.ac.ae/ill/, "
                "https://library.ku.ac.ae/eresources, https://library.ku.ac.ae/oa/).\n"
                "3. If you are not confident about a specific detail (phone number, exact policy, "
                "specific database URL), do NOT invent it β€” instead say you are not certain and "
                "direct the user to Ask a Librarian or the library website.\n"
                "4. Never make up staff names, contact details, or database names.\n"
                "5. Do NOT use general web knowledge or facts unrelated to KU Library.\n\n"
                f"Question: {question}\nAnswer:"
            )
            tier1_answer = ""
            try:
                if use_claude:
                    from langchain_anthropic import ChatAnthropic
                    t1_llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0.1, max_tokens=400)
                else:
                    t1_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1, max_tokens=400)
                t1_response = t1_llm.invoke([
                    {"role": "system", "content": ku_only_prompt},
                    {"role": "user",   "content": question},
                ])
                tier1_answer = t1_response.content.strip()
            except Exception as t1_err:
                print(f"[LibBee tier1 LLM error] {t1_err}")

            # ── Tier 2: If tier 1 is vague, search library.ku.ac.ae ──
            # Detect vague answers: short, uncertain, or explicitly admitting no knowledge
            vague_phrases = [
                "i'm not sure", "i am not sure", "i don't have", "i do not have",
                "not certain", "cannot confirm", "not available", "unable to find",
                "please contact", "you may want to", "i would recommend checking",
                "i don't have specific", "i lack specific",
            ]
            is_vague = (
                not tier1_answer
                or len(tier1_answer.split()) < 15
                or any(p in tier1_answer.lower().replace("\u2019", "'") for p in vague_phrases)
            )

            tier2_answer = ""
            tier2_sources = []
            if is_vague:
                try:
                    import openai as _openai
                    _client = _openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
                    # Scope web search to KU library domain only
                    scoped_query = f"site:library.ku.ac.ae {question}"
                    _resp = _client.responses.create(
                        model="gpt-4o-mini",
                        tools=[{"type": "web_search_preview"}],
                        input=[{
                            "role": "system",
                            "content": (
                                "You are LibBee, the Khalifa University Library AI Assistant. "
                                "Search the KU library website (library.ku.ac.ae) only. "
                                "Answer in 2-4 sentences using only what you find on the KU library website. "
                                "Always include the source URL. "
                                "If nothing relevant is found on library.ku.ac.ae, say so briefly."
                            )
                        }, {"role": "user", "content": scoped_query}],
                    )
                    for block in _resp.output:
                        if hasattr(block, "content"):
                            for item in block.content:
                                if hasattr(item, "text"):
                                    tier2_answer += item.text
                                if hasattr(item, "annotations"):
                                    for ann in item.annotations:
                                        if hasattr(ann, "url") and hasattr(ann, "title"):
                                            if "library.ku.ac.ae" in getattr(ann, "url", ""):
                                                tier2_sources.append({"url": ann.url, "title": ann.title})
                    if not tier2_answer:
                        tier2_answer = getattr(_resp, "output_text", "") or ""
                    tier2_answer = tier2_answer.strip()
                except Exception as t2_err:
                    print(f"[LibBee tier2 web search error] {t2_err}")

            # ── Combine best answer β€” ask_librarian=True for all miss tiers ──
            # The frontend will render the Ask a Librarian block.
            # Answer strings are clean β€” no embedded HTML footer.
            if tier2_answer and len(tier2_answer.split()) >= 10:
                # Web search on library.ku.ac.ae found something useful
                final_answer = tier2_answer
                final_sources = tier2_sources
                final_tools = tools_used + ["ku_web_search"]
            elif tier1_answer and len(tier1_answer.split()) >= 10:
                # Tier 1 KU-only LLM gave a decent answer
                final_answer = tier1_answer
                final_sources = []
                final_tools = tools_used + ["ku_only_llm"]
            else:
                # Both failed β€” clean redirect only
                final_answer = (
                    "I don't have that specific information in my knowledge base right now. "
                    "The KU Library team will be able to help directly."
                )
                final_sources = []
                final_tools = tools_used + ["redirected"]

            elapsed = time.time() - start
            return _make_agent_response(
                answer=final_answer, intent="library_info",
                tools_used=final_tools,
                search_results=[], sources=final_sources,
                model=req.model, elapsed=elapsed, question=question,
                ask_librarian=True,   # Tier 1/2/3 β€” always show footer
            )

    # ── Academic / medical search ─────────────────────────────────────
    if intent in ("search_academic", "search_medical"):
        import asyncio as _asyncio
        search_plan = await _build_search_plan(question)
        corrected_query = search_plan["corrected"]
        natural_query  = search_plan["natural"]
        database_query = search_plan["database_query"] or search_plan["corrected"]
        year_from = search_plan.get("year_from") or None
        year_to = search_plan.get("year_to") or None
        peer_reviewed = bool(search_plan.get("peer_reviewed"))
        open_access = bool(search_plan.get("open_access"))

        tasks = [tool_search_primo(database_query, limit=5, peer_reviewed=peer_reviewed, open_access=open_access, year_from=year_from, year_to=year_to)]
        if intent == "search_medical":
            tasks.append(tool_search_pubmed(database_query, limit=3))
        else:
            tasks.append(tool_search_scholar(natural_query, limit=3))

        raw_results = await _asyncio.gather(*tasks, return_exceptions=True)
        combined = []
        tools_used = []
        for r in raw_results:
            if isinstance(r, dict) and r.get("results"):
                source_name = r.get("source", "unknown")
                tools_used.append(source_name)
                for item in r["results"]:
                    merged = dict(item)
                    merged.setdefault("_source", source_name)
                    combined.append(_normalize_result_links(merged))

        wants_single_article = bool(re.search(r"\b(one|single)\s+(peer.?reviewed\s+)?(article|paper|study)\b", question, re.IGNORECASE))
        wants_structured_summary = bool(re.search(r"\b(summariz(?:e|ing)|summaris(?:e|ing)|main research question|methodology|methods?|key findings|strengths?|limitations?|critical(?:ly)? evaluate|critique|contribution)\b", question, re.IGNORECASE))
        if wants_single_article or wants_structured_summary:
            preferred = [r for r in combined if r.get("_source") == "PRIMO"]
            secondary = [r for r in combined if r.get("_source") != "PRIMO"]
            combined = preferred + secondary

        rag = await tool_library_info(question, history[-3:] if history else None, model=req.model)
        tools_used.append("get_library_info")
        tools_used = list(dict.fromkeys(tools_used))

        behavior = get_behavior_instructions()
        if wants_single_article or wants_structured_summary:
            candidate = _choose_verified_article(combined, year_from=year_from, year_to=year_to)
            if candidate:
                answer = await _summarize_verified_article(question, candidate, behavior, use_claude)
            else:
                answer = (
                    "I couldn’t confidently retrieve one exact article matching your full request from the current results. "
                    "Please look into the available AI tools below to refine or expand the search."
                )
        else:
            context_parts = []
            if rag.get("answer"):
                context_parts.append(f"Library Knowledge Base:\n{rag['answer']}")
            if combined:
                top = combined[:5]
                res_lines = []
                for idx, r in enumerate(top, 1):
                    res_lines.append(
                        f"{idx}. Title: {r.get('title','')}\n"
                        f"   Authors: {r.get('creator','')}\n"
                        f"   Year: {r.get('date','')}\n"
                        f"   Source: {r.get('source','')}\n"
                        f"   Type: {r.get('type','')}\n"
                        f"   DOI: {r.get('doi','')}\n"
                        f"   PRIMO link: {r.get('primo_url','')}\n"
                        f"   Direct link: {r.get('link','')}\n"
                        f"   Abstract/Description: {r.get('description','')}"
                    )
                context_parts.append("Candidate Search Results:\n" + "\n\n".join(res_lines))
            context_parts.append(f"Natural query for AI tools: {natural_query}")
            context_parts.append(f"Database query for PRIMO/PubMed: {database_query}")
            synthesis_prompt = (
                f"{behavior}\n\n"
                "You are the KU Library AI Assistant. Be concise but helpful (4-7 sentences).\n"
                "Answer the user's search request directly, mention the search direction, and mention 1-3 strong retrieved results when present.\n"
                "Do not invent titles, links, or findings beyond the retrieved metadata/abstracts.\n"
                "Keep the answer in the chat rather than redirecting the user elsewhere.\n\n"
                f"Context:\n{chr(10).join(context_parts) if context_parts else 'No additional context.'}\n\n"
                f"Question: {question}\nAnswer:"
            )
            try:
                if use_claude:
                    from langchain_anthropic import ChatAnthropic
                    synth_llm = ChatAnthropic(model="claude-haiku-4-5-20251001", temperature=0.2, max_tokens=900)
                else:
                    synth_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.2, max_tokens=900)
                answer = synth_llm.invoke(synthesis_prompt).content.strip()
            except Exception as ex:
                answer = rag.get("answer", f"Error generating answer: {ex}")

        elapsed = time.time() - start
        return _make_agent_response(
            answer=answer, intent=intent, tools_used=tools_used,
            search_results=combined[:8], sources=rag.get("sources", []),
            model=req.model, elapsed=elapsed, question=question,
            natural_query=natural_query, database_query=database_query,
            original_question=question,
        )

    # ── General / general_recent β€” web search or plain LLM ───────────
    general = await _answer_general(question, history)
    gen_answer = general.get("answer", "").strip()
    # Guard: if general returned a "no info" string, replace with a helpful redirect
    no_info_phrases = [
        "i don't have", "i do not have", "no specific information",
        "not available in my", "unable to find", "cannot find",
    ]
    gen_lower = gen_answer.lower().replace("\u2019", "'")
    if not gen_answer or any(p in gen_lower for p in no_info_phrases):
        gen_answer = (
            "I'm not sure about that one. For library-specific questions, try "
            "<a href=\"https://library.ku.ac.ae/AskUs\" target=\"_blank\">Ask a Librarian</a>. "
            "For general knowledge questions, you could also try a web search."
        )
    elapsed = time.time() - start
    return _make_agent_response(
        answer=gen_answer, intent=intent,
        tools_used=["general_web" if intent == "general_recent" else "general"],
        search_results=[], sources=general.get("sources", []),
        model=req.model, elapsed=elapsed, question=question,
    )



# ---- Rebuild index (protected) ----
@app.post("/rebuild")
async def rebuild_index(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    global vectorstore
    try:
        import shutil, glob as _glob

        # Delete old FAISS index files so we rebuild from scratch
        if os.path.exists(FAISS_INDEX_PATH):
            shutil.rmtree(FAISS_INDEX_PATH)
            print(f"Deleted old FAISS index at {FAISS_INDEX_PATH}")

        # List all knowledge files found
        kb_files = _glob.glob(os.path.join(KNOWLEDGE_DIR, "*.txt"))
        print(f"Knowledge files found: {len(kb_files)}")
        for f in kb_files:
            print(f"  - {os.path.basename(f)} ({os.path.getsize(f)} bytes)")

        docs = load_documents()
        if not docs:
            return {"error": "No knowledge files found", "kb_dir": KNOWLEDGE_DIR, "files": []}

        # Force rebuild β€” ignore any cached index
        vectorstore = build_vectorstore(docs, force_rebuild=True)
        chunks = vectorstore.index.ntotal

        return {
            "status": "ok",
            "chunks": chunks,
            "documents": len(docs),
            "files": [os.path.basename(f) for f in kb_files],
            "kb_dir": KNOWLEDGE_DIR
        }
    except Exception as e:
        import traceback
        return {"error": str(e), "traceback": traceback.format_exc()}


# ===== ADMIN LOGIN =====
@app.get("/admin/login", response_class=HTMLResponse)
async def admin_login_page():
    return """<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>KU Library AI β€” Admin Login</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;display:flex;justify-content:center;align-items:center;min-height:100vh}
.login-box{background:#fff;border-radius:16px;padding:40px;width:360px;box-shadow:0 4px 24px rgba(0,0,0,.1);text-align:center}
h1{color:#003366;font-size:1.3rem;margin-bottom:6px}
.subtitle{color:#6b7280;font-size:.84rem;margin-bottom:24px}
input{width:100%;padding:12px 14px;border:1.5px solid #d1d5db;border-radius:10px;font-size:.92rem;margin-bottom:14px}
input:focus{outline:none;border-color:#003366}
.btn{width:100%;padding:12px;background:#003366;color:#fff;border:none;border-radius:10px;font-weight:700;font-size:.92rem;cursor:pointer}
.btn:hover{background:#004488}
.error{color:#dc2626;font-size:.82rem;margin-bottom:10px;display:none}
</style></head><body>
<div class="login-box">
  <h1>πŸ” Admin Login</h1>
  <div class="subtitle">KU Library AI Dashboard</div>
  <div class="error" id="err">Incorrect password. Try again.</div>
  <form onsubmit="return doLogin(event)">
    <input type="password" id="pw" placeholder="Enter admin password" autofocus>
    <button type="submit" class="btn">Login</button>
  </form>
</div>
<script>
async function doLogin(e){
  e.preventDefault();
  const pw=document.getElementById('pw').value;
  const r=await fetch('/admin/auth',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:pw})});
  if(r.ok){window.location.href='/admin';}
  else{document.getElementById('err').style.display='block';document.getElementById('pw').value='';document.getElementById('pw').focus();}
  return false;
}
</script></body></html>"""


@app.post("/admin/auth")
async def admin_auth(request: Request, response: Response):
    data = await request.json()
    if data.get("password") == ADMIN_PASSWORD:
        token = create_session()
        resp = Response(content=json.dumps({"status": "ok"}), media_type="application/json")
        resp.set_cookie("admin_session", token, httponly=True, max_age=86400, samesite="lax")
        return resp
    raise HTTPException(status_code=401, detail="Invalid password")


@app.get("/admin/logout")
async def admin_logout(request: Request):
    token = request.cookies.get("admin_session")
    if token and token in admin_sessions:
        del admin_sessions[token]
    resp = RedirectResponse(url="/admin/login")
    resp.delete_cookie("admin_session")
    return resp


# ===== ADMIN DASHBOARD (protected) =====
WORKER_URL = "https://steep-haze-e1f8.nikeshn.workers.dev"

@app.get("/admin", response_class=HTMLResponse)
async def admin_dashboard(request: Request):
    if not verify_session(request):
        return RedirectResponse(url="/admin/login")

    config = {}
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute("SELECT key, value FROM bot_config").fetchall()
    conn.close()
    for r in rows: config[r["key"]] = r["value"]

    def esc(s):
        return (s or "").replace("&","&amp;").replace("<","&lt;").replace(">","&gt;").replace('"',"&quot;")

    return f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>KU Library AI β€” Admin</title>
<style>
*{{box-sizing:border-box;margin:0;padding:0}}
body{{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;color:#1a1a2e;padding:20px;max-width:1200px;margin:0 auto}}
h1{{color:#003366;font-size:1.3rem;margin-bottom:4px}}
.sub{{color:#6b7280;font-size:.82rem;margin-bottom:14px}}
.tabs{{display:flex;gap:2px;border-bottom:2px solid #d1d5db;margin-bottom:14px}}
.tab{{padding:8px 16px;cursor:pointer;font-weight:600;font-size:.84rem;color:#6b7280;border:none;background:none;border-bottom:3px solid transparent;margin-bottom:-2px}}
.tab.active{{color:#003366;border-bottom-color:#003366}}
.tc{{display:none}}.tc.active{{display:block}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:16px}}
.stat{{background:#fff;border-radius:10px;padding:12px;border:1px solid #d1d5db;text-align:center}}
.stat .n{{font-size:1.6rem;font-weight:800;color:#003366}}.stat .l{{font-size:.76rem;color:#6b7280}}
.card{{background:#fff;border-radius:10px;padding:14px;border:1px solid #d1d5db;margin-bottom:12px}}
.card h2{{font-size:.9rem;color:#003366;margin-bottom:8px}}
table{{width:100%;border-collapse:collapse;font-size:.78rem}}
th{{background:#003366;color:#fff;padding:6px 8px;text-align:left}}
td{{padding:5px 8px;border-bottom:1px solid #e5e7eb}}
tr:hover{{background:#f9fafb}}
.badge{{padding:2px 7px;border-radius:8px;font-size:.68rem;font-weight:600}}
.err{{color:#dc2626;font-size:.72rem}}
canvas{{max-height:180px}}
.fg{{margin-bottom:12px}}
.fg label{{display:block;font-weight:700;font-size:.82rem;color:#003366;margin-bottom:3px}}
.fg .h{{font-size:.72rem;color:#6b7280;margin-bottom:3px}}
textarea,input[type=text],select{{width:100%;padding:9px;border:1.5px solid #d1d5db;border-radius:8px;font-family:inherit;font-size:.82rem;resize:vertical}}
textarea:focus,input:focus,select:focus{{outline:none;border-color:#003366}}
.btn{{padding:9px 20px;border:none;border-radius:8px;font-weight:700;cursor:pointer;font-size:.84rem}}
.bp{{background:#003366;color:#fff}}.bp:hover{{background:#004488}}
.bg{{background:#059669;color:#fff}}
.br{{background:#dc2626;color:#fff}}
.toggle{{display:flex;align-items:center;gap:8px}}
.toggle input{{width:18px;height:18px;accent-color:#003366}}
.st{{padding:8px 14px;border-radius:8px;font-size:.8rem;font-weight:600;display:none;margin-top:8px}}
.st.ok{{background:#d1fae5;color:#065f46;display:block}}
.st.er{{background:#fecaca;color:#991b1b;display:block}}
.two{{display:grid;grid-template-columns:1fr 1fr;gap:12px}}
@media(max-width:768px){{.two{{grid-template-columns:1fr}}}}
#loading{{text-align:center;padding:40px;color:#6b7280}}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
</head><body>
<h1>πŸ“Š KU Library AI β€” Admin <span style="float:right;display:flex;gap:6px;align-items:center"><button onclick="location.reload()" class="btn bp" style="padding:5px 12px;font-size:.76rem">πŸ”„ Refresh</button><a href="/admin/logout" style="font-size:.76rem;color:#dc2626;text-decoration:none;padding:5px 12px;border:1.5px solid #dc2626;border-radius:8px;font-weight:600">πŸ”’ Logout</a></span></h1>
<div class="sub">Khalifa University Library AI Agent</div>

<div class="tabs">
  <div class="tab active" onclick="st(this,'analytics')">πŸ“ˆ Analytics</div>
  <div class="tab" onclick="st(this,'behavior')">πŸ€– Bot Behavior</div>
  <div class="tab" onclick="st(this,'queries')">πŸ“‹ Query Log</div>
  <div class="tab" onclick="st(this,'system')">βš™οΈ System</div>
</div>

<div class="tc active" id="t-analytics"><div id="loading">Loading analytics from Cloudflare D1…</div></div>

<div class="tc" id="t-behavior">
<div class="card"><h2>πŸ€– Bot Behavior</h2><p style="font-size:.8rem;color:#6b7280;margin-bottom:12px">Changes apply immediately.</p>
<div class="fg"><label>Welcome Message</label><div class="h">First message users see.</div><textarea id="c-welcome_message" rows="3">{esc(config.get('welcome_message',''))}</textarea></div>
<div class="fg"><label>Bot Personality / System Prompt</label><div class="h">Core instructions for every LLM call.</div><textarea id="c-bot_personality" rows="4">{esc(config.get('bot_personality',''))}</textarea></div>
<div class="fg"><label>Custom Instructions</label><div class="h">Extra guidance, e.g. "During Ramadan, mention reduced hours."</div><textarea id="c-custom_instructions" rows="3">{esc(config.get('custom_instructions',''))}</textarea></div>
<div class="fg"><label>πŸ“’ Announcement Banner</label><div class="h">Shows at top of chat. Leave empty to hide.</div><textarea id="c-announcement" rows="2">{esc(config.get('announcement',''))}</textarea></div>
<div class="two"><div class="fg"><label>Default Model</label><select id="c-default_model"><option value="gpt" {'selected' if config.get('default_model')=='gpt' else ''}>ChatGPT</option><option value="claude" {'selected' if config.get('default_model')=='claude' else ''}>Claude</option></select></div>
<div class="fg"><label>Max Results</label><select id="c-max_results"><option value="3" {'selected' if config.get('max_results')=='3' else ''}>3</option><option value="5" {'selected' if config.get('max_results')=='5' else ''}>5</option><option value="10" {'selected' if config.get('max_results')=='10' else ''}>10</option></select></div></div>
<div id="sv" class="st"></div><button class="btn bp" onclick="saveConfig()">πŸ’Ύ Save</button>
</div></div>

<div class="tc" id="t-queries"><div id="recent-loading">Loading query log…</div></div>

<div class="tc" id="t-system">
<div class="card"><h2>βš™οΈ Controls</h2>
<div class="fg"><div class="toggle"><input type="checkbox" id="c-maintenance_mode" {'checked' if config.get('maintenance_mode')=='true' else ''}><label><strong>Maintenance Mode</strong></label></div></div>
<div class="fg"><label>Maintenance Message</label><textarea id="c-maintenance_message" rows="2">{esc(config.get('maintenance_message',''))}</textarea></div>
<div style="display:flex;gap:8px;margin-top:10px;flex-wrap:wrap">
  <button class="btn bp" onclick="saveConfig()">πŸ’Ύ Save Config</button>
  <button class="btn bg" onclick="rebuildIdx()">πŸ”„ Rebuild RAG</button>
  <button class="btn" style="background:#dc2626;color:#fff;border:none;padding:8px 14px;border-radius:8px;font-weight:600;cursor:pointer" onclick="restartSpace()">♻️ Restart Space</button>
</div>
<div id="sys" class="st"></div>
</div>

<div class="card"><h2>🟒 Live Status</h2>
<div id="status-panel" style="font-size:.85rem">Loading status…</div>
</div>

<div class="card"><h2>System Info</h2><table>
<tr><td><strong>Knowledge Files</strong></td><td>{len(glob.glob(os.path.join(KNOWLEDGE_DIR,'*.txt')))} files</td></tr>
<tr><td><strong>OpenAI API</strong></td><td>{'βœ… Configured' if os.environ.get('OPENAI_API_KEY') else '❌ Missing'}</td></tr>
<tr><td><strong>Anthropic API</strong></td><td>{'βœ… Configured' if os.environ.get('ANTHROPIC_API_KEY') else '❌ Missing'}</td></tr>
<tr><td><strong>PRIMO API</strong></td><td>{'βœ… Configured' if os.environ.get('PRIMO_API_KEY') else '❌ Missing'}</td></tr>
<tr><td><strong>Admin Password</strong></td><td>{'βœ… Set' if os.environ.get('ADMIN_PASSWORD') else '❌ Missing'}</td></tr>
<tr><td><strong>Cloudflare D1</strong></td><td>Connected via Worker</td></tr>
</table></div></div>

<script>
const W='{WORKER_URL}';
function st(el,t){{document.querySelectorAll('.tab').forEach(e=>e.classList.remove('active'));document.querySelectorAll('.tc').forEach(e=>e.classList.remove('active'));el.classList.add('active');document.getElementById('t-'+t).classList.add('active');}}

// Fetch analytics from Cloudflare D1
fetch(W+'/analytics').then(r=>r.json()).then(d=>{{
  const el=document.getElementById('t-analytics');
  el.innerHTML=`
  <div class="grid">
    <div class="stat"><div class="n">${{d.total}}</div><div class="l">Total</div></div>
    <div class="stat"><div class="n">${{d.today}}</div><div class="l">Today</div></div>
    <div class="stat"><div class="n">${{d.week}}</div><div class="l">This Week</div></div>
    <div class="stat"><div class="n">${{(d.avg_time||0).toFixed(1)}}s</div><div class="l">Avg Time</div></div>
    <div class="stat"><div class="n">${{d.errors}}</div><div class="l">Errors</div></div>
  </div>
  <div class="two">
    <div class="card"><h2>Tool Usage</h2><table><tr><th>Tool</th><th>Count</th></tr>${{d.tools.map(t=>`<tr><td>${{t.tool_used}}</td><td>${{t.c}}</td></tr>`).join('')}}</table></div>
    <div class="card"><h2>Model Usage</h2><table><tr><th>Model</th><th>Count</th></tr>${{d.models.map(m=>`<tr><td>${{m.model}}</td><td>${{m.c}}</td></tr>`).join('')}}</table></div>
  </div>
  <div class="two">
    <div class="card"><h2>Hourly</h2><canvas id="hc"></canvas></div>
    <div class="card"><h2>Daily (14d)</h2><canvas id="dc"></canvas></div>
  </div>
  <div class="card"><h2>Popular (Top 20)</h2><table><tr><th>Question</th><th>Count</th></tr>${{d.popular.map(p=>`<tr><td>${{(p.question||'').substring(0,70)}}</td><td>${{p.c}}</td></tr>`).join('')}}</table></div>`;
  if(d.hourly.length)new Chart(document.getElementById('hc'),{{type:'bar',data:{{labels:d.hourly.map(h=>h.hour+':00'),datasets:[{{label:'Q',data:d.hourly.map(h=>h.c),backgroundColor:'#003366'}}]}},options:{{responsive:true,plugins:{{legend:{{display:false}}}}}}}});
  if(d.daily.length)new Chart(document.getElementById('dc'),{{type:'line',data:{{labels:d.daily.map(x=>(x.day||'').slice(5)),datasets:[{{label:'Q',data:d.daily.map(x=>x.c),borderColor:'#003366',backgroundColor:'rgba(0,51,102,0.1)',fill:true,tension:.3}}]}},options:{{responsive:true,plugins:{{legend:{{display:false}}}}}}}});
}}).catch(e=>{{document.getElementById('t-analytics').innerHTML='<div class="card" style="color:#dc2626">Failed to load analytics: '+e.message+'<br>Make sure D1 is initialized: <a href="'+W+'/analytics/init" target="_blank">Click here to init DB</a></div>';}});


// Fetch local feedback stats
fetch('/admin/feedback-stats').then(r=>r.json()).then(d=>{{
  const host=document.getElementById('t-analytics');
  if(!host) return;
  const s=(d.summary||[]).reduce((a,x)=>{{a[x.feedback]=x.c;return a;}},{{}});
  const card=document.createElement('div');
  card.className='card';
  card.innerHTML=`<h2>πŸ‘ User Feedback</h2>
    <div class="grid" style="margin-bottom:10px">
      <div class="stat"><div class="n">${{s.up||0}}</div><div class="l">Helpful</div></div>
      <div class="stat"><div class="n">${{s.down||0}}</div><div class="l">Not Helpful</div></div>
    </div>
    <div class="two">
      <div><h2 style="margin-bottom:6px">Recent feedback</h2><table><tr><th>Time</th><th>Question</th><th>Feedback</th></tr>${{(d.recent||[]).map(r=>`<tr><td>${{(r.timestamp||'').substring(0,19)}}</td><td>${{(r.question||'').substring(0,60)}}</td><td>${{r.feedback==='up'?'πŸ‘':'πŸ‘Ž'}}</td></tr>`).join('')}}</table></div>
      <div><h2 style="margin-bottom:6px">Top weak questions</h2><table><tr><th>Question</th><th>Count</th></tr>${{(d.weak||[]).map(r=>`<tr><td>${{(r.question||'').substring(0,70)}}</td><td>${{r.c}}</td></tr>`).join('')}}</table></div>
    </div>`;
  host.appendChild(card);
}}).catch(()=>{{}});

// Fetch recent queries
fetch(W+'/analytics/recent').then(r=>r.json()).then(d=>{{
  const el=document.getElementById('t-queries');
  el.innerHTML='<div class="card"><h2>Recent (50)</h2><table><tr><th>Time</th><th>Question</th><th>Tool</th><th>Model</th><th>Results</th><th>Status</th></tr>'+(d.results||[]).map(r=>`<tr><td>${{(r.timestamp||'').substring(0,19)}}</td><td title="${{r.question}}">${{(r.question||'').substring(0,55)}}</td><td><span class="badge" style="background:#e0e7ff">${{r.tool_used}}</span></td><td>${{r.model}}</td><td>${{r.result_count}}</td><td class="err">${{r.error||'βœ“'}}</td></tr>`).join('')+'</table></div>';
}}).catch(e=>{{document.getElementById('t-queries').innerHTML='<div class="card" style="color:#dc2626">'+e.message+'</div>';}});

async function saveConfig(){{
  const keys=['welcome_message','bot_personality','custom_instructions','announcement','default_model','max_results','maintenance_message'];
  const data={{}};keys.forEach(k=>{{data[k]=document.getElementById('c-'+k).value;}});
  data.maintenance_mode=document.getElementById('c-maintenance_mode').checked?'true':'false';
  const r=await fetch('/admin/config',{{method:'POST',headers:{{'Content-Type':'application/json'}},body:JSON.stringify(data)}});
  const res=await r.json();
  const s=document.getElementById('sv')||document.getElementById('sys');
  s.className=res.status==='ok'?'st ok':'st er'; s.textContent=res.status==='ok'?'βœ… Saved!':'❌ Error';
  setTimeout(()=>s.style.display='none',3000);
}}
async function rebuildIdx(){{
  const s=document.getElementById('sys');s.className='st ok';s.textContent='πŸ”„ Rebuilding...';s.style.display='block';
  const r=await fetch('/rebuild',{{method:'POST'}});const res=await r.json();
  s.textContent=res.status==='ok'?'βœ… Rebuilt: '+res.chunks+' chunks from '+res.documents+' files':'❌ '+(res.error||JSON.stringify(res));
  s.className=res.status==='ok'?'st ok':'st er';
  loadStatus(); // refresh status after rebuild
}}

async function restartSpace(){{
  if(!confirm('Restart the HF Space? The service will be unavailable for ~30-60 seconds.')) return;
  const s=document.getElementById('sys');s.className='st ok';s.textContent='♻️ Restarting...';s.style.display='block';
  try {{
    await fetch('/restart',{{method:'POST'}});
    s.textContent='♻️ Space restarting β€” please wait 30-60 seconds then refresh this page.';
    // Poll until back online
    let attempts=0;
    const poll=setInterval(async()=>{{
      attempts++;
      try{{
        const r=await fetch('/status');
        if(r.ok){{clearInterval(poll);s.textContent='βœ… Space is back online!';s.className='st ok';loadStatus();}}
      }}catch(e){{
        s.textContent=`♻️ Still restarting... (${{attempts*5}}s elapsed)`;
      }}
      if(attempts>24){{clearInterval(poll);s.textContent='⚠️ Restart taking longer than expected. Try refreshing the page.';}}
    }},5000);
  }}catch(e){{s.textContent='❌ '+e.message;s.className='st er';}}
}}

async function loadStatus(){{
  const el=document.getElementById('status-panel');
  if(!el) return;
  try{{
    const r=await fetch('/status');
    if(!r.ok){{el.innerHTML='<span style="color:#dc2626">❌ HF Space not responding</span>';return;}}
    const d=await r.json();
    const uptimeMin=Math.round((d.uptime_secs||0)/60);
    const memColor=d.mem_pct>85?'#dc2626':d.mem_pct>70?'#d97706':'#16a34a';
    el.innerHTML=`
      <table style="width:100%">
        <tr><td><strong>Space Status</strong></td><td><span style="color:#16a34a;font-weight:700">βœ… Running</span></td></tr>
        <tr><td><strong>Vectorstore</strong></td><td>${{d.vectorstore==='ready'?'βœ… Ready ('+d.chunks+' chunks, '+d.kb_files+' files)':'❌ Not initialized'}}</td></tr>
        <tr><td><strong>OpenAI API</strong></td><td>${{d.openai?'βœ… Configured':'❌ Missing'}}</td></tr>
        <tr><td><strong>Anthropic API</strong></td><td>${{d.anthropic?'βœ… Configured':'❌ Missing'}}</td></tr>
        <tr><td><strong>PRIMO API</strong></td><td>${{d.primo?'βœ… Configured':'❌ Missing'}}</td></tr>
        <tr><td><strong>Memory Usage</strong></td><td><span style="color:${{memColor}};font-weight:700">${{d.mem_pct}}%</span> (${{d.mem_used_mb}}MB / ${{d.mem_total_mb}}MB)</td></tr>
        <tr><td><strong>Uptime</strong></td><td>${{uptimeMin < 60 ? uptimeMin+'m' : Math.floor(uptimeMin/60)+'h '+uptimeMin%60+'m'}}</td></tr>
      </table>
      <div style="margin-top:8px;font-size:.74rem;color:#6b7280">Last checked: ${{new Date().toLocaleTimeString()}}</div>`;
  }}catch(e){{
    el.innerHTML='<span style="color:#dc2626">❌ Cannot reach HF Space: '+e.message+'</span>';
  }}
}}

// Load status on page load and every 30 seconds
loadStatus();
setInterval(loadStatus, 30000);
</script>
</body></html>"""


# ---- Restart Space endpoint ----
@app.post("/restart")
async def restart_space(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    import threading
    def do_restart():
        import time as t
        t.sleep(1)
        os.kill(os.getpid(), 9)  # Force restart β€” HF Space will auto-restart
    threading.Thread(target=do_restart, daemon=True).start()
    return {"status": "restarting", "message": "Space is restarting. Please wait 30-60 seconds."}


# ---- Status endpoint (no auth needed β€” for frontend health checks) ----
@app.get("/status")
async def get_status():
    # Read container-level memory from /sys/fs/cgroup (accurate for HF Spaces)
    # psutil reads the host machine memory which is misleading on shared containers
    try:
        # cgroup v2 (HF Spaces uses this)
        with open('/sys/fs/cgroup/memory.current') as f:
            mem_used_bytes = int(f.read().strip())
        with open('/sys/fs/cgroup/memory.max') as f:
            val = f.read().strip()
            mem_total_bytes = int(val) if val != 'max' else 16 * 1024**3  # 16GB default
        mem_used_mb = round(mem_used_bytes / 1024 / 1024)
        mem_total_mb = round(mem_total_bytes / 1024 / 1024)
        mem_pct = round(mem_used_bytes / mem_total_bytes * 100)
    except:
        # Fallback: try cgroup v1
        try:
            with open('/sys/fs/cgroup/memory/memory.usage_in_bytes') as f:
                mem_used_bytes = int(f.read().strip())
            with open('/sys/fs/cgroup/memory/memory.limit_in_bytes') as f:
                mem_total_bytes = int(f.read().strip())
            mem_used_mb = round(mem_used_bytes / 1024 / 1024)
            mem_total_mb = round(mem_total_bytes / 1024 / 1024)
            mem_pct = round(mem_used_bytes / mem_total_bytes * 100)
        except:
            mem_used_mb = mem_total_mb = mem_pct = 0

    kb_files = glob.glob(os.path.join(KNOWLEDGE_DIR, "*.txt"))
    chunks = vectorstore.index.ntotal if vectorstore else 0

    return {
        "status": "ok",
        "vectorstore": "ready" if vectorstore else "not_initialized",
        "chunks": chunks,
        "kb_files": len(kb_files),
        "openai": bool(os.environ.get("OPENAI_API_KEY")),
        "anthropic": bool(os.environ.get("ANTHROPIC_API_KEY")),
        "primo": bool(os.environ.get("PRIMO_API_KEY")),
        "mem_used_mb": mem_used_mb,
        "mem_total_mb": mem_total_mb,
        "mem_pct": mem_pct,
        "uptime_secs": round(time.time() - START_TIME),
    }


# ---- Admin stats from D1 (kept for API compatibility) ----
@app.get("/admin/stats")
async def admin_stats(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    # Stats now come from Cloudflare D1 via /analytics endpoint
    return {"message": "Use Cloudflare Worker /analytics endpoint for D1 data"}
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    total = conn.execute("SELECT COUNT(*) as c FROM queries").fetchone()["c"]
    today = conn.execute("SELECT COUNT(*) as c FROM queries WHERE timestamp >= date('now')").fetchone()["c"]
    tools = {r["tool_used"]: r["c"] for r in conn.execute("SELECT tool_used, COUNT(*) as c FROM queries GROUP BY tool_used").fetchall()}
    models = {r["model"]: r["c"] for r in conn.execute("SELECT model, COUNT(*) as c FROM queries GROUP BY model").fetchall()}
    conn.close()
    return {"total": total, "today": today, "tools": tools, "models": models}


# ---- Admin Config GET/POST (protected) ----
@app.get("/admin/config")
async def admin_get_config(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    rows = conn.execute("SELECT key, value, updated_at FROM bot_config").fetchall()
    conn.close()
    return {r["key"]: {"value": r["value"], "updated_at": r["updated_at"]} for r in rows}


@app.post("/admin/config")
async def admin_set_config(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    data = await request.json()
    settings = data.get("settings", data) if isinstance(data, dict) else data
    for key, value in settings.items():
        set_config(key, str(value))
    return {"status": "ok", "updated": list(settings.keys())}



class FeedbackRequest(BaseModel):
    question: str = ""
    feedback: str
    answer_excerpt: str = ""
    intent: str = ""

@app.post("/feedback")
async def feedback_submit(req: FeedbackRequest):
    try:
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO feedback (timestamp, question, feedback, answer_excerpt, intent) VALUES (?,?,?,?,?)",
            (datetime.utcnow().isoformat(), req.question or "", req.feedback or "", (req.answer_excerpt or "")[:500], req.intent or "")
        )
        conn.commit()
        conn.close()
        return {"status": "ok"}
    except Exception as e:
        return {"status": "error", "error": str(e)}

@app.get("/admin/feedback-stats")
async def admin_feedback_stats(request: Request):
    if not verify_session(request):
        raise HTTPException(status_code=401, detail="Not authenticated")
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    summary = [dict(r) for r in conn.execute("SELECT feedback, COUNT(*) as c FROM feedback GROUP BY feedback ORDER BY c DESC").fetchall()]
    recent = [dict(r) for r in conn.execute("SELECT timestamp, question, feedback, intent FROM feedback ORDER BY id DESC LIMIT 30").fetchall()]
    weak = [dict(r) for r in conn.execute("SELECT question, COUNT(*) as c FROM feedback WHERE feedback='down' AND question != '' GROUP BY question ORDER BY c DESC LIMIT 10").fetchall()]
    conn.close()
    return {"summary": summary, "recent": recent, "weak": weak}

# ---- Public config (for frontend) ----
@app.get("/config")
async def public_config():
    return {
        "welcome_message": get_config("welcome_message"),
        "bot_personality": get_config("bot_personality"),
        "custom_instructions": get_config("custom_instructions"),
        "announcement": get_config("announcement"),
        "default_model": get_config("default_model", "gpt"),
        "maintenance_mode": get_config("maintenance_mode", "false"),
        "maintenance_message": get_config("maintenance_message"),
        "max_results": get_config("max_results", "5"),
    }


# ---- Clear logs ----
@app.post("/admin/clear-logs")
async def clear_logs():
    conn = sqlite3.connect(DB_PATH)
    conn.execute("DELETE FROM queries")
    conn.commit()
    conn.close()
    return {"status": "ok", "message": "All logs cleared"}