Spaces:
Sleeping

File size: 119,067 Bytes
b8f40ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
AI Intelligence Query Engine (query_engine.py)
Natural-language query interface over Curium Lead Intelligence data.
Uses Claude with tool-use for agentic lookups against the leads database.
"""

import os
import json
import sqlite3
from pathlib import Path
from dotenv import load_dotenv
from anthropic import Anthropic

try:
    from rapidfuzz import fuzz
    FUZZY_AVAILABLE = True
except ImportError:
    FUZZY_AVAILABLE = False

# Load environment variables
env_path = Path(__file__).parent / '.env'
load_dotenv(dotenv_path=env_path, override=True)

DATABASE = "leads.db"

# Anthropic client singleton
_client = None


def get_client():
    """Get or create the Anthropic client."""
    global _client
    if _client is None:
        api_key = os.environ.get("ANTHROPIC_API_KEY")
        if not api_key:
            raise ValueError("ANTHROPIC_API_KEY environment variable is not set.")
        _client = Anthropic(api_key=api_key)
    return _client


def get_connection():
    return sqlite3.connect(DATABASE)


# =============================================================================
# CONTEXT SUMMARY β€” injected into system prompt so AI knows the data shape
# =============================================================================

def build_context_summary() -> str:
    """Build a text summary of all data for the AI system prompt."""
    conn = get_connection()
    cursor = conn.cursor()
    parts = []

    # Company stats
    cursor.execute("SELECT COUNT(*) FROM companies")
    total = cursor.fetchone()[0]
    cursor.execute("SELECT COUNT(*) FROM companies WHERE overall_score >= 50")
    hot = cursor.fetchone()[0]
    cursor.execute("SELECT COUNT(*) FROM companies WHERE network_status != 'Cold'")
    networked = cursor.fetchone()[0]

    # Signal counts
    signal_counts = {}
    for table, label in [
        ("signals_jobs", "job signals"),
        ("signals_news", "news signals"),
        ("signals_tenders", "tenders"),
        ("signals_annual_reports", "annual reports"),

        ("signals_sentiment", "sentiment signals"),
        ("signals_pe_deals", "PE/M&A deals"),
        ("signals_linkedin_intel", "LinkedIn intel contacts"),
    ]:
        try:
            cursor.execute(f"SELECT COUNT(*) FROM {table}")
            signal_counts[label] = cursor.fetchone()[0]
        except Exception:
            signal_counts[label] = 0

    parts.append(f"DATABASE OVERVIEW: {total} companies tracked, {hot} hot (score>=50), {networked} with network connections.")
    signal_line = ", ".join(f"{v} {k}" for k, v in signal_counts.items() if v > 0)
    if signal_line:
        parts.append(f"SIGNALS: {signal_line}.")

    # All companies with key fields
    cursor.execute("""
        SELECT name, overall_score, sector, network_status, td_score, cc_score, signal_summary
        FROM companies ORDER BY overall_score DESC
    """)
    rows = cursor.fetchall()
    if rows:
        parts.append(f"\nALL {len(rows)} COMPANIES (name | score | sector | network | TD | CC | signals):")
        for r in rows:
            name, score, sector, net, td, cc, sigs = r
            sector_str = sector or "Unknown"
            sigs_str = sigs[:80] if sigs else "none"
            parts.append(f"  {name} | {score} | {sector_str} | {net or 'Cold'} | TD:{td or 0} CC:{cc or 0} | {sigs_str}")

    # Team members and connection counts
    try:
        cursor.execute("""
            SELECT name, connections_count, movers_count FROM team_members ORDER BY connections_count DESC
        """)
        team = cursor.fetchall()
        if team:
            parts.append(f"\nTEAM MEMBERS ({len(team)}):")
            for name, conns, movers in team:
                parts.append(f"  {name}: {conns or 0} connections, {movers or 0} movers")
    except Exception:
        pass

    # Network stats
    try:
        cursor.execute("SELECT COUNT(*) FROM network_graph")
        net_total = cursor.fetchone()[0]
        cursor.execute("SELECT COUNT(DISTINCT company) FROM network_graph")
        net_companies = cursor.fetchone()[0]
        parts.append(f"\nNETWORK: {net_total} total connections across {net_companies} companies (vs {total} tracked β€” massive untapped potential).")
    except Exception:
        pass

    # Pre-computed strategic intelligence
    try:
        # Signal convergence count
        cursor.execute("SELECT c.id FROM companies c")
        all_ids = [r[0] for r in cursor.fetchall()]
        convergence_count = 0
        for cid in all_ids:
            signal_count = 0
            for tbl in ["signals_jobs", "signals_news", "signals_tenders", "signals_pe_deals",
                        "signals_sentiment", "signals_annual_reports", "signals_linkedin_intel"]:
                try:
                    cursor.execute(f"SELECT 1 FROM {tbl} WHERE company_id = ? LIMIT 1", (cid,))
                    if cursor.fetchone():
                        signal_count += 1
                except Exception:
                    pass
            if signal_count >= 3:
                convergence_count += 1

        # Warm+hot count
        cursor.execute("SELECT COUNT(*) FROM companies WHERE overall_score >= 50 AND network_status != 'Cold' AND network_status IS NOT NULL")
        warm_hot_count = cursor.fetchone()[0]

        # Cold hot leads
        cursor.execute("SELECT COUNT(*) FROM companies WHERE overall_score >= 50 AND (network_status = 'Cold' OR network_status IS NULL)")
        cold_hot_count = cursor.fetchone()[0]

        # Sleeping giants top 5 β€” with activity signals
        cursor.execute("""
            SELECT ng.company_normalized, COUNT(*) as total, SUM(ng.is_senior) as seniors,
                   SUM(CASE WHEN ng.date_connected >= date('now', '-6 months') THEN 1 ELSE 0 END) as recent
            FROM network_graph ng
            LEFT JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
            WHERE c.id IS NULL AND ng.company_normalized IS NOT NULL AND ng.company_normalized != '' AND LOWER(ng.company_normalized) NOT IN ('curium', 'self employed', 'freelance', 'retired', 'unemployed', '') AND LOWER(ng.company_normalized) NOT LIKE '%curium solutions%'
            GROUP BY ng.company_normalized
            HAVING total >= 3 AND (recent > 0 OR seniors >= 3)
            ORDER BY recent DESC, seniors DESC, total DESC
            LIMIT 5
        """)
        giants = cursor.fetchall()

        parts.append(f"\nSTRATEGIC OVERVIEW:")
        parts.append(f"  Signal convergence: {convergence_count} companies have 3+ converging signal types")
        parts.append(f"  Warm+Hot: {warm_hot_count} hot companies (score 50+) have warm network routes")
        parts.append(f"  Coverage gaps: {cold_hot_count} hot companies have ZERO network connections")
        if giants:
            giant_strs = [f"{g[0]} ({g[3] or 0} recent conns, {g[2] or 0} senior)" for g in giants]
            parts.append(f"  Top sleeping giants (untracked but showing activity): {'; '.join(giant_strs)}")
    except Exception:
        pass

    conn.close()
    return "\n".join(parts)


# =============================================================================
# TOOL DEFINITIONS β€” passed to Claude via tools= parameter
# =============================================================================

TOOLS = [
    {
        "name": "search_companies",
        "description": "Search and filter companies in the database. Use this to find companies matching criteria like score range, sector, signal type, service line, or name pattern.",
        "input_schema": {
            "type": "object",
            "properties": {
                "name_pattern": {
                    "type": "string",
                    "description": "Company name to search for (partial match, case-insensitive)"
                },
                "min_score": {
                    "type": "integer",
                    "description": "Minimum overall score (0-100)"
                },
                "max_score": {
                    "type": "integer",
                    "description": "Maximum overall score (0-100)"
                },
                "sector": {
                    "type": "string",
                    "description": "Sector to filter by (partial match)"
                },
                "signal_type": {
                    "type": "string",
                    "description": "Filter by signal type in signal_summary (e.g. 'pe', 'news', 'tender', 'job', 'sentiment', 'linkedin')"
                },
                "network_status": {
                    "type": "string",
                    "description": "Filter by network status: 'Cold', 'Direct', 'Senior', 'Company'"
                },
                "service_line": {
                    "type": "string",
                    "description": "Filter by service line: 'td' for Transformation Delivery (td_score > 0), 'cc' for Culture & Capability (cc_score > 0)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results to return (default 20)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_company_detail",
        "description": "Get the complete dossier for a specific company including all signals (jobs, news, tenders, network connections, sentiment, PE deals, LinkedIn intel). Use when you need deep detail on one company.",
        "input_schema": {
            "type": "object",
            "properties": {
                "company_name": {
                    "type": "string",
                    "description": "Company name (fuzzy matched)"
                }
            },
            "required": ["company_name"]
        }
    },
    {
        "name": "find_connections",
        "description": "Find team members who have connections at a specific company. Returns colleague names, contact names, positions, and connection details.",
        "input_schema": {
            "type": "object",
            "properties": {
                "company_name": {
                    "type": "string",
                    "description": "Company name to find connections at (fuzzy matched)"
                }
            },
            "required": ["company_name"]
        }
    },
    {
        "name": "find_person",
        "description": "Search for a person by name across the entire network (both network_graph connections and LinkedIn intel contacts). Use to find anyone in our data.",
        "input_schema": {
            "type": "object",
            "properties": {
                "person_name": {
                    "type": "string",
                    "description": "Person name to search for (partial match)"
                }
            },
            "required": ["person_name"]
        }
    },
    {
        "name": "get_movers",
        "description": "Find contacts who recently changed companies. These are warm leads β€” someone our team knows who moved to a new organisation.",
        "input_schema": {
            "type": "object",
            "properties": {
                "colleague": {
                    "type": "string",
                    "description": "Filter to movers connected to a specific team member"
                },
                "company": {
                    "type": "string",
                    "description": "Filter to movers who moved to a specific company (partial match)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 30)"
                }
            },
            "required": []
        }
    },
    {
        "name": "run_sql",
        "description": "Run a read-only SQL query against the leads database. Use for complex queries that other tools can't answer. Tables: companies, signals_jobs, signals_news, signals_tenders, signals_network, signals_annual_reports, signals_sentiment, signals_pe_deals, signals_linkedin_intel, network_graph, team_members. All signal tables have company_id FK to companies.id.",
        "input_schema": {
            "type": "object",
            "properties": {
                "sql": {
                    "type": "string",
                    "description": "SELECT query to run. Must be a SELECT statement. Auto-limited to 50 rows."
                }
            },
            "required": ["sql"]
        }
    },
    {
        "name": "find_warm_routes",
        "description": "Find routes into a company with evidence quality tiers. TIER 1: LinkedIn intel contacts with verified engagement data (active, posts about transformation, interaction history). TIER 2: Scored network matches (role/seniority matched). TIER 3: Raw LinkedIn connections (connected but no engagement evidence). Always shows evidence quality clearly.",
        "input_schema": {
            "type": "object",
            "properties": {
                "company_name": {
                    "type": "string",
                    "description": "Company name to find warm routes into (fuzzy matched)"
                }
            },
            "required": ["company_name"]
        }
    },
    {
        "name": "get_strategic_opportunities",
        "description": "Cross-reference ALL signal types against network data to find the highest-value opportunities. Runs 5 strategic analyses: signal convergence (3+ signal types), warm+hot leads (score 50+ with connections), PE integration plays, sentiment+hiring combos, and warm routes to cold hot leads. Use for 'where should we focus?' or 'best opportunities' questions.",
        "input_schema": {
            "type": "object",
            "properties": {
                "focus": {
                    "type": "string",
                    "description": "Optional focus area: 'convergence', 'warm_hot', 'pe', 'sentiment', 'cold_routes', or 'all' (default)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_sleeping_giants",
        "description": "Find untracked companies showing ACTIVITY SIGNALS β€” recent connection growth (last 6 months) or strong senior access (3+ senior contacts). Filters out historical-only connections with no evidence of current opportunity. These are organisations where the team is actively building relationships but hasn't formally pursued yet.",
        "input_schema": {
            "type": "object",
            "properties": {
                "min_connections": {
                    "type": "integer",
                    "description": "Minimum connections required (default 3)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 20)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_network_intelligence",
        "description": "Team-level network analytics β€” who has the strongest reach into which sectors/company clusters, which team member should lead which pursuits. Returns per-member stats and deployment recommendations.",
        "input_schema": {
            "type": "object",
            "properties": {
                "sector_filter": {
                    "type": "string",
                    "description": "Optional sector to focus on (e.g. 'healthcare', 'financial')"
                }
            },
            "required": []
        }
    },
    {
        "name": "detect_competitor_signals",
        "description": "Detect signs that OTHER consultancies are active at target companies. Looks for: (1) Hiring velocity β€” companies posting 3+ transformation/change/programme roles (someone is spending, a programme is in flight). (2) Transformation role holders β€” people with change/transformation titles at targets who are the buyers. (3) Tenders for consultancy services. (4) Team connections at competitor consultancies (Deloitte, Accenture, PwC, etc.) who could provide intel. Use for 'who else is pitching?' or 'where are competitors active?'",
        "input_schema": {
            "type": "object",
            "properties": {
                "company_name": {
                    "type": "string",
                    "description": "Optional: focus on a specific company. Leave empty for cross-portfolio scan."
                },
                "sector": {
                    "type": "string",
                    "description": "Optional: filter by sector"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_highest_conviction_leads",
        "description": "Find leads with the STRONGEST multi-signal evidence β€” not just score, but independent corroborating signals. Scores each company by number of independent conviction signals: hiring velocity (3+ transformation roles), leadership changes (news), poor sentiment + hiring combo, PE acquisition, engagement-verified contacts, tenders. Returns companies ranked by conviction level with full evidence breakdown.",
        "input_schema": {
            "type": "object",
            "properties": {
                "min_conviction": {
                    "type": "integer",
                    "description": "Minimum number of independent conviction signals (default 2)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 15)"
                }
            },
            "required": []
        }
    },
    {
        "name": "get_personal_action_plan",
        "description": "Generate a personal daily LinkedIn action plan for a team member. Analyses their network gaps vs hot companies, identifies warm intro opportunities via teammates, finds engagement targets, and returns 5-10 specific prioritised actions (connect, comment, message, request intro). Defaults to Piers if no name specified.",
        "input_schema": {
            "type": "object",
            "properties": {
                "colleague_name": {
                    "type": "string",
                    "description": "Team member name (default: Piers)"
                },
                "max_actions": {
                    "type": "integer",
                    "description": "Maximum actions to generate (default 10)"
                }
            },
            "required": []
        }
    },
]


# =============================================================================
# TOOL EXECUTION
# =============================================================================

def _fuzzy_match_company(name: str) -> tuple:
    """Find best matching company by name. Returns (company_id, company_name) or (None, None)."""
    conn = get_connection()
    cursor = conn.cursor()

    # Try exact match first
    cursor.execute("SELECT id, name FROM companies WHERE LOWER(name) = LOWER(?)", (name,))
    row = cursor.fetchone()
    if row:
        conn.close()
        return row[0], row[1]

    # Try LIKE match
    cursor.execute("SELECT id, name FROM companies WHERE LOWER(name) LIKE ?", (f"%{name.lower()}%",))
    rows = cursor.fetchall()
    if len(rows) == 1:
        conn.close()
        return rows[0][0], rows[0][1]

    # Fuzzy match if available
    if FUZZY_AVAILABLE and rows:
        best_id, best_name, best_score = None, None, 0
        for cid, cname in rows:
            score = fuzz.ratio(name.lower(), cname.lower())
            if score > best_score:
                best_id, best_name, best_score = cid, cname, score
        conn.close()
        if best_score >= 60:
            return best_id, best_name
        return None, None

    if FUZZY_AVAILABLE and not rows:
        cursor.execute("SELECT id, name FROM companies")
        all_companies = cursor.fetchall()
        conn.close()
        best_id, best_name, best_score = None, None, 0
        for cid, cname in all_companies:
            score = fuzz.ratio(name.lower(), cname.lower())
            if score > best_score:
                best_id, best_name, best_score = cid, cname, score
        if best_score >= 60:
            return best_id, best_name
        return None, None

    # If no fuzzy and multiple LIKE matches, return first
    if rows:
        conn.close()
        return rows[0][0], rows[0][1]

    conn.close()
    return None, None


def execute_tool(tool_name: str, tool_input: dict) -> str:
    """Execute a tool call and return the result as a string."""
    try:
        if tool_name == "search_companies":
            return _tool_search_companies(tool_input)
        elif tool_name == "get_company_detail":
            return _tool_get_company_detail(tool_input)
        elif tool_name == "find_connections":
            return _tool_find_connections(tool_input)
        elif tool_name == "find_person":
            return _tool_find_person(tool_input)
        elif tool_name == "get_movers":
            return _tool_get_movers(tool_input)
        elif tool_name == "run_sql":
            return _tool_run_sql(tool_input)
        elif tool_name == "find_warm_routes":
            return _tool_find_warm_routes(tool_input)
        elif tool_name == "get_strategic_opportunities":
            return _tool_get_strategic_opportunities(tool_input)
        elif tool_name == "get_sleeping_giants":
            return _tool_get_sleeping_giants(tool_input)
        elif tool_name == "get_network_intelligence":
            return _tool_get_network_intelligence(tool_input)
        elif tool_name == "detect_competitor_signals":
            return _tool_detect_competitor_signals(tool_input)
        elif tool_name == "get_highest_conviction_leads":
            return _tool_get_highest_conviction_leads(tool_input)
        elif tool_name == "get_personal_action_plan":
            return _tool_get_personal_action_plan(tool_input)
        else:
            return f"Unknown tool: {tool_name}"
    except Exception as e:
        return f"Tool error ({tool_name}): {str(e)}"


def _tool_search_companies(params: dict) -> str:
    conn = get_connection()
    cursor = conn.cursor()

    conditions = []
    values = []

    if params.get("name_pattern"):
        conditions.append("LOWER(name) LIKE ?")
        values.append(f"%{params['name_pattern'].lower()}%")

    if params.get("min_score") is not None:
        conditions.append("overall_score >= ?")
        values.append(params["min_score"])

    if params.get("max_score") is not None:
        conditions.append("overall_score <= ?")
        values.append(params["max_score"])

    if params.get("sector"):
        conditions.append("LOWER(sector) LIKE ?")
        values.append(f"%{params['sector'].lower()}%")

    if params.get("signal_type"):
        conditions.append("LOWER(signal_summary) LIKE ?")
        values.append(f"%{params['signal_type'].lower()}%")

    if params.get("network_status"):
        ns = params["network_status"]
        if ns.lower() == "cold":
            conditions.append("(network_status = 'Cold' OR network_status IS NULL)")
        else:
            conditions.append("LOWER(network_status) LIKE ?")
            values.append(f"%{ns.lower()}%")

    if params.get("service_line"):
        sl = params["service_line"].lower()
        if sl == "td":
            conditions.append("td_score > 0")
        elif sl == "cc":
            conditions.append("cc_score > 0")

    where = " AND ".join(conditions) if conditions else "1=1"
    limit = min(params.get("limit", 20), 50)

    cursor.execute(f"""
        SELECT name, overall_score, sector, network_status, td_score, cc_score,
               best_contact, best_colleague, signal_summary
        FROM companies WHERE {where}
        ORDER BY overall_score DESC LIMIT ?
    """, values + [limit])

    rows = cursor.fetchall()
    conn.close()

    if not rows:
        return "No companies found matching those criteria."

    lines = [f"Found {len(rows)} companies:"]
    for r in rows:
        name, score, sector, net, td, cc, contact, colleague, sigs = r
        line = f"- {name} (score: {score}, sector: {sector or '?'}, network: {net or 'Cold'}, TD:{td or 0}/CC:{cc or 0})"
        if contact:
            line += f" β€” best contact: {contact}"
        if colleague:
            line += f" via {colleague}"
        if sigs:
            line += f" | signals: {sigs[:100]}"
        lines.append(line)

    return "\n".join(lines)


def _tool_get_company_detail(params: dict) -> str:
    company_name = params.get("company_name", "")
    cid, matched_name = _fuzzy_match_company(company_name)
    if not cid:
        return f"No company found matching '{company_name}'."

    from collator import get_company_dossier
    dossier = get_company_dossier(cid)
    if not dossier:
        return f"Company '{matched_name}' (id={cid}) found but dossier retrieval failed."

    parts = [
        f"COMPANY: {dossier.name}",
        f"Score: {dossier.overall_score} (TD: {dossier.td_score}, CC: {dossier.cc_score})",
        f"Sector: {dossier.sector or 'Unknown'}",
        f"Network: {dossier.network_status or 'Cold'}",
        f"Best contact: {dossier.best_contact or 'None'} via {dossier.best_colleague or 'None'}",
        f"Signals: {dossier.signal_summary or 'None'}",
        f"Services: {', '.join(dossier.recommended_services) if dossier.recommended_services else 'None'}",
        f"First seen: {dossier.first_seen}, Last updated: {dossier.last_updated}",
    ]

    if dossier.jobs:
        parts.append(f"\nJOBS ({len(dossier.jobs)}):")
        for j in dossier.jobs[:5]:
            parts.append(f"  - {j.get('title', '?')} (score: {j.get('score', 0)}) β€” {j.get('analysis', '')[:80]}")

    if dossier.news:
        parts.append(f"\nNEWS ({len(dossier.news)}):")
        for n in dossier.news[:5]:
            parts.append(f"  - [{n.get('urgency', '?')}] {n.get('headline', '?')} (trigger: {n.get('trigger', '?')}, score: {n.get('score', 0)})")

    if dossier.tenders:
        parts.append(f"\nTENDERS ({len(dossier.tenders)}):")
        for t in dossier.tenders[:5]:
            parts.append(f"  - {t.get('title', '?')} (value: {t.get('value', '?')}, deadline: {t.get('deadline', '?')})")

    if dossier.network:
        parts.append(f"\nNETWORK CONNECTIONS ({len(dossier.network)}):")
        for n in dossier.network[:10]:
            parts.append(f"  - {n.get('contact', '?')} ({n.get('position', '?')}) β€” via {n.get('colleague', '?')} (tier {n.get('tier', '?')})")

    if dossier.sentiment_signals:
        parts.append(f"\nSENTIMENT ({len(dossier.sentiment_signals)}):")
        for s in dossier.sentiment_signals[:3]:
            parts.append(f"  - Overall: {s.get('overall_rating', '?')}, Mgmt: {s.get('management_rating', '?')}, Culture: {s.get('culture_rating', '?')} β€” {s.get('signal_reason', '')[:80]}")

    if dossier.pe_deals:
        parts.append(f"\nPE/M&A DEALS ({len(dossier.pe_deals)}):")
        for p in dossier.pe_deals[:3]:
            parts.append(f"  - {p.get('deal_type', '?')} by {p.get('acquirer_name', '?')} (date: {p.get('deal_date', '?')}, value: {p.get('deal_value', '?')})")

    if dossier.linkedin_intel:
        parts.append(f"\nLINKEDIN INTEL ({len(dossier.linkedin_intel)}):")
        for li in dossier.linkedin_intel[:5]:
            parts.append(f"  - {li.get('contact_name', '?')} ({li.get('contact_title', '?')}) via {li.get('colleague_name', '?')} β€” {li.get('relationship_tier', '?')}, action: {li.get('recommended_action', '?')}")

    if dossier.annual_reports:
        parts.append(f"\nANNUAL REPORTS ({len(dossier.annual_reports)}):")
        for ar in dossier.annual_reports[:3]:
            parts.append(f"  - Score: {ar.get('score', 0)}, filed: {ar.get('filing_date', '?')} β€” {ar.get('summary', '')[:100]}")

    return "\n".join(parts)


def _tool_find_connections(params: dict) -> str:
    company_name = params.get("company_name", "")
    conn = get_connection()
    cursor = conn.cursor()

    # Search network_graph (raw LinkedIn connections) β€” try exact LIKE first
    cursor.execute("""
        SELECT contact_name, company, position, colleague_owner, is_senior, status, is_new_company
        FROM network_graph
        WHERE LOWER(company) LIKE ?
        ORDER BY is_senior DESC, contact_name
        LIMIT 30
    """, (f"%{company_name.lower()}%",))
    net_rows = cursor.fetchall()

    # If no results, try matching on key words (handles "Valeo Food Group" vs "Valeo Foods Group")
    if not net_rows:
        words = [w for w in company_name.lower().split() if len(w) >= 3]
        if words:
            word_conditions = " AND ".join(["LOWER(company) LIKE ?" for _ in words])
            word_values = [f"%{w}%" for w in words]
            cursor.execute(f"""
                SELECT contact_name, company, position, colleague_owner, is_senior, status, is_new_company
                FROM network_graph
                WHERE {word_conditions}
                ORDER BY is_senior DESC, contact_name
                LIMIT 30
            """, word_values)
            net_rows = cursor.fetchall()

    # If still no results and fuzzy available, try fuzzy matching against distinct companies
    if not net_rows and FUZZY_AVAILABLE:
        cursor.execute("SELECT DISTINCT company FROM network_graph")
        all_companies = [r[0] for r in cursor.fetchall()]
        matches = []
        for co in all_companies:
            score = fuzz.partial_ratio(company_name.lower(), co.lower())
            if score >= 75:
                matches.append(co)
        if matches:
            placeholders = ",".join(["?" for _ in matches])
            cursor.execute(f"""
                SELECT contact_name, company, position, colleague_owner, is_senior, status, is_new_company
                FROM network_graph
                WHERE company IN ({placeholders})
                ORDER BY is_senior DESC, contact_name
                LIMIT 30
            """, matches)
            net_rows = cursor.fetchall()

    # Search signals_linkedin_intel (enriched contacts)
    cursor.execute("""
        SELECT li.contact_name, li.contact_title, li.colleague_name, li.connection_degree,
               li.relationship_tier, li.recommended_action, li.contact_active,
               li.posts_about_transformation, c.name
        FROM signals_linkedin_intel li
        JOIN companies c ON li.company_id = c.id
        WHERE LOWER(c.name) LIKE ?
        ORDER BY li.relationship_score DESC
        LIMIT 20
    """, (f"%{company_name.lower()}%",))
    li_rows = cursor.fetchall()

    conn.close()

    if not net_rows and not li_rows:
        return f"No connections found at any company matching '{company_name}'."

    parts = [f"Connections at companies matching '{company_name}':"]

    if net_rows:
        parts.append(f"\nNETWORK GRAPH ({len(net_rows)} connections):")
        for r in net_rows:
            contact, company, position, colleague, senior, status, new_co = r
            flags = []
            if senior:
                flags.append("SENIOR")
            if status == "MOVER":
                flags.append("MOVER")
            if new_co:
                flags.append("NEW_COMPANY")
            flag_str = f" [{', '.join(flags)}]" if flags else ""
            parts.append(f"  - {contact} ({position or '?'}) at {company} β€” connected via {colleague}{flag_str}")

    if li_rows:
        parts.append(f"\nLINKEDIN INTEL ({len(li_rows)} enriched contacts):")
        for r in li_rows:
            name, title, colleague, degree, tier, action, active, posts_transf, co_name = r
            flags = []
            if active:
                flags.append("ACTIVE")
            if posts_transf:
                flags.append("POSTS_TRANSFORMATION")
            flag_str = f" [{', '.join(flags)}]" if flags else ""
            parts.append(f"  - {name} ({title or '?'}) at {co_name} β€” via {colleague}, {degree} degree, tier: {tier}, action: {action}{flag_str}")

    return "\n".join(parts)


def _tool_find_person(params: dict) -> str:
    person_name = params.get("person_name", "")
    conn = get_connection()
    cursor = conn.cursor()

    # Search network_graph β€” try LIKE first
    cursor.execute("""
        SELECT contact_name, company, position, colleague_owner, is_senior, status, is_new_company
        FROM network_graph
        WHERE LOWER(contact_name) LIKE ?
        ORDER BY contact_name
        LIMIT 20
    """, (f"%{person_name.lower()}%",))
    net_rows = cursor.fetchall()

    # Fallback: match each name part independently (handles first/last in any order)
    if not net_rows:
        words = [w for w in person_name.lower().split() if len(w) >= 2]
        if words:
            word_conditions = " AND ".join(["LOWER(contact_name) LIKE ?" for _ in words])
            word_values = [f"%{w}%" for w in words]
            cursor.execute(f"""
                SELECT contact_name, company, position, colleague_owner, is_senior, status, is_new_company
                FROM network_graph
                WHERE {word_conditions}
                ORDER BY contact_name
                LIMIT 20
            """, word_values)
            net_rows = cursor.fetchall()

    # Search LinkedIn intel
    cursor.execute("""
        SELECT li.contact_name, li.contact_title, li.colleague_name, li.connection_degree,
               li.relationship_tier, li.recommended_action, c.name, c.overall_score
        FROM signals_linkedin_intel li
        JOIN companies c ON li.company_id = c.id
        WHERE LOWER(li.contact_name) LIKE ?
        ORDER BY c.overall_score DESC
        LIMIT 20
    """, (f"%{person_name.lower()}%",))
    li_rows = cursor.fetchall()

    conn.close()

    if not net_rows and not li_rows:
        return f"No one named '{person_name}' found in our network or LinkedIn intel data."

    parts = [f"People matching '{person_name}':"]

    if net_rows:
        parts.append(f"\nNETWORK ({len(net_rows)} matches):")
        for r in net_rows:
            contact, company, position, colleague, senior, status, new_co = r
            flags = []
            if senior:
                flags.append("SENIOR")
            if status == "MOVER":
                flags.append("MOVER")
            if new_co:
                flags.append("NEW_COMPANY")
            flag_str = f" [{', '.join(flags)}]" if flags else ""
            parts.append(f"  - {contact} ({position or '?'}) at {company} β€” via {colleague}{flag_str}")

    if li_rows:
        parts.append(f"\nLINKEDIN INTEL ({len(li_rows)} matches):")
        for r in li_rows:
            name, title, colleague, degree, tier, action, co_name, co_score = r
            parts.append(f"  - {name} ({title or '?'}) at {co_name} (score:{co_score}) β€” via {colleague}, tier: {tier}, action: {action}")

    return "\n".join(parts)


def _tool_get_movers(params: dict) -> str:
    conn = get_connection()
    cursor = conn.cursor()

    conditions = ["is_new_company = 1"]
    values = []

    if params.get("colleague"):
        conditions.append("LOWER(colleague_owner) LIKE ?")
        values.append(f"%{params['colleague'].lower()}%")

    if params.get("company"):
        co_words = [w for w in params['company'].lower().split() if len(w) >= 3]
        for w in co_words:
            conditions.append("LOWER(company) LIKE ?")
            values.append(f"%{w}%")

    limit = min(params.get("limit", 30), 50)
    where = " AND ".join(conditions)

    cursor.execute(f"""
        SELECT contact_name, company, position, colleague_owner, date_connected
        FROM network_graph
        WHERE {where}
        ORDER BY date_connected DESC
        LIMIT ?
    """, values + [limit])

    rows = cursor.fetchall()
    conn.close()

    if not rows:
        return "No movers found matching those criteria."

    parts = [f"Found {len(rows)} movers (contacts who changed companies):"]
    for r in rows:
        name, company, position, colleague, date_conn = r
        parts.append(f"  - {name} moved to {company} ({position or '?'}) β€” connected via {colleague}, connected: {date_conn or '?'}")

    return "\n".join(parts)


def _tool_run_sql(params: dict) -> str:
    sql = params.get("sql", "").strip()

    # Safety: only SELECT
    if not sql.upper().startswith("SELECT"):
        return "Error: only SELECT queries are allowed."

    # Block dangerous patterns
    lower = sql.lower()
    for blocked in ["drop ", "delete ", "insert ", "update ", "alter ", "create ", "attach ", "pragma "]:
        if blocked in lower:
            return f"Error: '{blocked.strip()}' statements are not allowed."

    # Auto-add LIMIT if missing
    if "limit" not in lower:
        sql = sql.rstrip(";") + " LIMIT 50"

    conn = get_connection()
    conn.execute("PRAGMA query_only = ON")
    cursor = conn.cursor()

    try:
        cursor.execute(sql)
        columns = [desc[0] for desc in cursor.description] if cursor.description else []
        rows = cursor.fetchall()
    except Exception as e:
        conn.close()
        return f"SQL error: {str(e)}"
    finally:
        conn.close()

    if not rows:
        return "Query returned no results."

    parts = [f"Results ({len(rows)} rows):"]
    parts.append(" | ".join(columns))
    parts.append("-" * 60)
    for row in rows:
        parts.append(" | ".join(str(v) for v in row))

    return "\n".join(parts)


def _tool_find_warm_routes(params: dict) -> str:
    company_name = params.get("company_name", "")
    conn = get_connection()
    cursor = conn.cursor()

    # ---- 1. LinkedIn Intel (HIGHEST EVIDENCE) ----
    # These contacts have been profile-scanned with engagement data:
    # relationship_score, contact_active, posts_about_transformation, last_interaction_days
    cursor.execute("""
        SELECT li.contact_name, li.contact_title, li.colleague_name, li.connection_degree,
               li.relationship_score, li.relationship_tier, li.recommended_action,
               li.contact_active, li.posts_about_transformation, li.last_interaction_days,
               li.mutual_connections, c.name, c.overall_score
        FROM signals_linkedin_intel li
        JOIN companies c ON li.company_id = c.id
        WHERE LOWER(c.name) LIKE ?
        ORDER BY li.relationship_score DESC LIMIT 20
    """, (f"%{company_name.lower()}%",))
    li_rows = cursor.fetchall()

    # ---- 2. Scored Network (MEDIUM EVIDENCE) ----
    cursor.execute("""
        SELECT sn.contact_name, sn.contact_position, sn.colleague_name, sn.connection_tier,
               sn.match_score, c.name, c.overall_score
        FROM signals_network sn
        JOIN companies c ON sn.company_id = c.id
        WHERE LOWER(c.name) LIKE ?
        ORDER BY sn.match_score DESC LIMIT 20
    """, (f"%{company_name.lower()}%",))
    sn_rows = cursor.fetchall()

    # ---- 3. Network Graph (CONNECTION ONLY β€” no engagement evidence) ----
    words = [w for w in company_name.lower().split() if len(w) >= 3]
    net_rows = []

    cursor.execute("""
        SELECT contact_name, company, position, colleague_owner, is_senior, status,
               is_new_company, date_connected
        FROM network_graph WHERE LOWER(company) LIKE ?
        ORDER BY is_senior DESC, date_connected DESC LIMIT 30
    """, (f"%{company_name.lower()}%",))
    net_rows = cursor.fetchall()

    if not net_rows and words:
        word_conditions = " AND ".join(["LOWER(company) LIKE ?" for _ in words])
        word_values = [f"%{w}%" for w in words]
        cursor.execute(f"""
            SELECT contact_name, company, position, colleague_owner, is_senior, status,
                   is_new_company, date_connected
            FROM network_graph WHERE {word_conditions}
            ORDER BY is_senior DESC, date_connected DESC LIMIT 30
        """, word_values)
        net_rows = cursor.fetchall()

    if not net_rows and FUZZY_AVAILABLE:
        cursor.execute("SELECT DISTINCT company FROM network_graph")
        all_companies = [r[0] for r in cursor.fetchall()]
        matches = [co for co in all_companies if fuzz.partial_ratio(company_name.lower(), co.lower()) >= 75]
        if matches:
            placeholders = ",".join(["?" for _ in matches])
            cursor.execute(f"""
                SELECT contact_name, company, position, colleague_owner, is_senior, status,
                       is_new_company, date_connected
                FROM network_graph WHERE company IN ({placeholders})
                ORDER BY is_senior DESC, date_connected DESC LIMIT 30
            """, matches)
            net_rows = cursor.fetchall()

    # ---- 4. Company context ----
    cid, matched_name = _fuzzy_match_company(company_name)
    company_info = ""
    if cid:
        cursor.execute("SELECT overall_score, network_status, signal_summary FROM companies WHERE id = ?", (cid,))
        row = cursor.fetchone()
        if row:
            company_info = f"\nTRACKED COMPANY: {matched_name} (score: {row[0]}, network: {row[1] or 'Cold'}, signals: {row[2] or 'none'})"

    conn.close()

    if not net_rows and not li_rows and not sn_rows:
        return f"No routes found into '{company_name}'. This company may not be in our network. Try run_sql against network_graph for related companies, or get_sleeping_giants for similar organisations."

    parts = [f"ROUTES INTO '{company_name.upper()}'"]
    if company_info:
        parts.append(company_info)

    # ---- EVIDENCE QUALITY HIERARCHY ----
    # Lead with engagement-verified contacts, then scored network, then raw connections
    best_route = None
    best_evidence = None

    # TIER 1: LinkedIn Intel β€” engagement-verified
    if li_rows:
        # Separate by engagement evidence
        engaged = [r for r in li_rows if r[7] or r[8] or r[9] >= 0]  # active, posts_transformation, or has interaction data
        dormant = [r for r in li_rows if not (r[7] or r[8] or r[9] >= 0)]

        if engaged:
            parts.append(f"\nβœ… VERIFIED ENGAGEMENT ({len(engaged)} contacts with LinkedIn activity evidence):")
            for r in engaged:
                name, title, colleague, degree, rel_score, tier, action, active, posts_transf, last_int, mutual, co_name, co_score = r
                evidence = []
                if active:
                    evidence.append("active on LinkedIn")
                if posts_transf:
                    evidence.append("posts about transformation")
                if last_int >= 0:
                    evidence.append(f"last interaction {last_int}d ago")
                if mutual:
                    evidence.append(f"{mutual} mutual connections")
                evidence_str = " | ".join(evidence) if evidence else "profile scanned"
                parts.append(f"  - {name} ({title or '?'}) via {colleague} β€” score: {rel_score}/100 ({tier}) β€” {evidence_str}")
                if not best_route:
                    best_route = f"{name} via {colleague}"
                    best_evidence = f"relationship score {rel_score}/100, {', '.join(evidence)}"

        if dormant:
            parts.append(f"\n⚠️ DORMANT CONTACTS ({len(dormant)} β€” connected but no engagement detected):")
            for r in dormant:
                name, title, colleague, degree, rel_score, tier, action, active, posts_transf, last_int, mutual, co_name, co_score = r
                parts.append(f"  - {name} ({title or '?'}) via {colleague} β€” score: {rel_score}/100 β€” {action[:80]}")

    # TIER 2: Scored network matches
    if sn_rows:
        parts.append(f"\nSCORED NETWORK ({len(sn_rows)} β€” matched by role/seniority, no engagement data):")
        for r in sn_rows:
            name, position, colleague, tier, score, co_name, co_score = r
            parts.append(f"  - {name} ({position or '?'}) via {colleague}, tier: {tier}, match: {score}")
            if not best_route:
                best_route = f"{name} via {colleague}"
                best_evidence = f"scored network match ({tier}, score {score})"

    # TIER 3: Raw network connections β€” CONNECTION ONLY, no engagement evidence
    if net_rows:
        seniors = [r for r in net_rows if r[4]]
        recent = [r for r in net_rows if not r[4] and r[7] and r[7] >= '2025-08-01']
        older = [r for r in net_rows if not r[4] and (not r[7] or r[7] < '2025-08-01')]

        if seniors:
            parts.append(f"\nπŸ“‹ SENIOR CONNECTIONS ({len(seniors)} β€” LinkedIn connected, no engagement verification):")
            for r in seniors[:10]:
                contact, company, position, colleague, senior, status, new_co, date_conn = r
                date_str = f", connected {date_conn[:10]}" if date_conn else ""
                parts.append(f"  - {contact} ({position or '?'}) at {company} β€” via {colleague}{date_str}")
            if not best_route:
                best_route = f"{seniors[0][0]} via {seniors[0][3]}"
                best_evidence = "senior LinkedIn connection (no engagement data β€” needs verification)"

        if recent:
            parts.append(f"\nπŸ“‹ RECENT CONNECTIONS ({len(recent)} β€” connected in last 6 months, unverified):")
            for r in recent[:5]:
                contact, company, position, colleague, senior, status, new_co, date_conn = r
                parts.append(f"  - {contact} ({position or '?'}) at {company} β€” via {colleague}, connected {date_conn[:10] if date_conn else '?'}")

        if older:
            parts.append(f"\nπŸ“‹ OLDER CONNECTIONS ({len(older)} β€” no recent activity, unverified):")
            parts.append(f"  ({len(older)} contacts listed but no engagement evidence β€” run LinkedIn profile scan to verify)")

    # ---- RECOMMENDATION ----
    if best_route:
        parts.insert(1, f"\n🎯 BEST ROUTE: {best_route}")
        parts.insert(2, f"   Evidence: {best_evidence}")

    # Data quality notice
    parts.append(f"\nπŸ“Š CONFIDENCE NOTE: Only contacts under 'Verified Engagement' have actual LinkedIn activity data. "
                 f"All other connections are based on LinkedIn connection status only β€” run a profile scan to get engagement evidence before reaching out.")

    return "\n".join(parts)


def _tool_get_strategic_opportunities(params: dict) -> str:
    focus = params.get("focus", "all").lower()
    conn = get_connection()
    cursor = conn.cursor()
    parts = ["STRATEGIC OPPORTUNITY ANALYSIS"]
    results_found = False

    # 1. Signal Convergence β€” companies with 3+ signal types
    if focus in ("all", "convergence"):
        cursor.execute("""
            SELECT c.name, c.overall_score, c.sector, c.network_status,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_jobs j WHERE j.company_id=c.id) THEN 1 ELSE 0 END) as has_jobs,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_news n WHERE n.company_id=c.id) THEN 1 ELSE 0 END) as has_news,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_tenders t WHERE t.company_id=c.id) THEN 1 ELSE 0 END) as has_tenders,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_pe_deals p WHERE p.company_id=c.id) THEN 1 ELSE 0 END) as has_pe,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_sentiment s WHERE s.company_id=c.id) THEN 1 ELSE 0 END) as has_sentiment,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_annual_reports a WHERE a.company_id=c.id) THEN 1 ELSE 0 END) as has_reports,
                   (CASE WHEN EXISTS(SELECT 1 FROM signals_linkedin_intel l WHERE l.company_id=c.id) THEN 1 ELSE 0 END) as has_linkedin
            FROM companies c
            ORDER BY c.overall_score DESC
        """)
        rows = cursor.fetchall()
        convergence = []
        for r in rows:
            name, score, sector, net, *signal_flags = r
            signal_types = []
            labels = ['jobs', 'news', 'tenders', 'PE/M&A', 'sentiment', 'annual_reports', 'linkedin_intel']
            for flag, label in zip(signal_flags, labels):
                if flag:
                    signal_types.append(label)
            if len(signal_types) >= 3:
                convergence.append((name, score, sector, net, signal_types))

        if convergence:
            results_found = True
            parts.append(f"\nπŸ”₯ SIGNAL CONVERGENCE β€” {len(convergence)} companies with 3+ signal types (transformation in motion):")
            for name, score, sector, net, signals in convergence[:10]:
                parts.append(f"  - {name} (score: {score}, sector: {sector or '?'}, network: {net or 'Cold'}) β€” signals: {', '.join(signals)}")

    # 2. Hot leads with verified engagement vs connection-only
    if focus in ("all", "warm_hot"):
        # Hot leads WITH LinkedIn intel engagement evidence
        cursor.execute("""
            SELECT c.name, c.overall_score, c.sector, c.network_status, c.best_contact, c.best_colleague,
                   (SELECT COUNT(*) FROM signals_linkedin_intel li
                    WHERE li.company_id = c.id AND (li.contact_active = 1 OR li.posts_about_transformation = 1)) as engaged_contacts
            FROM companies c
            WHERE c.overall_score >= 50 AND c.network_status != 'Cold' AND c.network_status IS NOT NULL
            ORDER BY engaged_contacts DESC, c.overall_score DESC
        """)
        rows = cursor.fetchall()
        if rows:
            results_found = True
            verified = [r for r in rows if r[6] > 0]
            unverified = [r for r in rows if r[6] == 0]

            if verified:
                parts.append(f"\nβœ… HOT + ENGAGEMENT VERIFIED β€” {len(verified)} leads with LinkedIn activity evidence:")
                for name, score, sector, net, contact, colleague, engaged in verified[:10]:
                    parts.append(f"  - {name} (score: {score}, network: {net}, {engaged} active contacts) β€” route: {contact or '?'} via {colleague or '?'}")

            if unverified:
                parts.append(f"\nπŸ“‹ HOT + CONNECTED β€” {len(unverified)} leads with connections but no engagement data (need profile scan):")
                for name, score, sector, net, contact, colleague, engaged in unverified[:10]:
                    parts.append(f"  - {name} (score: {score}, network: {net}) β€” route: {contact or '?'} via {colleague or '?'}")

    # 3. PE Integration Plays
    if focus in ("all", "pe"):
        cursor.execute("""
            SELECT c.name, c.overall_score, pe.acquirer_name, pe.deal_type, pe.deal_date,
                   c.network_status, c.best_contact, c.best_colleague
            FROM signals_pe_deals pe
            JOIN companies c ON pe.company_id = c.id
            ORDER BY c.overall_score DESC
        """)
        rows = cursor.fetchall()
        pe_with_connections = []
        pe_without = []
        for r in rows:
            name, score, acquirer, deal_type, deal_date, net, contact, colleague = r
            if net and net != 'Cold':
                pe_with_connections.append(r)
            else:
                pe_without.append(r)

        if pe_with_connections:
            results_found = True
            parts.append(f"\nπŸ’° PE INTEGRATION PLAYS β€” {len(pe_with_connections)} PE-backed companies WITH connections (post-acquisition = TD goldmine):")
            for name, score, acquirer, deal_type, deal_date, net, contact, colleague in pe_with_connections[:10]:
                parts.append(f"  - {name} (score: {score}) β€” {deal_type} by {acquirer} ({deal_date or '?'}) β€” route: {contact or '?'} via {colleague or '?'}")
        if pe_without:
            parts.append(f"\n  PE companies without connections ({len(pe_without)}):")
            for name, score, acquirer, deal_type, deal_date, net, contact, colleague in pe_without[:5]:
                parts.append(f"  - {name} (score: {score}) β€” {deal_type} by {acquirer} β€” COLD (check network_graph for hidden routes)")

    # 4. Sentiment + Hiring β€” poor ratings AND active job postings
    if focus in ("all", "sentiment"):
        cursor.execute("""
            SELECT c.name, c.overall_score, s.overall_rating, s.management_rating, s.signal_reason,
                   c.network_status
            FROM signals_sentiment s
            JOIN companies c ON s.company_id = c.id
            WHERE s.overall_rating <= 3.5
            AND EXISTS(SELECT 1 FROM signals_jobs j WHERE j.company_id = c.id)
            ORDER BY s.overall_rating ASC
        """)
        rows = cursor.fetchall()
        if rows:
            results_found = True
            parts.append(f"\n⚠️ SENTIMENT + HIRING β€” {len(rows)} companies with poor ratings AND active job postings (they have a problem AND are spending):")
            for name, score, rating, mgmt, reason, net in rows[:10]:
                parts.append(f"  - {name} (score: {score}, Glassdoor: {rating}, mgmt: {mgmt}, network: {net or 'Cold'}) β€” {(reason or '')[:80]}")

    # 5. Warm routes to cold hot leads
    if focus in ("all", "cold_routes"):
        cursor.execute("""
            SELECT c.id, c.name, c.overall_score, c.sector
            FROM companies c
            WHERE c.overall_score >= 50 AND (c.network_status = 'Cold' OR c.network_status IS NULL)
            ORDER BY c.overall_score DESC
        """)
        cold_hot = cursor.fetchall()
        found_routes = []
        for cid, cname, cscore, csector in cold_hot:
            # Check network_graph for connections the scored system missed
            words = [w for w in cname.lower().split() if len(w) >= 3]
            if words:
                word_conditions = " AND ".join(["LOWER(company) LIKE ?" for _ in words])
                word_values = [f"%{w}%" for w in words]
                cursor.execute(f"""
                    SELECT contact_name, company, colleague_owner, is_senior
                    FROM network_graph WHERE {word_conditions}
                    ORDER BY is_senior DESC LIMIT 5
                """, word_values)
                routes = cursor.fetchall()
                if routes:
                    found_routes.append((cname, cscore, csector, routes))

        if found_routes:
            results_found = True
            parts.append(f"\nπŸ”“ HIDDEN ROUTES TO COLD HOT LEADS β€” {len(found_routes)} hot companies marked 'Cold' but with connections in network_graph:")
            for cname, cscore, csector, routes in found_routes[:10]:
                route_strs = [f"{r[0]} via {r[2]}{' [SENIOR]' if r[3] else ''}" for r in routes[:3]]
                parts.append(f"  - {cname} (score: {cscore}, sector: {csector or '?'}) β€” routes: {'; '.join(route_strs)}")

    conn.close()

    if not results_found:
        parts.append("\nNo strategic opportunities found matching that focus. Try 'all' for the full analysis.")

    return "\n".join(parts)


def _tool_get_sleeping_giants(params: dict) -> str:
    min_conns = params.get("min_connections", 3)
    limit = min(params.get("limit", 20), 50)
    conn = get_connection()
    cursor = conn.cursor()

    # Find untracked companies with EVIDENCE OF ACTIVITY:
    # - Recent connections (last 6 months) = active relationship building
    # - Senior connections = decision-maker access
    # Pure connection count without activity signals is just historical noise.
    cursor.execute(f"""
        SELECT ng.company_normalized, COUNT(*) as total,
               SUM(ng.is_senior) as seniors,
               SUM(CASE WHEN ng.date_connected >= date('now', '-6 months') THEN 1 ELSE 0 END) as recent_connections,
               GROUP_CONCAT(DISTINCT ng.colleague_owner) as team
        FROM network_graph ng
        LEFT JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
        WHERE c.id IS NULL AND ng.company_normalized IS NOT NULL AND ng.company_normalized != '' AND LOWER(ng.company_normalized) NOT IN ('curium', 'self employed', 'freelance', 'retired', 'unemployed', '') AND LOWER(ng.company_normalized) NOT LIKE '%curium solutions%'
        GROUP BY ng.company_normalized
        HAVING total >= ? AND (recent_connections > 0 OR seniors >= 3)
        ORDER BY recent_connections DESC, seniors DESC, total DESC
        LIMIT ?
    """, (min_conns, limit))
    rows = cursor.fetchall()
    conn.close()

    if not rows:
        return f"No sleeping giants found with {min_conns}+ connections and activity signals. Try lowering min_connections."

    parts = [f"SLEEPING GIANTS β€” {len(rows)} untracked companies with network activity:"]
    parts.append("These companies show evidence of active relationship building (recent connections) or strong senior access β€” but aren't being formally tracked.\n")

    for company, total, seniors, recent, team in rows:
        signals = []
        if recent:
            signals.append(f"{recent} new connections in last 6mo")
        if seniors:
            signals.append(f"{seniors} senior contacts")
        signal_str = " | ".join(signals)
        parts.append(f"  - {company} β€” {total} total connections | {signal_str} | team: {team}")

    parts.append(f"\nπŸ’‘ These are opportunities with live activity. Ask me to find warm routes into any of these.")

    return "\n".join(parts)


def _tool_get_network_intelligence(params: dict) -> str:
    sector_filter = params.get("sector_filter", "")
    conn = get_connection()
    cursor = conn.cursor()

    # Per team member stats
    sector_condition = ""
    sector_values = []
    if sector_filter:
        # Match sector against tracked companies
        sector_condition = "AND LOWER(ng.company) IN (SELECT LOWER(name) FROM companies WHERE LOWER(sector) LIKE ?)"
        sector_values = [f"%{sector_filter.lower()}%"]

    cursor.execute(f"""
        SELECT ng.colleague_owner,
               COUNT(*) as total_connections,
               SUM(ng.is_senior) as senior_connections,
               SUM(CASE WHEN ng.is_new_company = 1 THEN 1 ELSE 0 END) as movers,
               COUNT(DISTINCT ng.company_normalized) as unique_companies
        FROM network_graph ng
        WHERE ng.colleague_owner IS NOT NULL {sector_condition}
        GROUP BY ng.colleague_owner
        ORDER BY senior_connections DESC, total_connections DESC
    """, sector_values)
    team_stats = cursor.fetchall()

    # Connections at hot tracked companies (score 50+)
    cursor.execute("""
        SELECT ng.colleague_owner, COUNT(*) as hot_connections,
               GROUP_CONCAT(DISTINCT c.name) as hot_companies
        FROM network_graph ng
        JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
        WHERE c.overall_score >= 50 AND ng.colleague_owner IS NOT NULL
        GROUP BY ng.colleague_owner
        ORDER BY hot_connections DESC
    """)
    hot_stats = {r[0]: (r[1], r[2]) for r in cursor.fetchall()}

    # LinkedIn intel relationship quality per team member
    cursor.execute("""
        SELECT li.colleague_name, COUNT(*) as intel_contacts,
               AVG(li.relationship_score) as avg_rel_score,
               SUM(CASE WHEN li.relationship_tier IN ('Tier 1', 'Tier 2') THEN 1 ELSE 0 END) as strong_ties
        FROM signals_linkedin_intel li
        WHERE li.colleague_name IS NOT NULL
        GROUP BY li.colleague_name
        ORDER BY avg_rel_score DESC
    """)
    li_stats = {r[0]: (r[1], round(r[2] or 0, 1), r[3]) for r in cursor.fetchall()}

    # Sector reach per team member
    cursor.execute("""
        SELECT ng.colleague_owner, c.sector, COUNT(*) as cnt
        FROM network_graph ng
        JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
        WHERE c.sector IS NOT NULL AND ng.colleague_owner IS NOT NULL
        GROUP BY ng.colleague_owner, c.sector
        ORDER BY cnt DESC
    """)
    sector_reach = {}
    for colleague, sector, cnt in cursor.fetchall():
        if colleague not in sector_reach:
            sector_reach[colleague] = []
        sector_reach[colleague].append((sector, cnt))

    conn.close()

    if not team_stats:
        return "No team network data found."

    sector_label = f" (filtered: {sector_filter})" if sector_filter else ""
    parts = [f"TEAM NETWORK INTELLIGENCE{sector_label}"]

    for member, total, seniors, movers, companies in team_stats:
        parts.append(f"\nπŸ“Š {member}:")
        parts.append(f"  Connections: {total} total, {seniors or 0} senior, {movers or 0} movers, {companies} unique companies")

        if member in hot_stats:
            hot_cnt, hot_cos = hot_stats[member]
            cos_list = hot_cos[:200] if hot_cos else ""
            parts.append(f"  Hot company connections: {hot_cnt} at [{cos_list}]")

        if member in li_stats:
            intel_cnt, avg_score, strong = li_stats[member]
            parts.append(f"  LinkedIn intel: {intel_cnt} contacts, avg relationship: {avg_score}, strong ties: {strong}")

        if member in sector_reach:
            top_sectors = sector_reach[member][:3]
            sectors_str = ", ".join(f"{s} ({c})" for s, c in top_sectors)
            parts.append(f"  Top sectors: {sectors_str}")

    # Deployment recommendations
    parts.append("\n🎯 DEPLOYMENT RECOMMENDATIONS:")
    if team_stats:
        # Best senior network
        senior_leader = max(team_stats, key=lambda x: x[2] or 0)
        parts.append(f"  - {senior_leader[0]} has the strongest senior network ({senior_leader[2] or 0} senior connections) β€” best for C-suite approaches")

        # Most hot company connections
        if hot_stats:
            hot_leader = max(hot_stats.items(), key=lambda x: x[1][0])
            parts.append(f"  - {hot_leader[0]} has the most connections at hot companies ({hot_leader[1][0]}) β€” should lead active pursuits")

        # Best relationship quality
        if li_stats:
            rel_leader = max(li_stats.items(), key=lambda x: x[1][1])
            parts.append(f"  - {rel_leader[0]} has the highest relationship quality (avg score: {rel_leader[1][1]}) β€” best for warm introductions")

    return "\n".join(parts)


COMPETITOR_CONSULTANCIES = [
    'deloitte', 'mckinsey', 'bcg', 'boston consulting', 'bain', 'kpmg', 'pwc',
    'pricewaterhousecoopers', 'ey ', 'ernst young', 'accenture', 'capgemini',
    'pa consulting', 'gate one', 'baringa', 'newton europe', 'oliver wyman',
    'moorhouse', 'north highland', 'clarasys', 'oaklin', 'changepoint',
    'mondrian alpha', 'argon', 'protiviti', 'slalom', 'wavestone',
]

TRANSFORMATION_ROLE_KEYWORDS = [
    'transformation', 'change manager', 'change management', 'change lead',
    'change director', 'programme manager', 'programme director', 'pmo',
    'project manager', 'business analyst', 'operating model',
    'organisational development', 'organizational development',
    'culture', 'people strategy', 'people lead', 'hr transformation',
    'workforce', 'restructuring', 'turnaround',
]


def _tool_detect_competitor_signals(params: dict) -> str:
    company_name = params.get("company_name", "")
    sector_filter = params.get("sector", "")
    conn = get_connection()
    cursor = conn.cursor()
    parts = ["COMPETITOR & MARKET ACTIVITY SIGNALS"]

    # Build optional company/sector filters
    company_condition = ""
    company_values = []
    if company_name:
        cid, matched = _fuzzy_match_company(company_name)
        if cid:
            company_condition = "AND c.id = ?"
            company_values = [cid]
            parts.append(f"\nFocused on: {matched}")
        else:
            parts.append(f"\n⚠️ '{company_name}' not found in tracked companies. Showing cross-portfolio scan.")

    sector_condition = ""
    sector_values = []
    if sector_filter:
        sector_condition = "AND LOWER(c.sector) LIKE ?"
        sector_values = [f"%{sector_filter.lower()}%"]

    # ---- 1. HIRING VELOCITY β€” companies posting 3+ transformation roles ----
    role_like_conditions = " OR ".join(["LOWER(j.job_title) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
    role_values = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]

    cursor.execute(f"""
        SELECT c.name, c.overall_score, c.network_status, COUNT(*) as role_count,
               GROUP_CONCAT(DISTINCT j.job_title) as titles
        FROM signals_jobs j
        JOIN companies c ON j.company_id = c.id
        WHERE ({role_like_conditions}) {company_condition} {sector_condition}
        GROUP BY c.id
        HAVING role_count >= 3
        ORDER BY role_count DESC
        LIMIT 15
    """, role_values + company_values + sector_values)
    hiring = cursor.fetchall()

    if hiring:
        parts.append(f"\nπŸ”΄ HIRING VELOCITY β€” {len(hiring)} companies with 3+ transformation roles (programme in flight, budget confirmed):")
        for name, score, net, count, titles in hiring:
            title_list = titles[:150] if titles else ''
            parts.append(f"  - {name} (score: {score}, network: {net or 'Cold'}) β€” {count} roles: {title_list}")
        parts.append("  β†’ Multiple transformation hires = active programme. A consultancy may already be involved. This is a piggyback opportunity.")

    # ---- 2. TRANSFORMATION ROLE HOLDERS β€” buyers at target companies ----
    if company_name and company_values:
        # Company-specific: find transformation contacts at this company
        cid_val = company_values[0]
        words = [w for w in company_name.lower().split() if len(w) >= 3]
        if words:
            word_conds = " AND ".join(["LOWER(ng.company) LIKE ?" for _ in words])
            word_vals = [f"%{w}%" for w in words]
            role_conds = " OR ".join(["LOWER(ng.position) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
            role_vals = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]

            cursor.execute(f"""
                SELECT ng.contact_name, ng.position, ng.company, ng.colleague_owner, ng.is_senior
                FROM network_graph ng
                WHERE ({word_conds}) AND ({role_conds})
                ORDER BY ng.is_senior DESC
                LIMIT 20
            """, word_vals + role_vals)
            buyers = cursor.fetchall()

            if buyers:
                parts.append(f"\nπŸ‘” TRANSFORMATION ROLE HOLDERS at matching companies ({len(buyers)} β€” these are the buyers/influencers):")
                for name, position, company, colleague, senior in buyers:
                    senior_tag = " [SENIOR]" if senior else ""
                    parts.append(f"  - {name} ({position}) at {company} β€” via {colleague}{senior_tag}")
    else:
        # Cross-portfolio: top companies by transformation role holder count
        role_conds = " OR ".join(["LOWER(ng.position) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
        role_vals = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]

        cursor.execute(f"""
            SELECT c.name, c.overall_score, COUNT(*) as holder_count,
                   SUM(ng.is_senior) as senior_holders
            FROM network_graph ng
            JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
            WHERE ({role_conds}) {company_condition} {sector_condition}
            GROUP BY c.id
            HAVING holder_count >= 2
            ORDER BY holder_count DESC
            LIMIT 10
        """, role_vals + company_values + sector_values)
        holders = cursor.fetchall()

        if holders:
            parts.append(f"\nπŸ‘” TRANSFORMATION ROLE HOLDERS β€” {len(holders)} tracked companies where we know the buyers:")
            for name, score, count, seniors in holders:
                parts.append(f"  - {name} (score: {score}) β€” {count} contacts in transformation roles ({seniors or 0} senior)")

    # ---- 3. TENDERS FOR CONSULTANCY SERVICES ----
    tender_keywords = ['consultancy', 'transformation', 'change management', 'programme management',
                       'leadership', 'coaching', 'culture', 'organisational development']
    tender_conds = " OR ".join(["LOWER(t.title) LIKE ? OR LOWER(t.matched_keywords) LIKE ?" for _ in tender_keywords])
    tender_vals = []
    for kw in tender_keywords:
        tender_vals.extend([f"%{kw}%", f"%{kw}%"])

    cursor.execute(f"""
        SELECT DISTINCT t.title, t.value, t.deadline, t.matched_keywords, t.days_to_deadline
        FROM signals_tenders t
        JOIN companies c ON t.company_id = c.id
        WHERE ({tender_conds}) {company_condition.replace('c.id', 't.company_id') if company_condition else ''} {sector_condition}
        ORDER BY t.value DESC
        LIMIT 10
    """, tender_vals + company_values + sector_values)
    tenders = cursor.fetchall()

    if tenders:
        parts.append(f"\nπŸ“‹ ACTIVE TENDERS for consultancy/transformation services ({len(tenders)}):")
        for title, value, deadline, keywords, days_left in tenders:
            value_str = f"Β£{value:,.0f}" if value else "undisclosed"
            deadline_str = deadline[:10] if deadline else "?"
            urgent = " ⚑ URGENT" if days_left and days_left < 14 else ""
            parts.append(f"  - {title[:80]} | {value_str} | deadline: {deadline_str}{urgent} | {keywords or ''}")

    # ---- 4. COMPETITOR FIRM CONNECTIONS β€” intelligence sources ----
    parts.append(f"\nπŸ” COMPETITOR INTELLIGENCE NETWORK:")
    for firm in ['deloitte', 'accenture', 'pwc', 'kpmg', 'capgemini', 'bcg', 'baringa', 'pa consulting']:
        cursor.execute("SELECT COUNT(*), GROUP_CONCAT(DISTINCT colleague_owner) FROM network_graph WHERE LOWER(company_normalized) LIKE ?",
                       (f"%{firm}%",))
        row = cursor.fetchone()
        if row and row[0] > 0:
            team = row[1][:60] if row[1] else ''
            parts.append(f"  - {firm.title()}: {row[0]} connections (team: {team})")

    parts.append("  β†’ These connections can provide market intel β€” who's pitching where, which engagements are ending, where there's dissatisfaction with incumbents.")

    conn.close()

    if len(parts) <= 2:
        parts.append("\nNo strong competitor signals detected. This could mean the market is untouched β€” or we need more data.")

    return "\n".join(parts)


def _tool_get_highest_conviction_leads(params: dict) -> str:
    min_conviction = params.get("min_conviction", 2)
    limit = min(params.get("limit", 15), 30)
    conn = get_connection()
    cursor = conn.cursor()

    # Get all tracked companies
    cursor.execute("SELECT id, name, overall_score, sector, network_status, signal_summary FROM companies ORDER BY overall_score DESC")
    companies = cursor.fetchall()

    leads = []
    for cid, name, score, sector, net, sig_summary in companies:
        signals = []
        evidence = []

        # Signal 1: HIRING VELOCITY β€” 3+ transformation job postings
        role_like_conditions = " OR ".join(["LOWER(job_title) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
        role_values = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]
        cursor.execute(f"""
            SELECT COUNT(*) FROM signals_jobs
            WHERE company_id = ? AND ({role_like_conditions})
        """, [cid] + role_values)
        job_count = cursor.fetchone()[0]
        if job_count >= 3:
            signals.append("hiring_velocity")
            evidence.append(f"{job_count} transformation roles posted")

        # Signal 2: LEADERSHIP CHANGE β€” news with leadership trigger
        cursor.execute("""
            SELECT COUNT(*) FROM signals_news
            WHERE company_id = ? AND LOWER(trigger_type) IN ('leadership', 'merger')
        """, (cid,))
        news_count = cursor.fetchone()[0]
        if news_count > 0:
            signals.append("leadership_change")
            evidence.append(f"{news_count} leadership/merger news")

        # Signal 3: POOR SENTIMENT β€” Glassdoor issues
        cursor.execute("""
            SELECT overall_rating, management_rating FROM signals_sentiment
            WHERE company_id = ? AND overall_rating <= 3.5
        """, (cid,))
        sent = cursor.fetchone()
        if sent:
            signals.append("sentiment_crisis")
            evidence.append(f"Glassdoor: {sent[0]}/5 overall, {sent[1]}/5 management")

        # Signal 4: PE/M&A β€” acquisition activity
        cursor.execute("""
            SELECT acquirer_name, deal_type FROM signals_pe_deals WHERE company_id = ?
        """, (cid,))
        pe = cursor.fetchone()
        if pe:
            signals.append("pe_acquisition")
            evidence.append(f"{pe[1]} by {pe[0]}")

        # Signal 5: ENGAGEMENT-VERIFIED CONTACTS β€” LinkedIn intel with activity
        cursor.execute("""
            SELECT COUNT(*) FROM signals_linkedin_intel
            WHERE company_id = ? AND (contact_active = 1 OR posts_about_transformation = 1)
        """, (cid,))
        engaged = cursor.fetchone()[0]
        if engaged > 0:
            signals.append("verified_engagement")
            evidence.append(f"{engaged} contacts with LinkedIn activity")

        # Signal 6: ACTIVE TENDERS
        cursor.execute("""
            SELECT COUNT(*) FROM signals_tenders
            WHERE company_id = ? AND (days_to_deadline > 0 OR days_to_deadline IS NULL)
        """, (cid,))
        tender_count = cursor.fetchone()[0]
        if tender_count > 0:
            signals.append("active_tenders")
            evidence.append(f"{tender_count} open tenders")

        # Signal 7: NETWORK DEPTH β€” 3+ connections including seniors
        cursor.execute("""
            SELECT COUNT(*), SUM(is_senior) FROM network_graph
            WHERE company_normalized = (SELECT name_normalized FROM companies WHERE id = ?)
        """, (cid,))
        net_row = cursor.fetchone()
        if net_row and net_row[0] and net_row[0] >= 3 and net_row[1] and net_row[1] >= 1:
            signals.append("network_depth")
            evidence.append(f"{net_row[0]} connections, {net_row[1]} senior")

        conviction = len(signals)
        if conviction >= min_conviction:
            leads.append({
                'name': name,
                'score': score,
                'sector': sector,
                'network': net,
                'conviction': conviction,
                'signals': signals,
                'evidence': evidence,
            })

    # Sort by conviction count, then overall score
    leads.sort(key=lambda x: (x['conviction'], x['score']), reverse=True)
    leads = leads[:limit]

    conn.close()

    if not leads:
        return f"No companies found with {min_conviction}+ independent conviction signals. Try lowering min_conviction."

    parts = [f"HIGHEST CONVICTION LEADS β€” {len(leads)} companies with {min_conviction}+ independent corroborating signals"]
    parts.append("Each signal is independently verifiable evidence of transformation opportunity.\n")

    for lead in leads:
        signal_icons = {
            'hiring_velocity': 'πŸ’Ό', 'leadership_change': 'πŸ‘”', 'sentiment_crisis': '⚠️',
            'pe_acquisition': 'πŸ’°', 'verified_engagement': 'βœ…', 'active_tenders': 'πŸ“‹',
            'network_depth': 'πŸ”—',
        }
        icons = " ".join(signal_icons.get(s, 'β€’') for s in lead['signals'])
        parts.append(f"{'='*60}")
        parts.append(f"{icons} {lead['name']} β€” CONVICTION: {lead['conviction']}/7 signals")
        parts.append(f"  Score: {lead['score']} | Sector: {lead['sector'] or '?'} | Network: {lead['network'] or 'Cold'}")
        for ev in lead['evidence']:
            parts.append(f"  βœ“ {ev}")

    parts.append(f"\n{'='*60}")
    parts.append("SIGNAL KEY: πŸ’Ό hiring velocity | πŸ‘” leadership change | ⚠️ sentiment crisis | πŸ’° PE deal | βœ… verified engagement | πŸ“‹ tenders | πŸ”— network depth")

    return "\n".join(parts)


def _draft_message(msg_type, **kwargs):
    """Generate a template-based LinkedIn message. No API calls."""
    contact_name = kwargs.get('contact_name', '')
    first_name = contact_name.split()[0] if contact_name else 'there'
    company = kwargs.get('company', 'your company')
    signals = kwargs.get('signals', '')

    if msg_type == 'connection':
        if signals:
            return f"Hi {first_name}, I work in transformation consulting at Curium Solutions. Noticed {company} is {signals} β€” would be great to connect and share perspectives."
        return f"Hi {first_name}, I work in transformation consulting at Curium Solutions. I'd love to connect β€” always interested in what's happening at {company}."

    elif msg_type == 'intro_ask':
        colleague = kwargs.get('colleague', 'them')
        position = kwargs.get('position', 'key contact')
        return f"Hi {colleague}, would you be able to introduce me to {contact_name} at {company}? They're a {position} and {company} is on our radar ({signals or 'high-scoring lead'}). Happy to draft something for you to forward."

    elif msg_type == 'mover':
        return f"Hi {first_name}, saw you've moved to {company} β€” congratulations! Would love to catch up and hear how the new role is going."

    elif msg_type == 'reconnect':
        return f"Hi {first_name}, hope you're well! It's been a while β€” I'd love to reconnect and hear what's happening at {company}. Coffee or a quick call?"

    elif msg_type == 'competitor_intel':
        hot_company = kwargs.get('hot_company', 'the market')
        return f"Hi {first_name}, hope all's well at {company}. Curious if you're hearing anything about {hot_company} β€” we're seeing some interesting signals. Always good to compare notes."

    return ""


def _tool_get_personal_action_plan(params: dict) -> str:
    from datetime import date
    colleague_name = params.get("colleague_name", "Piers")
    max_actions = min(params.get("max_actions", 10), 15)
    MAX_INTROS_PER_COLLEAGUE = 2

    conn = get_connection()
    cursor = conn.cursor()

    # Resolve colleague name (fuzzy match against team_members)
    cursor.execute("SELECT name, connections_count FROM team_members WHERE LOWER(name) LIKE ?", (f"%{colleague_name.lower()}%",))
    member_row = cursor.fetchone()
    if not member_row:
        conn.close()
        return f"No team member found matching '{colleague_name}'. Available: check team_members table."
    member_name = member_row[0]
    member_connections = member_row[1] or 0

    # Compute rank
    cursor.execute("SELECT name FROM team_members ORDER BY connections_count DESC")
    all_members = [r[0] for r in cursor.fetchall()]
    total_team = len(all_members)
    rank = all_members.index(member_name) + 1 if member_name in all_members else total_team

    # Recent connections (last 6 months)
    cursor.execute("""
        SELECT COUNT(*) FROM network_graph
        WHERE colleague_owner = ? AND date_connected >= date('now', '-6 months')
    """, (member_name,))
    recent_connections = cursor.fetchone()[0]

    # Hot companies where this member has connections
    cursor.execute("""
        SELECT DISTINCT c.name FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50 AND ng.colleague_owner = ?
    """, (member_name,))
    my_hot_companies = set(r[0] for r in cursor.fetchall())

    # Hot companies where ANY team member has connections
    cursor.execute("""
        SELECT DISTINCT c.name FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50
    """)
    team_hot_companies = set(r[0] for r in cursor.fetchall())

    # LinkedIn intel count for data gap analysis
    cursor.execute("SELECT COUNT(*) FROM signals_linkedin_intel WHERE LOWER(colleague_name) LIKE ?",
                   (f"%{member_name.lower()}%",))
    li_intel_count = cursor.fetchone()[0]

    actions = []

    # =========================================================================
    # PRIORITY 1: Engage with verified contacts (highest value, lowest effort)
    # =========================================================================
    cursor.execute("""
        SELECT li.contact_name, li.contact_title, li.colleague_name, li.contact_active,
               li.posts_about_transformation, li.recommended_action, c.name, c.overall_score
        FROM signals_linkedin_intel li
        JOIN companies c ON li.company_id = c.id
        WHERE LOWER(li.colleague_name) LIKE ?
          AND (li.contact_active = 1 OR li.posts_about_transformation = 1)
        ORDER BY c.overall_score DESC
    """, (f"%{member_name.lower()}%",))
    for row in cursor.fetchall():
        contact, title, colleague, active, posts_transf, action, company, score = row
        if posts_transf:
            actions.append({
                'priority': 1, 'type': 'engage', 'icon': 'πŸ’¬',
                'action': f"Comment on {contact}'s recent posts about transformation at {company} (score {score})",
                'reason': f"Verified active, posts about transformation β€” {action}",
                'company': company, 'score': score,
                'draft': f"Great post, {contact.split()[0] if contact else 'there'}! This resonates with what we're seeing across transformation programmes β€” especially the focus on [topic]. Would love to compare notes.",
            })
        elif active:
            actions.append({
                'priority': 1, 'type': 'message', 'icon': 'βœ‰οΈ',
                'action': f"Message {contact} ({title}) at {company} β€” they're active on LinkedIn (score {score})",
                'reason': f"Active contact, engagement verified β€” {action}",
                'company': company, 'score': score,
                'draft': _draft_message('reconnect', contact_name=contact, company=company),
            })

    # =========================================================================
    # PRIORITY 1.5: Movers β€” contacts who changed companies (warmest reconnect)
    # =========================================================================
    cursor.execute("""
        SELECT ng.contact_name, ng.position, ng.company, ng.date_connected,
               COALESCE(c.overall_score, 0) as score, c.signal_summary
        FROM network_graph ng
        LEFT JOIN companies c ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE ng.colleague_owner = ? AND ng.is_new_company = 1
        ORDER BY COALESCE(c.overall_score, 0) DESC
        LIMIT 3
    """, (member_name,))
    for row in cursor.fetchall():
        contact, position, company, date_conn, score, signals = row
        score_str = f" (score {score})" if score else ""
        actions.append({
            'priority': 1, 'type': 'mover', 'icon': 'πŸš€',
            'action': f"Congratulate {contact} on their move to {company}{score_str} β€” reconnect and explore",
            'reason': f"Your contact changed companies β€” warmest possible reconnection",
            'company': company, 'score': score or 0,
            'draft': _draft_message('mover', contact_name=contact, company=company),
        })

    # =========================================================================
    # PRIORITY 2: Request warm intros to hot companies via teammates
    #             CAPPED: max 2 intros per colleague to diversify
    # =========================================================================
    cursor.execute("""
        SELECT c.name, c.overall_score, c.sector, c.signal_summary,
               ng.colleague_owner, ng.contact_name, ng.position, ng.is_senior
        FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50
          AND ng.colleague_owner != ?
          AND LOWER(c.name_normalized) NOT IN (
            SELECT LOWER(company_normalized) FROM network_graph WHERE colleague_owner = ?
          )
        ORDER BY c.overall_score DESC, ng.is_senior DESC
    """, (member_name, member_name))
    seen_intro_companies = set()
    colleague_intro_count = {}
    for row in cursor.fetchall():
        company, score, sector, signal_summary, via_colleague, contact, position, is_senior = row
        if company in seen_intro_companies:
            continue
        if colleague_intro_count.get(via_colleague, 0) >= MAX_INTROS_PER_COLLEAGUE:
            continue
        colleague_intro_count[via_colleague] = colleague_intro_count.get(via_colleague, 0) + 1
        seen_intro_companies.add(company)
        senior_tag = " [SENIOR]" if is_senior else ""
        context = sector or ((signal_summary[:50] + '...') if signal_summary else 'tracked company')
        actions.append({
            'priority': 2, 'type': 'intro', 'icon': '🀝',
            'action': f"Ask {via_colleague} for intro to {contact} ({position}){senior_tag} at {company} (score {score})",
            'reason': f"Hot company β€” {context}. You have no connections, {via_colleague} does",
            'company': company, 'score': score,
            'draft': _draft_message('intro_ask', contact_name=contact, company=company,
                                    colleague=via_colleague, position=position or 'key contact',
                                    signals=context),
        })

    # =========================================================================
    # PRIORITY 2.5: Competitor intelligence β€” contacts at rival consultancies
    # =========================================================================
    # Filter to firms with 3+ char names to avoid false positives (e.g. 'ey ' matching 'bentley')
    safe_competitors = [f for f in COMPETITOR_CONSULTANCIES if len(f.strip()) >= 4]
    competitor_like = " OR ".join(["LOWER(company_normalized) LIKE ?" for _ in safe_competitors])
    competitor_vals = [f"%{firm.strip()}%" for firm in safe_competitors]
    cursor.execute(f"""
        SELECT contact_name, position, company, is_senior FROM network_graph
        WHERE colleague_owner = ? AND ({competitor_like})
          AND (is_senior = 1 OR LOWER(position) LIKE '%director%'
               OR LOWER(position) LIKE '%partner%' OR LOWER(position) LIKE '%managing%')
        ORDER BY is_senior DESC
    """, [member_name] + competitor_vals)
    competitor_contacts = cursor.fetchall()

    # Find hot companies with hiring velocity to ask about
    role_like_conditions = " OR ".join(["LOWER(j.job_title) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
    role_values = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]
    cursor.execute(f"""
        SELECT c.name, c.overall_score, COUNT(*) as role_count
        FROM signals_jobs j
        JOIN companies c ON j.company_id = c.id
        WHERE c.overall_score >= 50 AND ({role_like_conditions})
        GROUP BY c.id HAVING role_count >= 3
        ORDER BY c.overall_score DESC LIMIT 5
    """, role_values)
    hiring_hot = cursor.fetchall()

    competitor_action_count = 0
    for contact, position, firm, is_senior in competitor_contacts:
        if competitor_action_count >= 2:
            break
        hot_target = hiring_hot[competitor_action_count] if competitor_action_count < len(hiring_hot) else None
        hot_name = hot_target[0] if hot_target else "the market"
        hot_score = hot_target[1] if hot_target else 0
        actions.append({
            'priority': 2, 'type': 'competitor_intel', 'icon': 'πŸ•΅οΈ',
            'action': f"Reach out to {contact} ({position}) at {firm} β€” ask what they're hearing about {hot_name}" + (f" (score {hot_score})" if hot_score else ""),
            'reason': f"Your contact at a competitor firm β€” potential intel on who's pitching where",
            'company': firm, 'score': hot_score,
            'draft': _draft_message('competitor_intel', contact_name=contact, company=firm, hot_company=hot_name),
        })
        competitor_action_count += 1

    # =========================================================================
    # PRIORITY 3: Connect with transformation role holders at hot companies
    # =========================================================================
    cursor.execute(f"""
        SELECT j.job_title, c.name, c.overall_score, c.sector, c.signal_summary
        FROM signals_jobs j
        JOIN companies c ON j.company_id = c.id
        WHERE c.overall_score >= 40 AND ({role_like_conditions})
        ORDER BY c.overall_score DESC
    """, role_values)
    seen_connect_companies = set()
    for row in cursor.fetchall():
        title, company, score, sector, signals = row
        if company in seen_connect_companies:
            continue
        seen_connect_companies.add(company)
        signal_snippet = (signals or '')[:60]
        context = sector or ((signals[:50] + '...') if signals else 'transformation')
        actions.append({
            'priority': 3, 'type': 'connect', 'icon': 'πŸ”—',
            'action': f"Send connection request to {title} at {company} (score {score})",
            'reason': f"Active transformation role β€” {context}",
            'company': company, 'score': score,
            'draft': _draft_message('connection', contact_name=title, company=company,
                                    signals=signal_snippet if signal_snippet else ''),
        })

    # =========================================================================
    # PRIORITY 4: Reconnect with dormant senior connections
    # =========================================================================
    cursor.execute("""
        SELECT ng.contact_name, ng.position, ng.company, c.overall_score, c.sector, c.signal_summary
        FROM network_graph ng
        JOIN companies c ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE ng.colleague_owner = ? AND ng.is_senior = 1 AND c.overall_score >= 40
        ORDER BY c.overall_score DESC
        LIMIT 3
    """, (member_name,))
    seen_reconnect = set()
    for row in cursor.fetchall():
        contact, position, company, score, sector, signals = row
        if contact in seen_reconnect:
            continue
        seen_reconnect.add(contact)
        context = sector or ((signals[:50] + '...') if signals else 'tracked company')
        actions.append({
            'priority': 4, 'type': 'reconnect', 'icon': 'πŸ”„',
            'action': f"Reconnect with {contact} ({position}) at {company} β€” senior contact, score {score}",
            'reason': f"Your senior connection β€” {context}",
            'company': company, 'score': score,
            'draft': _draft_message('reconnect', contact_name=contact, company=company),
        })

    # =========================================================================
    # PRIORITY 5: Content engagement for visibility
    # =========================================================================
    cursor.execute("""
        SELECT n.headline, c.name, c.overall_score, c.sector, n.trigger_type
        FROM signals_news n
        JOIN companies c ON n.company_id = c.id
        WHERE c.overall_score >= 50
        ORDER BY c.overall_score DESC
        LIMIT 10
    """)
    seen_news_companies = set()
    for row in cursor.fetchall():
        headline, company, score, sector, trigger = row
        if company in seen_news_companies:
            continue
        seen_news_companies.add(company)
        actions.append({
            'priority': 5, 'type': 'content', 'icon': 'πŸ“°',
            'action': f"Share/comment on news: \"{headline[:80]}\" about {company} (score {score})",
            'reason': f"Position Curium's expertise in {sector or 'transformation'} β€” {trigger or 'industry'} trigger",
            'company': company, 'score': score,
            'draft': '',
        })

    # =========================================================================
    # SCAN RECOMMENDATIONS: Fill data gaps
    # =========================================================================
    cursor.execute("""
        SELECT ng.contact_name, ng.position, ng.company, c.overall_score
        FROM network_graph ng
        JOIN companies c ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE ng.colleague_owner = ? AND ng.is_senior = 1 AND c.overall_score >= 40
          AND ng.contact_name NOT IN (
            SELECT COALESCE(contact_name, '') FROM signals_linkedin_intel
            WHERE LOWER(colleague_name) LIKE ?
          )
        ORDER BY c.overall_score DESC LIMIT 5
    """, (member_name, f"%{member_name.lower()}%"))
    scan_recs = cursor.fetchall()

    # If few senior contacts at tracked companies, broaden to sleeping giants
    if len(scan_recs) < 3:
        cursor.execute("""
            SELECT ng.contact_name, ng.position, ng.company_normalized, 0 as score
            FROM network_graph ng
            WHERE ng.colleague_owner = ? AND ng.is_senior = 1
              AND ng.company_normalized IN (
                SELECT company_normalized FROM network_graph
                GROUP BY company_normalized HAVING COUNT(*) >= 3
              )
              AND ng.contact_name NOT IN (
                SELECT COALESCE(contact_name, '') FROM signals_linkedin_intel
                WHERE LOWER(colleague_name) LIKE ?
              )
            ORDER BY ng.date_connected DESC LIMIT ?
        """, (member_name, f"%{member_name.lower()}%", 5 - len(scan_recs)))
        scan_recs.extend(cursor.fetchall())

    conn.close()

    # Sort by priority then score, limit to max_actions
    actions.sort(key=lambda a: (a['priority'], -a['score']))
    actions = actions[:max_actions]

    # Build output
    today = date.today().strftime("%d %B %Y")
    parts = [
        f"{'='*60}",
        f"{member_name.upper()}'S DAILY LINKEDIN ACTION PLAN β€” {today}",
        f"{'='*60}",
        f"",
        f"NETWORK POSITION:",
        f"  Rank: {rank} of {total_team} | {member_connections:,} connections | {recent_connections} new in last 6 months",
        f"  Hot companies connected: {len(my_hot_companies)} | Team total: {len(team_hot_companies)} | Gap: {len(team_hot_companies - my_hot_companies)} companies",
        f"  LinkedIn intel contacts: {li_intel_count}" + (" β€” run profile scans to unlock engagement actions!" if li_intel_count < 5 else ""),
        f"",
    ]

    if not actions:
        parts.append("No specific actions generated β€” try broadening criteria or checking data availability.")
        return "\n".join(parts)

    # Group by priority
    priority_labels = {
        1: "ENGAGE VERIFIED CONTACTS / RECONNECT MOVERS",
        2: "REQUEST WARM INTROS / COMPETITOR INTEL",
        3: "NEW CONNECTION REQUESTS",
        4: "RECONNECT WITH DORMANT SENIORS",
        5: "CONTENT ENGAGEMENT",
    }

    current_priority = None
    action_num = 0
    for a in actions:
        if a['priority'] != current_priority:
            current_priority = a['priority']
            parts.append(f"\n--- Priority {current_priority}: {priority_labels.get(current_priority, 'OTHER')} ---")
        action_num += 1
        parts.append(f"  {action_num}. {a['icon']} {a['action']}")
        parts.append(f"     Why: {a['reason']}")
        if a.get('draft'):
            parts.append(f"     πŸ“ Draft: \"{a['draft']}\"")

    # Scan recommendations (separate section, not numbered)
    if scan_recs:
        parts.append(f"\n{'='*60}")
        parts.append(f"πŸ“Š DATA GAP: You have {li_intel_count} LinkedIn intel contact(s). Run a profile scan on these to unlock Priority 1 actions:")
        for rec in scan_recs:
            contact, position, company, score = rec
            score_str = f" (score {score})" if score else ""
            parts.append(f"  - {contact} ({position or '?'}) at {company}{score_str}")

    parts.append(f"\n{'='*60}")
    parts.append(f"Total actions: {len(actions)} | Estimated time: 15-20 minutes")
    parts.append(f"Focus on Priority 1-2 first β€” these have the highest evidence and impact.")

    return "\n".join(parts)


# =============================================================================
# SYSTEM PROMPT
# =============================================================================

SYSTEM_PROMPT_TEMPLATE = """You are the **Curium Intelligence Assistant**, an AI analyst embedded in Curium Solutions' lead intelligence platform. You are PROACTIVELY STRATEGIC β€” don't just answer questions, surface hidden opportunities and cross-reference insights.

ABOUT CURIUM:
Curium Solutions is a UK transformation consultancy with two practice areas:
- **Transformation Delivery (TD)**: Project/programme management, change management, business analysis, TMO/PMO, operating models, agile, M&A integration, service desk
- **Culture & Capability (CC)**: Executive coaching, leadership strategy, culture diagnostics, team profiling (CODE 3i), facilitation, resilience, 1-to-1 coaching, dysfunctional teams, mindset & behaviour
- **CODE 3i**: Digital psychometric product for team dynamics assessment

YOUR DATA:
{context_summary}

CRITICAL DATA INSIGHT:
The `companies` table tracks ~160 formally scored companies. But `network_graph` contains 30,000+ connections across 17,000+ companies. This means the vast majority of the team's network is UNTRACKED. When a company isn't found in the tracked companies table, ALWAYS check network_graph β€” there may be strong connections there. The `get_sleeping_giants` tool specifically finds these hidden opportunities.

YOUR TOOLS:
You have 13 tools to query the database. Use them strategically:
- **search_companies**: Filter tracked companies by name, score, sector, signal type, service line, network status
- **get_company_detail**: Get full dossier for one company (all signals, contacts, scores)
- **find_connections**: Find team members who know people at a specific company
- **find_person**: Search for a person by name across the entire network
- **get_movers**: Find contacts who changed companies (warm re-engagement leads)
- **run_sql**: Power-user raw SQL for complex cross-table queries
- **find_warm_routes**: Find routes into a company with evidence quality tiers (verified engagement β†’ scored β†’ raw connections)
- **get_strategic_opportunities**: Cross-reference all signals + network data β€” finds convergence, engagement-verified leads, PE plays, sentiment combos
- **get_sleeping_giants**: Find untracked companies with activity signals β€” recent connection growth or strong senior access
- **get_network_intelligence**: Team-level analytics β€” who should lead which pursuits, sector reach, deployment recommendations
- **detect_competitor_signals**: Detect where OTHER consultancies are active β€” hiring velocity (3+ transformation roles = programme in flight), transformation role holders we know, tenders, competitor firm connections
- **get_highest_conviction_leads**: Multi-signal conviction scoring β€” finds companies with the most independent corroborating signals (hiring + leadership change + sentiment + PE + engagement + tenders + network depth)
- **get_personal_action_plan**: Generate a daily LinkedIn action plan for a specific team member. Cross-references their network gaps with hot companies, finds warm intro opportunities via teammates, identifies engagement targets. Default: Piers. Use when asked about "what should I do on LinkedIn?" or "my action plan" or "help me network".

DATA QUALITY β€” CRITICAL:
There are THREE tiers of evidence quality. You MUST be transparent about which tier you're drawing from:
1. **VERIFIED ENGAGEMENT** (signals_linkedin_intel where contact_active=1 or posts_about_transformation=1 or last_interaction_days>=0) β€” these contacts have actual LinkedIn activity evidence. This is the MOST reliable data.
2. **SCORED NETWORK** (signals_network) β€” contacts matched by role and seniority to tracked companies. Moderate evidence.
3. **RAW CONNECTIONS** (network_graph) β€” LinkedIn connections only. Being connected does NOT mean the relationship is active. NEVER call these "warm" unless there is engagement evidence. Say "connected via LinkedIn" not "warm route".

When presenting contacts, ALWAYS state the evidence tier. Never inflate confidence beyond what the data supports.
A LinkedIn connection with zero engagement is NOT a warm lead β€” it's just a connection.

PROACTIVE BEHAVIOUR:
- When asked about a company, check for routes AND mention related opportunities β€” but be clear about evidence quality
- When asked about connections, ALWAYS mention engagement status (active/dormant/unverified) alongside company score and signals
- Proactively suggest cross-references but distinguish between verified and unverified data
- When connections exist but have no engagement data, recommend running a LinkedIn profile scan before reaching out
- When asked "where should we focus?", prioritise opportunities with engagement evidence over raw connection count
- Always think about WHO on the team should lead each approach β€” use `get_network_intelligence` if needed
- When any team member asks about their personal networking or LinkedIn activity, always use get_personal_action_plan β€” don't just list connections, give them specific actions

RESPONSE STYLE:
- British English, direct, actionable
- Use bullet points, be specific with names and numbers
- Always reference actual data β€” never fabricate names, companies, or connections
- When suggesting a route in, name the specific colleague, contact, AND the evidence quality
- If data is thin or unverified, say so honestly rather than speculating β€” "we have a connection but no engagement data" is more useful than false confidence
- Keep responses focused and practical β€” this is for busy BD consultants
- End strategic analyses with a clear "RECOMMENDED NEXT STEPS" section"""


def build_system_prompt(context_summary: str) -> str:
    return SYSTEM_PROMPT_TEMPLATE.format(context_summary=context_summary)


# =============================================================================
# PROACTIVE BRIEFING GENERATOR
# =============================================================================

def generate_proactive_briefing() -> dict:
    """Pre-compute strategic intelligence for the UI briefing cards.
    Pure SQLite queries β€” no AI calls, fast, computed once per session.
    """
    conn = get_connection()
    cursor = conn.cursor()
    briefing = {
        'sleeping_giants': [],
        'ready_to_approach': [],
        'signal_storms': [],
        'pe_plays': [],
        'hiring_velocity': [],
        'highest_conviction': [],
    }

    # 1. Sleeping Giants β€” untracked companies with ACTIVITY SIGNALS
    #    Recent connections = active relationship building, not just historical noise
    try:
        cursor.execute("""
            SELECT ng.company_normalized, COUNT(*) as total,
                   SUM(ng.is_senior) as seniors,
                   SUM(CASE WHEN ng.date_connected >= date('now', '-6 months') THEN 1 ELSE 0 END) as recent_connections,
                   GROUP_CONCAT(DISTINCT ng.colleague_owner) as team
            FROM network_graph ng
            LEFT JOIN companies c ON LOWER(c.name_normalized) = LOWER(ng.company_normalized)
            WHERE c.id IS NULL AND ng.company_normalized IS NOT NULL AND ng.company_normalized != '' AND LOWER(ng.company_normalized) NOT IN ('curium', 'self employed', 'freelance', 'retired', 'unemployed', '') AND LOWER(ng.company_normalized) NOT LIKE '%curium solutions%'
            GROUP BY ng.company_normalized
            HAVING total >= 3 AND (recent_connections > 0 OR seniors >= 3)
            ORDER BY recent_connections DESC, seniors DESC, total DESC
            LIMIT 5
        """)
        for row in cursor.fetchall():
            briefing['sleeping_giants'].append({
                'company': row[0],
                'connections': row[1],
                'seniors': row[2] or 0,
                'recent': row[3] or 0,
                'team': row[4] or '',
            })
    except Exception:
        pass

    # 2. Ready to Approach β€” hot leads with ENGAGEMENT-VERIFIED contacts first
    try:
        cursor.execute("""
            SELECT c.name, c.overall_score, c.network_status, c.best_contact, c.best_colleague, c.sector,
                   (SELECT COUNT(*) FROM signals_linkedin_intel li
                    WHERE li.company_id = c.id AND (li.contact_active = 1 OR li.posts_about_transformation = 1)) as engaged_contacts,
                   (SELECT COUNT(*) FROM signals_linkedin_intel li WHERE li.company_id = c.id) as total_intel
            FROM companies c
            WHERE c.overall_score >= 50 AND c.network_status != 'Cold' AND c.network_status IS NOT NULL
            ORDER BY engaged_contacts DESC, c.overall_score DESC
            LIMIT 5
        """)
        for row in cursor.fetchall():
            engaged = row[6] or 0
            total_intel = row[7] or 0
            if engaged > 0:
                evidence = f"{engaged} contacts with verified engagement"
            elif total_intel > 0:
                evidence = f"{total_intel} contacts scanned, none active"
            else:
                evidence = "connected but not scanned"
            briefing['ready_to_approach'].append({
                'company': row[0],
                'score': row[1],
                'network_status': row[2],
                'best_contact': row[3] or 'Unknown',
                'best_colleague': row[4] or 'Unknown',
                'sector': row[5] or 'Unknown',
                'evidence': evidence,
            })
    except Exception:
        pass

    # 3. Signal Storms β€” companies with 3+ converging signal types
    try:
        cursor.execute("SELECT c.id, c.name, c.overall_score, c.sector, c.network_status FROM companies c ORDER BY c.overall_score DESC")
        companies = cursor.fetchall()
        signal_tables = [
            ("signals_jobs", "Jobs"),
            ("signals_news", "News"),
            ("signals_tenders", "Tenders"),
            ("signals_pe_deals", "PE/M&A"),
            ("signals_sentiment", "Sentiment"),
            ("signals_annual_reports", "Reports"),
            ("signals_linkedin_intel", "LinkedIn"),
        ]
        for cid, name, score, sector, net in companies:
            signals = []
            for tbl, label in signal_tables:
                try:
                    cursor.execute(f"SELECT 1 FROM {tbl} WHERE company_id = ? LIMIT 1", (cid,))
                    if cursor.fetchone():
                        signals.append(label)
                except Exception:
                    pass
            if len(signals) >= 3:
                briefing['signal_storms'].append({
                    'company': name,
                    'score': score,
                    'sector': sector or 'Unknown',
                    'network': net or 'Cold',
                    'signal_types': signals,
                })
            if len(briefing['signal_storms']) >= 5:
                break
    except Exception:
        pass

    # 4. PE Integration Plays β€” PE-backed companies with network connections
    try:
        cursor.execute("""
            SELECT c.name, c.overall_score, pe.acquirer_name, pe.deal_type,
                   c.network_status, c.best_contact, c.best_colleague
            FROM signals_pe_deals pe
            JOIN companies c ON pe.company_id = c.id
            WHERE c.network_status != 'Cold' AND c.network_status IS NOT NULL
            ORDER BY c.overall_score DESC
            LIMIT 5
        """)
        for row in cursor.fetchall():
            briefing['pe_plays'].append({
                'company': row[0],
                'score': row[1],
                'acquirer': row[2] or 'Unknown',
                'deal_type': row[3] or 'Unknown',
                'network_status': row[4],
                'best_contact': row[5] or 'Unknown',
                'best_colleague': row[6] or 'Unknown',
            })
    except Exception:
        pass

    # 5. Hiring Velocity β€” companies with 3+ transformation roles (programme in flight)
    try:
        role_like_conditions = " OR ".join(["LOWER(j.job_title) LIKE ?" for _ in TRANSFORMATION_ROLE_KEYWORDS])
        role_values = [f"%{kw}%" for kw in TRANSFORMATION_ROLE_KEYWORDS]

        cursor.execute(f"""
            SELECT c.name, c.overall_score, c.network_status, COUNT(*) as role_count,
                   GROUP_CONCAT(DISTINCT j.job_title) as titles
            FROM signals_jobs j
            JOIN companies c ON j.company_id = c.id
            WHERE ({role_like_conditions})
            GROUP BY c.id
            HAVING role_count >= 3
            ORDER BY role_count DESC
            LIMIT 5
        """, role_values)
        for row in cursor.fetchall():
            titles = (row[4] or '')[:120]
            briefing['hiring_velocity'].append({
                'company': row[0],
                'score': row[1],
                'network': row[2] or 'Cold',
                'role_count': row[3],
                'titles': titles,
            })
    except Exception:
        pass

    # 6. Highest Conviction β€” companies with 3+ independent signal types
    try:
        cursor.execute("SELECT id, name, overall_score, sector, network_status FROM companies ORDER BY overall_score DESC")
        all_cos = cursor.fetchall()
        for cid, cname, cscore, csector, cnet in all_cos:
            signal_count = 0
            signal_names = []

            # Check each independent signal source
            for tbl, label in [
                ("signals_jobs", "hiring"), ("signals_news", "news"),
                ("signals_sentiment", "sentiment"), ("signals_pe_deals", "PE/M&A"),
                ("signals_tenders", "tenders"),
            ]:
                try:
                    cursor.execute(f"SELECT 1 FROM {tbl} WHERE company_id = ? LIMIT 1", (cid,))
                    if cursor.fetchone():
                        signal_count += 1
                        signal_names.append(label)
                except Exception:
                    pass

            # Check engagement-verified contacts
            cursor.execute("""
                SELECT COUNT(*) FROM signals_linkedin_intel
                WHERE company_id = ? AND (contact_active = 1 OR posts_about_transformation = 1)
            """, (cid,))
            engaged = cursor.fetchone()[0]
            if engaged > 0:
                signal_count += 1
                signal_names.append(f"engagement ({engaged})")

            # Check network depth
            cursor.execute("""
                SELECT COUNT(*), SUM(is_senior) FROM network_graph
                WHERE company_normalized = (SELECT name_normalized FROM companies WHERE id = ?)
            """, (cid,))
            net_r = cursor.fetchone()
            if net_r and net_r[0] and net_r[0] >= 3 and net_r[1] and net_r[1] >= 1:
                signal_count += 1
                signal_names.append(f"network ({net_r[0]} conns)")

            if signal_count >= 3:
                briefing['highest_conviction'].append({
                    'company': cname,
                    'score': cscore,
                    'sector': csector or 'Unknown',
                    'network': cnet or 'Cold',
                    'conviction': signal_count,
                    'signals': signal_names,
                })

            if len(briefing['highest_conviction']) >= 5:
                break
    except Exception:
        pass

    # 7. Personal briefing for default team member (Piers)
    try:
        briefing['personal'] = _generate_personal_briefing(cursor)
    except Exception:
        briefing['personal'] = {}

    conn.close()
    return briefing


def _generate_personal_briefing(cursor, colleague_name="Piers") -> dict:
    """Pre-compute personal network intel for a team member."""
    # Resolve member
    cursor.execute("SELECT name, connections_count FROM team_members WHERE LOWER(name) LIKE ?",
                   (f"%{colleague_name.lower()}%",))
    member_row = cursor.fetchone()
    if not member_row:
        return {}
    member_name = member_row[0]
    member_connections = member_row[1] or 0

    # Rank
    cursor.execute("SELECT name FROM team_members ORDER BY connections_count DESC")
    all_members = [r[0] for r in cursor.fetchall()]
    total_team = len(all_members)
    rank = all_members.index(member_name) + 1 if member_name in all_members else total_team

    # Recent connections
    cursor.execute("""
        SELECT COUNT(*) FROM network_graph
        WHERE colleague_owner = ? AND date_connected >= date('now', '-6 months')
    """, (member_name,))
    recent_connections = cursor.fetchone()[0]

    # Hot companies where this member has connections
    cursor.execute("""
        SELECT DISTINCT c.name FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50 AND ng.colleague_owner = ?
    """, (member_name,))
    my_hot = set(r[0] for r in cursor.fetchall())

    # Hot companies where ANY team member has connections
    cursor.execute("""
        SELECT DISTINCT c.name FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50
    """)
    team_hot = set(r[0] for r in cursor.fetchall())

    # Top 3 warm intro opportunities (hot companies where member has no connection but teammates do)
    cursor.execute("""
        SELECT c.name, c.overall_score, ng.colleague_owner, ng.contact_name, ng.position, ng.is_senior
        FROM companies c
        JOIN network_graph ng ON LOWER(ng.company_normalized) = LOWER(c.name_normalized)
        WHERE c.overall_score >= 50
          AND ng.colleague_owner != ?
          AND LOWER(c.name_normalized) NOT IN (
            SELECT LOWER(company_normalized) FROM network_graph WHERE colleague_owner = ?
          )
        ORDER BY c.overall_score DESC, ng.is_senior DESC
    """, (member_name, member_name))
    seen_companies = set()
    colleague_count = {}
    top_intros = []
    for row in cursor.fetchall():
        company, score, via_colleague, contact, position, is_senior = row
        if company in seen_companies:
            continue
        if colleague_count.get(via_colleague, 0) >= 2:
            continue
        colleague_count[via_colleague] = colleague_count.get(via_colleague, 0) + 1
        seen_companies.add(company)
        top_intros.append({
            'company': company,
            'score': score,
            'via_colleague': via_colleague,
            'contact': contact,
            'position': position or '',
        })
        if len(top_intros) >= 3:
            break

    # Top 3 action previews
    top_actions = []
    for intro in top_intros:
        top_actions.append(
            f"Ask {intro['via_colleague']} for intro to {intro['contact']} at {intro['company']} (score {intro['score']})"
        )

    # Check for verified engagement contacts
    cursor.execute("""
        SELECT li.contact_name, c.name FROM signals_linkedin_intel li
        JOIN companies c ON li.company_id = c.id
        WHERE LOWER(li.colleague_name) LIKE ?
          AND (li.contact_active = 1 OR li.posts_about_transformation = 1)
        ORDER BY c.overall_score DESC LIMIT 3
    """, (f"%{member_name.lower()}%",))
    for row in cursor.fetchall():
        contact, company = row
        top_actions.insert(0, f"Engage with {contact}'s posts at {company}")

    top_actions = top_actions[:3]

    return {
        'name': member_name,
        'rank': rank,
        'total_team': total_team,
        'connections': member_connections,
        'recent_connections': recent_connections,
        'hot_companies_connected': len(my_hot),
        'hot_companies_team_has': len(team_hot),
        'top_intro_opportunities': top_intros,
        'top_actions_preview': top_actions,
    }


# =============================================================================
# AGENTIC QUERY LOOP
# =============================================================================

MAX_TOOL_ROUNDS = 5


def run_query(user_message: str, conversation_history: list, context_summary: str) -> tuple:
    """
    Run an agentic query with tool use.

    Args:
        user_message: The user's question
        conversation_history: List of {"role": "user"/"assistant", "content": str} dicts
        context_summary: Pre-built context summary string

    Returns:
        (response_text, updated_conversation_history)
    """
    client = get_client()
    system_prompt = build_system_prompt(context_summary)

    # Build messages for the API call: history + new user message
    api_messages = []
    for msg in conversation_history:
        api_messages.append({"role": msg["role"], "content": msg["content"]})
    api_messages.append({"role": "user", "content": user_message})

    # Agentic loop
    for _round in range(MAX_TOOL_ROUNDS):
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=4096,
            system=system_prompt,
            tools=TOOLS,
            messages=api_messages,
        )

        # Check if we're done (no tool use)
        if response.stop_reason == "end_turn":
            # Extract text from content blocks
            text_parts = []
            for block in response.content:
                if block.type == "text":
                    text_parts.append(block.text)
            final_text = "\n".join(text_parts)

            # Update conversation history with simplified text
            updated_history = list(conversation_history)
            updated_history.append({"role": "user", "content": user_message})
            updated_history.append({"role": "assistant", "content": final_text})

            return final_text, updated_history

        # Tool use: execute tools and feed results back
        if response.stop_reason == "tool_use":
            # Add assistant message with all content blocks (text + tool_use)
            api_messages.append({"role": "assistant", "content": response.content})

            # Execute each tool call and build tool results
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    result = execute_tool(block.name, block.input)
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result,
                    })

            api_messages.append({"role": "user", "content": tool_results})
            continue

        # Unexpected stop reason β€” extract what we can
        text_parts = []
        for block in response.content:
            if block.type == "text":
                text_parts.append(block.text)
        final_text = "\n".join(text_parts) if text_parts else "I wasn't able to complete that query. Please try rephrasing."

        updated_history = list(conversation_history)
        updated_history.append({"role": "user", "content": user_message})
        updated_history.append({"role": "assistant", "content": final_text})
        return final_text, updated_history

    # Exceeded max rounds
    text_parts = []
    for block in response.content:
        if block.type == "text":
            text_parts.append(block.text)
    final_text = "\n".join(text_parts) if text_parts else "Query required too many lookups. Try a more specific question."

    updated_history = list(conversation_history)
    updated_history.append({"role": "user", "content": user_message})
    updated_history.append({"role": "assistant", "content": final_text})
    return final_text, updated_history