Spaces:
Running

File size: 102,702 Bytes
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
2fd367f
cd61bf7
 
895011f
cd61bf7
 
a76cbc6
cd61bf7
 
 
2400a38
e3cd75f
2400a38
e3cd75f
 
2400a38
 
 
 
 
e3cd75f
 
2400a38
 
e3cd75f
2400a38
 
 
 
 
 
 
 
 
 
e3cd75f
2400a38
 
12aef18
9023f15
12aef18
 
a843d00
9023f15
 
 
a843d00
 
 
 
 
 
 
 
 
 
 
 
 
12aef18
a843d00
12aef18
 
 
 
 
 
 
 
 
 
 
 
 
 
9023f15
a843d00
 
 
12aef18
 
 
 
 
a843d00
 
12aef18
a843d00
 
12aef18
a843d00
 
 
 
 
 
 
 
 
 
 
 
 
12aef18
a843d00
12aef18
 
9023f15
 
a843d00
9fb267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101c2eb
 
 
 
 
6d3b96e
 
33256ac
101c2eb
6d3b96e
 
101c2eb
 
8d0d85b
101c2eb
 
 
 
 
 
 
 
 
 
 
33256ac
101c2eb
 
33256ac
101c2eb
 
 
 
6d3b96e
 
 
 
10e7b9a
6d3b96e
 
 
 
 
 
10e7b9a
 
 
 
 
 
 
 
33256ac
10e7b9a
 
 
 
 
33256ac
 
 
10e7b9a
 
33256ac
10e7b9a
 
 
 
 
 
 
 
6d3b96e
10e7b9a
6d3b96e
10e7b9a
 
6d3b96e
 
 
 
33256ac
 
101c2eb
 
cd34c6f
 
 
 
 
 
 
27bea75
 
33256ac
cd34c6f
 
 
27bea75
 
cd34c6f
 
 
 
27bea75
 
cd34c6f
 
33256ac
 
cd34c6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27bea75
 
 
 
cd34c6f
27bea75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd34c6f
 
 
 
 
 
 
 
 
 
 
 
 
27bea75
 
cd34c6f
27bea75
cd34c6f
 
 
 
 
 
33256ac
cd34c6f
 
 
 
 
 
33256ac
cd34c6f
 
 
 
 
 
 
33256ac
 
27bea75
cd34c6f
 
 
 
 
 
33256ac
cd34c6f
 
 
 
 
 
33256ac
 
 
27bea75
 
 
 
cd34c6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a54992
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
5a54992
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
5a54992
 
 
cca9494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a54992
 
 
a76cbc6
 
5a54992
 
 
 
 
 
 
 
 
 
a76cbc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a54992
 
a76cbc6
cd61bf7
cca9494
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
 
 
 
34739db
41be229
34739db
41be229
 
 
cd61bf7
 
 
 
41be229
 
 
 
cd61bf7
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
0bdce5c
 
 
4e07887
0bdce5c
4e07887
0bdce5c
4e07887
 
0bdce5c
 
 
 
 
 
6a6deb3
 
 
 
 
 
 
 
 
 
 
0bdce5c
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fee233
 
 
cd61bf7
 
 
 
 
 
 
1fee233
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
895011f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
895011f
 
 
 
 
 
 
cd61bf7
 
 
895011f
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
33256ac
 
cd61bf7
6404030
 
cd61bf7
 
 
 
 
 
 
 
6404030
 
 
 
 
 
cd61bf7
6404030
 
 
 
 
 
 
 
 
cd61bf7
6404030
cd61bf7
6404030
 
 
 
 
 
 
 
 
 
 
33256ac
 
 
cd61bf7
6404030
 
 
 
7c6e551
 
 
 
 
 
 
 
6404030
 
 
 
 
 
e651f28
6404030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
1fee233
 
cd61bf7
 
 
 
 
 
 
 
 
1fee233
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5b0923
cd61bf7
 
c5b0923
cd61bf7
 
c5b0923
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04373b4
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dba971d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
dba971d
cd61bf7
 
 
464c219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6404030
 
 
bc65edb
6404030
 
bc65edb
 
6404030
 
 
 
 
 
 
 
 
 
 
 
 
df4fd36
 
 
 
 
 
 
 
 
 
 
 
 
 
e3cd75f
 
 
 
 
 
 
 
449cfa0
 
e3cd75f
f9d6bc4
e3cd75f
f9d6bc4
e3cd75f
 
f9d6bc4
 
 
 
 
 
 
 
 
 
 
 
 
 
e3cd75f
 
 
 
07ef569
 
 
 
 
 
 
 
 
 
9fb267a
 
 
 
 
 
 
 
 
 
 
07ef569
9fb267a
 
 
 
 
 
 
 
 
 
 
07ef569
fda4900
39ac4b7
 
 
 
 
fda4900
39ac4b7
 
fda4900
39ac4b7
 
 
 
 
 
449cfa0
39ac4b7
 
fda4900
39ac4b7
 
 
 
 
 
 
bc65edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ac4b7
 
 
 
bc65edb
39ac4b7
 
 
 
 
 
 
 
bc65edb
 
39ac4b7
bc65edb
39ac4b7
 
 
 
 
bc65edb
 
 
 
 
 
 
 
39ac4b7
 
 
bc65edb
 
39ac4b7
 
 
 
 
 
 
 
 
 
 
 
6404030
 
 
 
 
 
bc65edb
c56f47b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3e0ab
 
 
 
 
 
 
 
 
 
 
 
 
 
b82c62a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f1711
 
 
 
6404030
cd34c6f
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
2fd367f
cd61bf7
 
cc60d0c
cd61bf7
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
e4d238f
 
 
 
2fd367f
 
33256ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22169b1
 
 
 
d6efaed
 
 
22169b1
6df5db6
 
 
81b3ca5
 
6df5db6
 
df6fb4c
 
 
 
 
 
 
fc80520
abc13a7
 
 
 
f673563
 
 
 
 
 
 
 
7e95eff
f673563
d5ac7bd
 
 
 
 
 
 
 
 
fc80520
d5ac7bd
abc13a7
 
 
fc80520
 
 
af3b3ec
fc80520
af3b3ec
fc80520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abc13a7
f673563
 
 
 
abc13a7
 
22169b1
d6efaed
 
 
 
 
abc13a7
22169b1
d6efaed
 
 
 
 
1fee233
 
 
 
d6efaed
5339570
 
d6efaed
c222f07
d6efaed
5339570
 
1fee233
 
4aca3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a65240a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aca3b9
 
 
 
33256ac
 
1fee233
 
33256ac
 
1fee233
33256ac
1fee233
 
 
c222f07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33256ac
 
c222f07
1fee233
 
 
 
 
 
33256ac
 
1fee233
 
 
 
 
 
33256ac
 
1fee233
 
 
 
 
 
33256ac
 
101c2eb
2fd367f
 
 
 
 
 
 
 
 
 
 
 
 
0ce5872
 
 
 
 
 
 
 
 
 
 
 
 
 
2fd367f
 
 
 
 
 
 
 
e4d238f
 
2fd367f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87b355
 
 
 
 
 
 
2a7e440
 
c87b355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6c8caf
 
 
c87b355
 
 
a6c8caf
c87b355
 
 
 
a6c8caf
c87b355
 
 
 
a6c8caf
c87b355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fb267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select
from typing import Dict, Any, Optional
from datetime import datetime
from uuid import UUID
import httpx
import hmac
import hashlib

from app.core.database import get_session
from app.models.tenant import Tenant
from app.models.lead import Lead, Conversation, Message, LeadStatus, Psychotype, MessageStatus
from app.services.ai_core import get_ai_core
from app.services.email import get_email_service
from app.services.subscription_manager import SubscriptionManager
from app.core.config import settings
from app.core.logging import get_logger
from app.api.telegram_webhook import transcribe_telegram_voice, analyze_telegram_image, analyze_telegram_document

logger = get_logger(__name__)


def _extract_topic_from_conversation(conversation_history, user_message: str) -> str:
    """
    Extract topic from conversation for booking notes.
    Returns topic string like "автоматизация, ΠΏΡ€ΠΎΠ΄Π°ΠΆΠΈ"
    """
    topic_keywords = []
    keywords_to_find = [
        "автоматизация", "ΠΏΡ€ΠΎΠ΄Π°ΠΆΠΈ", "ΠΊΠΎΠ½ΡΡƒΠ»ΡŒΡ‚Π°Ρ†ΠΈΡ", "Π²Π½Π΅Π΄Ρ€Π΅Π½ΠΈΠ΅", 
        "Π°ΡƒΠ΄ΠΈΡ‚", "ai", "Π±ΠΎΡ‚", "crm", "интСграция", "ΠΏΠΎΠΌΠΎΡ‰ΡŒ",
        "ΠΏΠ°Ρ€Ρ‚Π½Π΅Ρ€", "Ρ†Π΅Π½Π°", "ΡΡ‚ΠΎΠΈΠΌΠΎΡΡ‚ΡŒ", "Π΄Π΅ΠΌΠΎ", "ΠΎΠ±ΡƒΡ‡Π΅Π½ΠΈΠ΅",
        "вопрос", "услуга", "Ρ‚Π°Ρ€ΠΈΡ„", "подписка"
    ]
    
    # Check last 10 user messages for keywords
    user_messages = [msg.content.lower() for msg in conversation_history[-10:] if msg.sender_type == "user"]
    user_messages.append(user_message.lower())
    
    for msg in user_messages:
        for keyword in keywords_to_find:
            if keyword in msg and keyword not in topic_keywords:
                topic_keywords.append(keyword)
                if len(topic_keywords) >= 3:
                    break
    
    return ", ".join(topic_keywords) if topic_keywords else "ΠšΠΎΠ½ΡΡƒΠ»ΡŒΡ‚Π°Ρ†ΠΈΡ"


def _extract_booking_info_from_conversation(conversation_history, lead, user_text: str) -> dict:
    """
    Extract booking info from conversation history.
    Returns dict with: name, phone, topic for comprehensive notes.
    Universal for any business type.
    """
    import re
    
    # Get best available name: AI-extracted > lead.name > "ΠšΠ»ΠΈΠ΅Π½Ρ‚"
    best_name = "ΠšΠ»ΠΈΠ΅Π½Ρ‚"
    
    # 1. Try AI-extracted name from summary (most reliable)
    if lead and lead.ai_summary_json:
        ai_name = lead.ai_summary_json.get('client_name')
        if ai_name and isinstance(ai_name, str) and len(ai_name) >= 2:
            best_name = ai_name
    
    # 2. Fallback to lead.name if no AI name
    if best_name == "ΠšΠ»ΠΈΠ΅Π½Ρ‚" and lead and lead.name:
        best_name = lead.name
    
    info = {
        "name": best_name,
        "phone": lead.phone if lead and lead.phone else None,
        "topic": None
    }
    
    # Get user messages
    user_messages = [msg.content for msg in conversation_history if msg.sender_type == "user"]
    
    # Patterns for phone extraction
    phone_patterns = [
        r'[\+]?[0-9]{10,15}',  # International format
        r'[\+]?996\s*\d{9}',   # Kyrgyzstan
        r'[\+]?7\s*\d{10}',    # Russia
        r'\d{3}[\s\-]?\d{3}[\s\-]?\d{4}', # 999-123-4567
    ]
    
    # Extract phone if not already have
    if not info["phone"]:
        for msg in reversed(user_messages[-15:]):
            for pattern in phone_patterns:
                match = re.search(pattern, msg)
                if match:
                    info["phone"] = match.group(0).strip()
                    break
            if info["phone"]:
                break
    
    # Extract topic from AI summary (niche or intent) - UNIVERSAL for any business
    topic_parts = []
    
    if lead and lead.ai_summary_json:
        # Try niche first (client's business area)
        niche = lead.ai_summary_json.get('niche')
        if niche and isinstance(niche, str) and len(niche) > 2:
            topic_parts.append(niche)
        
        # Then intent
        intent = lead.ai_summary_json.get('intent', '')
        if intent and len(intent) > 3 and len(intent) < 50:
            # Clean up generic phrases
            intent_clean = intent.replace('НС выявлСн', '').replace('Анализ Π² процСссС', '').strip()
            if intent_clean and intent_clean not in topic_parts:
                topic_parts.append(intent_clean[:40])  # Limit length
    
    info["topic"] = " | ".join(topic_parts) if topic_parts else "ΠšΠΎΠ½ΡΡƒΠ»ΡŒΡ‚Π°Ρ†ΠΈΡ"
    
    return info



async def _find_available_slots(
    session,
    tenant_id: UUID,
    requested_time: datetime,
    count: int = 3,
    duration_minutes: int = 30
) -> list:
    """
    Find next N available time slots after requested_time.
    Returns list of datetime objects for available slots.
    """
    from app.models.booking import Appointment, AppointmentStatus
    from app.models.tenant import Tenant
    from datetime import timedelta
    
    available_slots = []
    
    # Get tenant booking settings for working hours
    tenant = await session.get(Tenant, tenant_id)
    booking_settings = tenant.booking_settings or {} if tenant else {}
    working_hours = booking_settings.get('working_hours', {})
    working_days = booking_settings.get('working_days', ['mon', 'tue', 'wed', 'thu', 'fri'])
    
    start_hour = int(working_hours.get('start', '09:00').split(':')[0])
    end_hour = int(working_hours.get('end', '18:00').split(':')[0])
    
    # Day mapping
    day_map = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6}
    working_day_nums = [day_map.get(d, 0) for d in working_days]
    
    # Get all booked slots for the next 7 days
    end_search = requested_time + timedelta(days=7)
    stmt = select(Appointment).where(
        Appointment.tenant_id == tenant_id,
        Appointment.status == AppointmentStatus.SCHEDULED,
        Appointment.start_time >= requested_time,
        Appointment.start_time <= end_search
    )
    result = await session.execute(stmt)
    booked_appointments = result.scalars().all()
    booked_times = {appt.start_time for appt in booked_appointments}
    
    # Start searching from requested time, move forward in 30-min increments
    current = requested_time + timedelta(minutes=duration_minutes)
    
    while len(available_slots) < count and current < end_search:
        # Check if within working hours
        is_working_day = current.weekday() in working_day_nums
        is_working_hour = start_hour <= current.hour < end_hour
        
        if is_working_day and is_working_hour:
            # Check if not booked
            if current not in booked_times:
                available_slots.append(current)
        
        # Move to next slot
        current += timedelta(minutes=duration_minutes)
        
        # If we've moved past end of day, jump to next day start
        if current.hour >= end_hour:
            next_day = current.date() + timedelta(days=1)
            current = datetime.combine(next_day, datetime.min.time().replace(hour=start_hour))
    
    return available_slots


async def send_product_images_if_mentioned(
    session,
    tenant_id: UUID,
    bot_token: str,
    chat_id: str,
    ai_text: str,
    conversation_id: UUID = None  # NEW: to save messages in DB
) -> Optional[int]:
    """
    Detect product names mentioned in AI response and send ALL their images.
    Also saves image messages to database so they appear in chat UI.
    """
    from app.models.product import Product
    from app.models.lead import Message
    from app.services.telegram_service import telegram_service
    
    # Get all products with images for this tenant
    stmt = select(Product).where(
        Product.tenant_id == tenant_id,
        Product.is_active == True
    )
    result = await session.execute(stmt)
    products = result.scalars().all()
    
    if not products:
        return None
    
    ai_text_lower = ai_text.lower()
    last_message_id = None
    
    for product in products:
        # Check if product name is mentioned in AI response
        product_name_lower = product.name.lower()
        if product_name_lower in ai_text_lower:
            # Collect all image URLs
            all_image_urls = []
            
            # Add all images from image_urls array
            if product.image_urls and len(product.image_urls) > 0:
                all_image_urls.extend(product.image_urls)
            # Fallback: add single image_url if present and not already in list
            elif product.image_url and product.image_url not in all_image_urls:
                all_image_urls.append(product.image_url)
            
            if not all_image_urls:
                continue
                
            # Caption without box emoji
            caption = product.name
            
            try:
                # Send all photos as a media group (album)
                result = await telegram_service.send_media_group(
                    token=bot_token,
                    chat_id=chat_id,
                    photo_urls=all_image_urls,
                    caption=caption
                )
                if result["success"]:
                    last_message_id = result["message_id"]
                    logger.info(f"πŸ“· Auto-sent {len(all_image_urls)} images as album for product: {product.name} (msg_id: {last_message_id})")
                
                # Save one message for the album in database
                if conversation_id and result["success"]:
                    image_message = Message(
                        conversation_id=conversation_id,
                        tenant_id=tenant_id,
                        sender_type="ai",
                        content=f"{product.name} ({len(all_image_urls)} Ρ„ΠΎΡ‚ΠΎ)",
                        media_url=all_image_urls[0],  # First image as preview
                        media_type="image",
                        media_name=f"{product.name}.jpg"
                    )
                    session.add(image_message)
                    
            except Exception as e:
                logger.error(f"❌ Failed to send album for {product.name}: {e}")
    
    # Commit all image messages if any were added
    if conversation_id:
        await session.commit()
    
    return last_message_id


async def send_media_files(
    session,
    tenant_id: UUID,
    lead_id: UUID,
    bot_token: str,
    chat_id: str,
    media_ids: list,
    conversation_id: UUID = None,
    user_message: str = ""  # For context in Reply
) -> Optional[int]:
    """
    Send media files from MediaLibrary when AI uses [SEND_MEDIA:ID] tag.
    Records progress to prevent duplicate sends.
    
    NEW: If media was already sent, uses Reply feature to reference it.
    """
    from app.models.knowledge import KnowledgeFile, LeadContentProgress
    from app.models.lead import Message
    from app.services.telegram_service import telegram_service
    from app.services.ai_core.media_tracker import media_tracker
    from app.services.llm_client import get_llm_client
    from datetime import datetime
    
    last_sent_message_id = None
    
    for media_id_short in media_ids:
        try:
            # Find media file by ID prefix (we use first 8 chars in prompt)
            stmt = select(KnowledgeFile).where(
                KnowledgeFile.tenant_id == tenant_id,
                KnowledgeFile.is_active == True
            )
            result = await session.execute(stmt)
            all_files = result.scalars().all()
            
            # Find matching file by ID prefix
            media_file = None
            for f in all_files:
                if str(f.id).startswith(media_id_short):
                    media_file = f
                    break
            
            if not media_file:
                logger.warning(f"⚠️ Media file not found: {media_id_short}")
                continue
            
            # Check if already sent to this lead
            progress_stmt = select(LeadContentProgress).where(
                LeadContentProgress.lead_id == lead_id,
                LeadContentProgress.knowledge_file_id == media_file.id
            )
            progress_result = await session.execute(progress_stmt)
            existing_progress = progress_result.scalar_one_or_none()
            
            media_id_str = str(media_file.id)
            lead_id_str = str(lead_id)
            
            # Check if already sent - use Reply feature instead of skipping
            if existing_progress and existing_progress.sent_at:
                # Get cached message_id for Reply
                cached_message_id = media_tracker.get_message_id_for_media(lead_id_str, media_id_str)
                
                if cached_message_id:
                    # Generate contextual reference to the media
                    try:
                        llm = get_llm_client()
                        reference_text = await llm.generate_media_reference_text(
                            media_type=media_file.file_type or "image",
                            product_name=media_file.name,
                            user_question=user_message
                        )
                    except Exception:
                        reference_text = f"ΠžΠ±Ρ€Π°Ρ‚ΠΈΡ‚Π΅ Π²Π½ΠΈΠΌΠ°Π½ΠΈΠ΅ Π½Π° {media_file.name} Π²Ρ‹ΡˆΠ΅:"
                    
                    # Send Reply to the original media message
                    await telegram_service.send_message(
                        token=bot_token,
                        chat_id=chat_id,
                        text=reference_text,
                        reply_to_message_id=int(cached_message_id)
                    )
                    logger.info(f"πŸ“Ž Sent Reply reference to already-sent media: {media_file.name}")
                else:
                    logger.info(f"πŸ“ Media already sent but no message_id cached: {media_file.name}")
                continue
            
            # Determine what to send
            file_url = media_file.file_url or media_file.external_link
            if not file_url:
                logger.warning(f"⚠️ Media file has no URL: {media_file.name}")
                continue
            
            # Send based on file type
            caption = media_file.name
            if media_file.description:
                caption += f"\n{media_file.description}"
            
            send_result = {"success": False, "message_id": None}
            
            if media_file.file_type in ['image', 'qr']:
                send_result = await telegram_service.send_photo(
                    token=bot_token,
                    chat_id=chat_id,
                    photo_url=file_url,
                    caption=caption
                )
            elif media_file.file_type == 'video':
                send_result = await telegram_service.send_video(
                    token=bot_token,
                    chat_id=chat_id,
                    video_url=file_url,
                    caption=caption
                )
            elif media_file.file_type == 'document':
                send_result = await telegram_service.send_document(
                    token=bot_token,
                    chat_id=chat_id,
                    document_url=file_url,
                    caption=caption
                )
            elif media_file.file_type in ['link']:
                # Send as text message with link
                # send_message returns dict with message_id in recent update (not yet, send_message returns dict? No, check telegram_service)
                # Ah, send_message in telegram_service returns dict!
                send_result = await telegram_service.send_message(
                    token=bot_token,
                    chat_id=chat_id,
                    text=f"πŸ”— {media_file.name}\n{file_url}"
                )
            else:
                # Default: send as document
                send_result = await telegram_service.send_document(
                    token=bot_token,
                    chat_id=chat_id,
                    document_url=file_url,
                    caption=caption
                )
            
            if send_result.get("success"):
                last_sent_message_id = send_result.get("message_id")
            
            # Store message_id in MediaTracker for Reply feature
            if send_result.get("message_id"):
                media_tracker.mark_sent(lead_id_str, media_id_str, str(send_result["message_id"]))
            
            logger.info(f"πŸ“ Sent media file: {media_file.name} ({media_file.file_type})")
            
            # Record progress
            if existing_progress:
                existing_progress.sent_at = datetime.utcnow()
                session.add(existing_progress)
            else:
                progress = LeadContentProgress(
                    lead_id=lead_id,
                    knowledge_file_id=media_file.id,
                    sent_at=datetime.utcnow()
                )
                session.add(progress)
            
            # Save message to chat history
            if conversation_id:
                file_message = Message(
                    conversation_id=conversation_id,
                    tenant_id=tenant_id,
                    sender_type="ai",
                    content=f"πŸ“ {media_file.name}",
                    media_url=file_url,
                    media_type=media_file.file_type,
                    media_name=media_file.name
                )
                session.add(file_message)
            
        except Exception as e:
            logger.error(f"❌ Failed to send media {media_id_short}: {e}")
    
    await session.commit()

async def download_telegram_file(bot_token: str, file_id: str) -> tuple[bytes, str]:
    """
    Download file from Telegram Bot API.
    Returns (file_bytes, file_extension)
    """
    async with httpx.AsyncClient() as client:
        # 1. Get file path
        file_info_url = f"https://api.telegram.org/bot{bot_token}/getFile"
        file_response = await client.post(file_info_url, json={"file_id": file_id}, timeout=10.0)
        file_response.raise_for_status()
        
        file_data = file_response.json()
        if not file_data.get("ok"):
            raise Exception(f"Telegram getFile failed: {file_data}")
        
        file_path = file_data["result"]["file_path"]
        
        # 2. Download file
        download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
        download_response = await client.get(download_url, timeout=30.0)
        download_response.raise_for_status()
        
        # 3. Extract extension
        file_ext = file_path.split(".")[-1] if "." in file_path else "bin"
        
        return download_response.content, file_ext


def get_mime_type(extension: str) -> str:
    """Map file extension to MIME type."""
    mime_map = {
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "png": "image/png",
        "webp": "image/webp",
        "gif": "image/gif",
        "ogg": "audio/ogg",
        "oga": "audio/ogg",
        "mp3": "audio/mpeg",
        "m4a": "audio/mp4",
        "pdf": "application/pdf",
        "doc": "application/msword",
        "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "txt": "text/plain",
    }
    return mime_map.get(extension.lower(), "application/octet-stream")


router = APIRouter(prefix="/webhook", tags=["Webhooks"])


@router.post("/telegram/{tenant_id}")
async def telegram_webhook(
    tenant_id: UUID,
    request: Request,
    background_tasks: BackgroundTasks,
    session = Depends(get_session),
    x_telegram_bot_api_secret_token: Optional[str] = Header(None)
):
    """
    Telegram webhook endpoint for receiving messages.
    
    Each tenant has unique webhook URL: /webhook/telegram/{tenant_id}
    Security: Validates X-Telegram-Bot-Api-Secret-Token header
    """
    try:
        # Get tenant first to validate webhook secret
        tenant = await session.get(Tenant, tenant_id)
        if not tenant or not tenant.is_active:
            raise HTTPException(status_code=404, detail="Tenant not found or inactive")
        
        # Validate webhook secret token (if configured)
        # Note: Telegram sends this header if you set secret_token in setWebhook
        # TODO: Uncomment when telegram_webhook_secret column is added to DB
        # webhook_secret = getattr(tenant, 'telegram_webhook_secret', None)
        # if webhook_secret and x_telegram_bot_api_secret_token != webhook_secret:
        #     logger.warning(
        #         "Invalid Telegram webhook secret",
        #         tenant_id=str(tenant_id)
        #     )
        #     raise HTTPException(status_code=403, detail="Invalid webhook secret")
        
        # Parse Telegram update
        update = await request.json()
        
        # Extract message data
        if "message" not in update:
            return {"ok": True}  # Ignore non-message updates
        
        message = update["message"]
        
        # Check for voice/audio/photo/document (multimodal content)
        voice = message.get("voice") or message.get("audio")
        photo_list = message.get("photo", [])
        document = message.get("document")
        
        has_text = "text" in message
        has_voice = voice is not None
        has_photo = len(photo_list) > 0
        has_document = document is not None
        has_media = has_voice or has_photo or has_document
        
        # Log what we received
        logger.info(f"πŸ“© Telegram message: text={has_text}, voice={has_voice}, photo={has_photo}, doc={has_document}")
        
        # Validate required fields
        if "from" not in message:
            return {"ok": True}  # Ignore messages without sender
        
        # Must have either text or media
        if not has_text and not has_media:
            logger.info("⏭️ Ignoring message without text or media")
            return {"ok": True}
        
        # Check if message is from a real user (not bot)
        telegram_user = message["from"]
        if telegram_user.get("is_bot", False):
            return {"ok": True}  # Ignore bot messages
        
        telegram_id = str(telegram_user["id"])
        chat_id = str(message["chat"]["id"])
        
        # Extract text (or caption from media) or transcribe voice
        user_text = message.get("text") or message.get("caption") or ""
        
        # Handle reply_to_message - include context of quoted message
        reply_to = message.get("reply_to_message")
        reply_context = ""
        if reply_to:
            # Extract quoted message content
            quoted_text = reply_to.get("text") or reply_to.get("caption") or ""
            quoted_from = reply_to.get("from", {})
            is_from_bot = quoted_from.get("is_bot", False)
            
            if quoted_text:
                quoted_source = "Π±ΠΎΡ‚" if is_from_bot else "ΠΊΠ»ΠΈΠ΅Π½Ρ‚"
                reply_context = f"[Π’ ΠΎΡ‚Π²Π΅Ρ‚ Π½Π° сообщСниС {quoted_source}: \"{quoted_text[:200]}{'...' if len(quoted_text) > 200 else ''}\"] "
                logger.info(f"↩️ Reply detected: quoting {quoted_source} message")
            elif reply_to.get("photo"):
                reply_context = "[Π’ ΠΎΡ‚Π²Π΅Ρ‚ Π½Π° Ρ„ΠΎΡ‚ΠΎ] "
                logger.info("↩️ Reply to photo detected")
            elif reply_to.get("voice") or reply_to.get("audio"):
                reply_context = "[Π’ ΠΎΡ‚Π²Π΅Ρ‚ Π½Π° голосовоС сообщСниС] "
                logger.info("↩️ Reply to voice detected")
        
        voice_file_id = voice.get("file_id") if voice else None
        photo_file_id = photo_list[-1]["file_id"] if photo_list else None
        doc_file_id = document.get("file_id") if document else None
        doc_mime_type = document.get("mime_type") if document else None
        doc_file_name = document.get("file_name", "document") if document else None
        
        # Process voice message (transcribe to text)
        if voice_file_id and tenant.telegram_bot_token:
            try:
                user_text = await transcribe_telegram_voice(tenant.telegram_bot_token, voice_file_id)
                logger.info(f"🎀 Voice transcribed: {user_text[:50]}...")
            except Exception as e:
                logger.error(f"❌ Voice transcription failed: {e}")
                user_text = "[ГолосовоС сообщСниС - Π½Π΅ ΡƒΠ΄Π°Π»ΠΎΡΡŒ Ρ€Π°ΡΠΏΠΎΠ·Π½Π°Ρ‚ΡŒ]"
        
        # Process photo (analyze with Vision)
        elif photo_file_id and tenant.telegram_bot_token and not user_text:
            try:
                user_text = await analyze_telegram_image(tenant.telegram_bot_token, photo_file_id)
                logger.info(f"πŸ“· Image analyzed: {user_text[:50]}...")
            except Exception as e:
                logger.error(f"❌ Image analysis failed: {e}")
                user_text = "[Π€ΠΎΡ‚ΠΎ - Π½Π΅ ΡƒΠ΄Π°Π»ΠΎΡΡŒ ΠΏΡ€ΠΎΠ°Π½Π°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ]"
        
        # Process document (analyze based on type)
        elif doc_file_id and tenant.telegram_bot_token and not user_text:
            try:
                user_text = await analyze_telegram_document(
                    tenant.telegram_bot_token, 
                    doc_file_id, 
                    doc_mime_type, 
                    doc_file_name
                )
                logger.info(f"πŸ“„ Document analyzed: {user_text[:50]}...")
            except Exception as e:
                logger.error(f"❌ Document analysis failed: {e}")
                user_text = f"[Π”ΠΎΠΊΡƒΠΌΠ΅Π½Ρ‚: {doc_file_name}] (Ошибка Π°Π½Π°Π»ΠΈΠ·Π°)"
        
        # If still no text after all processing, use placeholder
        if not user_text:
            user_text = "[МСдиа-сообщСниС Π±Π΅Π· содСрТимого]"
        
        # Prepend reply context so AI knows what message user is replying to
        if reply_context:
            user_text = reply_context + user_text
        
        # Tenant already fetched and validated above
        
        # Find or create lead
        lead = await get_or_create_lead(
            session=session,
            tenant_id=tenant_id,
            telegram_id=telegram_id,
            telegram_user=telegram_user
        )
        
        # Find or create conversation
        conversation = await get_or_create_conversation(
            session=session,
            tenant_id=tenant_id,
            lead_id=lead.id,
            channel="telegram"
        )
        
        # Download and upload media if present
        media_url = None
        media_type = None
        media_name = None
        
        if (voice_file_id or photo_file_id or doc_file_id) and tenant.telegram_bot_token:
            try:
                file_id = voice_file_id or photo_file_id or doc_file_id
                
                # 1. Download from Telegram
                logger.info(f"⬇️ Downloading file {file_id[:8]}... from Telegram")
                file_bytes, file_ext = await download_telegram_file(
                    tenant.telegram_bot_token, 
                    file_id
                )
                logger.info(f"βœ… Downloaded {len(file_bytes)} bytes, ext: {file_ext}")
                
                # 2. Upload to Supabase
                from app.core.supabase import supabase_client
                import time
                import re
                
                if supabase_client:
                    bucket = "chat-attachments"
                    ts = int(time.time())
                    safe_name = f"{ts}_{file_id[:12]}.{file_ext}"
                    path = f"{tenant_id}/{conversation.id}/{safe_name}"
                    
                    mime_type = get_mime_type(file_ext)
                    
                    try:
                        logger.info(f"⬆️ Uploading to Supabase: {path} ({mime_type})")
                        upload_result = supabase_client.storage.from_(bucket).upload(
                            path=path,
                            file=file_bytes,
                            file_options={"content-type": mime_type}
                        )
                        media_url = supabase_client.storage.from_(bucket).get_public_url(path)
                        logger.info(f"βœ… Uploaded to Supabase: {media_url[:80]}...")
                        
                        # 3. Set media metadata
                        media_type = mime_type
                        if voice_file_id:
                            media_name = "voice.ogg"
                        elif photo_file_id:
                            media_name = f"photo.{file_ext}"
                        elif doc_file_id:
                            media_name = doc_file_name or f"document.{file_ext}"
                    except Exception as upload_err:
                        import traceback
                        logger.error(f"❌ Supabase upload failed: {upload_err}")
                        logger.error(f"πŸ“‹ Traceback: {traceback.format_exc()}")
                        # Check if bucket exists issue
                        if "not found" in str(upload_err).lower() or "bucket" in str(upload_err).lower():
                            logger.error(f"πŸ’‘ Hint: Check if bucket '{bucket}' exists in Supabase Storage")
                else:
                    logger.warning("⚠️ Supabase client not available, media will not be uploaded")
                    
            except Exception as e:
                import traceback
                logger.error(f"❌ Failed to download/upload media: {e}")
                logger.error(f"πŸ“‹ Full traceback: {traceback.format_exc()}")
                # Continue without media - at least save the transcribed text
        
        # Save user message WITH media fields
        user_message = Message(
            tenant_id=tenant_id,
            conversation_id=conversation.id,
            sender_type="user",
            content=user_text,
            media_url=media_url,
            media_type=media_type,
            media_name=media_name
        )
        session.add(user_message)
        await session.commit()
        await session.refresh(user_message)
        
        # Notify WebSocket clients about new message (real-time updates)
        try:
            from app.api.websocket_chat import notify_new_message
            await notify_new_message(str(lead.id), {
                "id": str(user_message.id),
                "content": user_message.content,
                "sender_type": "user",
                "created_at": user_message.created_at.isoformat() if user_message.created_at else None,
                "media_url": user_message.media_url,
                "media_type": user_message.media_type
            })
            logger.debug(f"πŸ“‘ WebSocket notified: user message {user_message.id}")
        except Exception as e:
            logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}")

        # Extract real name from message (avoid using Telegram nicknames)
        try:
            from app.utils.name_extraction import extract_name_from_message, should_update_lead_name
            from app.services.llm_client import get_llm_client
            
            # Try to extract name from first few messages using AI
            if user_text and len(user_text) > 5:
                llm = get_llm_client()
                extracted_name = await extract_name_from_message(user_text, llm_client=llm, use_llm_fallback=True)
                
                if extracted_name and should_update_lead_name(lead.name or "", extracted_name):
                    logger.info(f"βœ… Updating lead name from '{lead.name}' to '{extracted_name}'")
                    lead.name = extracted_name
                    session.add(lead)
                    await session.commit()
                    
                    # Notify WebSocket clients about name update for real-time AI Summary refresh
                    try:
                        from app.api.websocket_chat import notify_lead_updated
                        await notify_lead_updated(str(lead.id), {
                            "id": str(lead.id),
                            "name": lead.name,
                        })
                        logger.debug(f"πŸ“‘ WebSocket: lead name updated to '{lead.name}'")
                    except Exception as ws_err:
                        logger.warning(f"⚠️ WebSocket lead update failed: {ws_err}")
        except Exception as e:
            logger.warning(f"⚠️ Name extraction failed (non-critical): {e}")
        
        # Update lead activity
        lead.last_message_at = datetime.utcnow()
        lead.last_activity_at = datetime.utcnow()
        session.add(lead)
        await session.commit()
        
        # Check if human took over
        if conversation.human_takeover:
            # Don't respond with AI, human is handling
            logger.info(
                "πŸ‘€ Human takeover active, skipping AI response",
                conversation_id=str(conversation.id)
            )
            return {"ok": True, "status": "human_handling"}
        
        # Process AI response in background to respond quickly to Telegram
        logger.info(
            "🎯 Adding background task for AI response",
            user_message_id=str(user_message.id),
            conversation_id=str(conversation.id),
            chat_id=chat_id
        )
        
        # Determine if we should respond with voice (voice-to-voice mode)
        respond_with_voice = voice_file_id is not None
        
        background_tasks.add_task(
            process_ai_response_background,
            tenant.id,
            lead.id,
            conversation.id,
            user_message.id,  # Pass message ID for debouncing
            user_text,
            chat_id,
            respond_with_voice  # New parameter: respond with voice if user sent voice
        )
        
        # Return immediately to Telegram (prevents retry)
        return {"ok": True, "status": "processing"}
        
    except Exception as e:
        logger.error(
            "Webhook error",
            tenant_id=str(tenant_id),
            error=str(e),
            exc_info=True
        )
        raise


async def get_or_create_lead(
    session: AsyncSession,
    tenant_id: UUID,
    telegram_id: str,
    telegram_user: Dict[str, Any]
) -> Lead:
    """Find existing lead or create new one."""
    
    # Try to find existing lead
    stmt = select(Lead).where(
        Lead.tenant_id == tenant_id,
        Lead.telegram_id == telegram_id
    )
    result = await session.execute(stmt)
    lead = result.scalar_one_or_none()
    
    if lead:
        return lead
    
    # Create new lead
    name = telegram_user.get("first_name", "")
    if telegram_user.get("last_name"):
        name += f" {telegram_user['last_name']}"
    
    lead = Lead(
        tenant_id=tenant_id,
        telegram_id=telegram_id,
        name=name or None,
        status=LeadStatus.NEW,
        psychotype=Psychotype.UNKNOWN,
        heat_score=0
    )
    
    session.add(lead)
    await session.commit()
    await session.refresh(lead)
    
    return lead


async def get_or_create_conversation(
    session: AsyncSession,
    tenant_id: UUID,
    lead_id: UUID,
    channel: str
) -> Conversation:
    """Find active conversation or create new one."""
    
    # Try to find active conversation
    stmt = select(Conversation).where(
        Conversation.tenant_id == tenant_id,
        Conversation.lead_id == lead_id,
        Conversation.channel == channel,
        Conversation.is_active == True
    )
    result = await session.execute(stmt)
    conversation = result.scalar_one_or_none()
    
    if conversation:
        return conversation
    
    # βœ… ΠŸΠ ΠžΠ’Π•Π ΠšΠ Π›Π˜ΠœΠ˜Π’ΠžΠ’ ΠŸΠ•Π Π•Π” Π‘ΠžΠ—Π”ΠΠΠ˜Π•Πœ ΠΠžΠ’ΠžΠ“Πž Π”Π˜ΠΠ›ΠžΠ“Π
    tenant = await session.get(Tenant, tenant_id)
    if not tenant:
        raise HTTPException(status_code=404, detail="Tenant not found")
    
    can_create, reason = await SubscriptionManager.check_can_create_conversation(
        tenant=tenant,
        session=session
    )
    
    if not can_create:
        logger.warning(
            "❌ Conversation blocked by subscription limit",
            tenant_id=str(tenant_id),
            reason=reason,
            plan=tenant.subscription_plan,
            leads_count=tenant.leads_this_month
        )
        raise HTTPException(
            status_code=403,
            detail=reason or "Достигнут Π»ΠΈΠΌΠΈΡ‚ подписки"
        )
    
    # Create new conversation
    conversation = Conversation(
        tenant_id=tenant_id,
        lead_id=lead_id,
        channel=channel,
        is_active=True
    )
    
    session.add(conversation)
    
    # βœ… Π£Π’Π•Π›Π˜Π§Π˜Π’ΠΠ•Πœ БЧЁВЧИК Π”Π˜ΠΠ›ΠžΠ“ΠžΠ’
    await SubscriptionManager.increment_conversation_count(
        tenant=tenant,
        session=session
    )
    
    await session.commit()
    await session.refresh(conversation)
    
    logger.info(
        "βœ… New conversation created",
        conversation_id=str(conversation.id),
        tenant_plan=tenant.subscription_plan,
        leads_count=tenant.leads_this_month
    )
    
    return conversation


async def send_telegram_message(
    bot_token: str,
    chat_id: str,
    text: str,
    reply_to_message_id: int = None
) -> bool:
    """Send message via Telegram Bot API (Text or Photo)."""
    import re
    
    if not bot_token or not bot_token.strip():
        logger.warning(
            "⚠️ No valid bot token configured for tenant",
            chat_id=chat_id
        )
        return False
    
    # 1. Extract Image URLs (Supabase or standard extensions)
    # Matches: https://...supabase... or ending in .jpg/png/webp
    img_pattern = r"(https?://[^\s\)]+(?:supabase\.co|products)[^\s\)]+)|(https?://[^\s\)]+\.(?:jpg|jpeg|png|webp))"
    matches = re.findall(img_pattern, text, re.IGNORECASE)
    # Flatten matches and filter empty
    images = [m[0] or m[1] for m in matches if m[0] or m[1]]
    
    # 2. Clean Text (Remove links to images to avoid duplicates)
    clean_text = text
    for img in images:
        # Remove Markdown links: [text](url)
        clean_text = re.sub(r"\[.*?\]\(" + re.escape(img) + r"\)", "", clean_text)
        # Remove plain URLs in parens: (url)
        clean_text = clean_text.replace(f"({img})", "")
        # Remove plain URLs
        clean_text = clean_text.replace(img, "")
    
    clean_text = clean_text.strip()
    
    async with httpx.AsyncClient() as client:
        success = True
        
        # 3. Send Text (if any remains)
        if clean_text:
            text_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
            payload = {
                "chat_id": chat_id,
                "text": clean_text,
                "parse_mode": "Markdown"
            }
            if reply_to_message_id:
                payload["reply_to_message_id"] = reply_to_message_id

            
            try:
                # Attempt 1: Markdown
                response = await client.post(text_url, json=payload, timeout=10.0)
                
                # Retry Plain Text if Markdown fails (ANY 400 error)
                if response.status_code == 400:
                    logger.warning(
                        "⚠️ Markdown failed, retrying with plain text",
                        error=response.text[:200],
                        chat_id=chat_id
                    )
                    del payload["parse_mode"]  # Remove parse_mode entirely
                    response = await client.post(text_url, json=payload, timeout=10.0)
                
                response.raise_for_status()
            except Exception as e:
                logger.error("❌ Failed to send text", error=str(e))
                success = False

        # 4. Send Images (as Photos)
        photo_url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
        for img in images:
            try:
                # Check extension, if it's .jfif or unknown, Telegram might reject as photo.
                # But Supabase usually serves content-type correctly.
                # If Telegram rejects generic URL, we might need download/re-upload, 
                # but usually passing URL works fine.
                payload = {
                    "chat_id": chat_id,
                    "photo": img,
                    "caption": "" # Optional: add caption?
                }
                logger.info("πŸ“Έ Sending photo", url=img)
                resp = await client.post(photo_url, json=payload, timeout=20.0)
                resp.raise_for_status()
            except Exception as e:
                logger.error("❌ Failed to send photo", url=img, error=str(e))
                # Don't fail the whole task if one image fails, but log it.
                # If we rely on image for context, this might be bad.
                pass
                
        return success


async def process_ai_response_background(
    tenant_id: UUID,
    lead_id: UUID,
    conversation_id: UUID,
    user_message_id: UUID,  # Message ID for debouncing check
    user_text: str,
    chat_id: str,
    respond_with_voice: bool = False  # New: respond with voice message if True
):
    """
    Background task: Generate AI response and send to Telegram.
    Creates its own database session to avoid session lifecycle issues.
    
    **ANTI-SPAM DEBOUNCING:**
    - Waits 4 seconds before processing
    - Checks if user sent newer messages during wait
    - Only processes if this is still the latest message (prevents spam)
    
    **VOICE-TO-VOICE MODE:**
    - If respond_with_voice=True, AI will send voice message instead of text
    """
    from app.core.database import async_session_maker
    import asyncio
    
    logger.info(
        "πŸš€ Starting debounced AI response task",
        user_message_id=str(user_message_id),
        conversation_id=str(conversation_id),
        lead_id=str(lead_id)
    )
    
    # TASK 2: Set status during processing (NO "waiting" - not allowed by DB constraint)
    try:
        async with async_session_maker() as session:
            lead = await session.get(Lead, lead_id)
            if lead:
                # NOTE: "waiting" is NOT in DB constraint, using "idle" instead
                # Allowed values: idle, generating, analyzing, error
                lead.processing_status = "idle"  # Keep as idle until we start generating
                session.add(lead)
                await session.commit()
                logger.info(
                    "βœ… Lead status confirmed as idle",
                    lead_id=str(lead_id)
                )
            else:
                logger.error(
                    "❌ Lead not found for debouncing",
                    lead_id=str(lead_id)
                )
                return
    except Exception as e:
        logger.error(
            "❌ Failed to set processing status",
            lead_id=str(lead_id),
            error=str(e),
            exc_info=True
        )
        return
    
    # TASK 1: Add 2-second debouncing delay (reduced from 4s for faster response)
    # This gives the user time to finish typing multiple messages
    logger.info(
        "⏳ Starting 2-second debounce delay...",
        lead_id=str(lead_id)
    )
    await asyncio.sleep(2)
    
    async with async_session_maker() as session:
        try:
            # TASK 2: Check for Newer Messages (The Filter)
            # If user sent more messages during the sleep, abort this task
            stmt = select(Message).where(
                Message.conversation_id == conversation_id,
                Message.sender_type == "user"
            ).order_by(Message.created_at.desc()).limit(1)
            
            result = await session.execute(stmt)
            latest_user_message = result.scalar_one_or_none()
            
            if latest_user_message and latest_user_message.id != user_message_id:
                # User sent a newer message during the debounce period
                logger.info(
                    "⏭️ Debouncing: Skipping old message",
                    current_msg_id=str(user_message_id),
                    latest_msg_id=str(latest_user_message.id),
                    conversation_id=str(conversation_id)
                )
                # Reset status to idle since we're not processing
                lead = await session.get(Lead, lead_id)
                if lead:
                    lead.processing_status = "idle"
                    session.add(lead)
                    await session.commit()
                return  # Abort - let the newer message's task handle the reply
            
            logger.info(
                "βœ… This is the latest message, proceeding with AI generation",
                user_message_id=str(user_message_id),
                conversation_id=str(conversation_id)
            )
            
            # Fetch fresh objects from database
            tenant = await session.get(Tenant, tenant_id)
            lead = await session.get(Lead, lead_id)
            conversation = await session.get(Conversation, conversation_id)
            
            if not tenant or not lead or not conversation:
                logger.error(
                    "Background task: objects not found",
                    tenant_id=str(tenant_id),
                    lead_id=str(lead_id)
                )
                return
            
            # πŸ”΄ CHECK AI MASTER TOGGLE - Skip if disabled
            if not getattr(tenant, 'ai_enabled', True):
                logger.info(
                    "πŸ”‡ AI is DISABLED for this tenant - skipping response",
                    tenant_id=str(tenant_id)
                )
                return
            # Set processing status to GENERATING
            lead.processing_status = "generating"
            session.add(lead)
            await session.commit()
            
            ai_core = get_ai_core()
            
            # Get conversation history
            history_stmt = select(Message).where(
                Message.conversation_id == conversation.id
            ).order_by(Message.created_at.desc()).limit(settings.MAX_CONTEXT_MESSAGES)
            
            history_result = await session.execute(history_stmt)
            conversation_history = list(reversed(history_result.scalars().all()))
            
            # BATCH MESSAGES: Collect all user messages since last AI response
            # This ensures AI responds to ALL messages sent during debounce period
            batched_user_text = user_text
            
            if conversation_history:
                # Find the last AI message index
                last_ai_index = -1
                for i in range(len(conversation_history) - 1, -1, -1):
                    if conversation_history[i].sender_type == "ai":
                        last_ai_index = i
                        break
                
                # Collect all user messages after last AI message
                user_messages_since_ai = []
                for msg in conversation_history[last_ai_index + 1:]:
                    if msg.sender_type == "user" and msg.content:
                        user_messages_since_ai.append(msg.content)
                
                if len(user_messages_since_ai) > 1:
                    # Multiple messages - combine them
                    batched_user_text = "\n".join(user_messages_since_ai)
                    logger.info(
                        f"πŸ“¦ Batching {len(user_messages_since_ai)} user messages for single AI response",
                        conversation_id=str(conversation_id)
                    )
                elif len(user_messages_since_ai) == 1:
                    batched_user_text = user_messages_since_ai[0]
            
            # Generate response to ALL batched messages
            ai_response = await ai_core.generate_sales_response(
                session=session,
                tenant=tenant,
                lead=lead,
                user_message=batched_user_text,
                conversation_history=conversation_history
            )
            
            # POST-GENERATION CHECK: Did new messages arrive during AI generation?
            # If yes, abort sending - the newer message's task will handle response
            post_gen_stmt = select(Message).where(
                Message.conversation_id == conversation_id,
                Message.sender_type == "user"
            ).order_by(Message.created_at.desc()).limit(1)
            
            post_gen_result = await session.execute(post_gen_stmt)
            post_gen_latest = post_gen_result.scalar_one_or_none()
            
            if post_gen_latest and post_gen_latest.id != user_message_id:
                # New message arrived DURING generation - abort!
                logger.info(
                    "⏭️ Post-generation abort: New message arrived during AI generation",
                    original_msg_id=str(user_message_id),
                    new_msg_id=str(post_gen_latest.id),
                    conversation_id=str(conversation_id)
                )
                # Reset lead status
                lead.processing_status = "idle"
                session.add(lead)
                await session.commit()
                return  # Exit - let the newer message's background task respond
            
            # --- BOOKING INTERCEPTION START ---
            import re
            from datetime import datetime
            from app.models.booking import Appointment, AppointmentStatus, Service, Resource  # Added Resource
            
            ai_text = ai_response["text"]
            # Updated regex to capture optional resource: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM] or [BOOK_CONFIRMED: YYYY-MM-DD HH:MM | Resource Name]
            booking_match = re.search(r'\[BOOK_CONFIRMED:\s*([\d\-]+\s[\d:]+)(?:\s*\|\s*(.+?))?\]', ai_text)
            
            if booking_match:
                try:
                    date_str = booking_match.group(1)
                    # Expected format: YYYY-MM-DD HH:MM
                    start_time = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
                    end_time = start_time.replace(minute=start_time.minute + 30) # Default 30 min
                    
                    # Find default service
                    srv_stmt = select(Service).where(Service.tenant_id == tenant_id).limit(1)
                    srv_result = await session.execute(srv_stmt)
                    default_srv = srv_result.scalar_one_or_none()
                    
                    if not default_srv:
                        # Auto-create default service if missing
                        default_srv = Service(
                            tenant_id=tenant_id,
                            name="General Consultation",
                            duration_minutes=30,
                            price=0.0,
                            is_active=True
                        )
                        session.add(default_srv)
                        await session.commit()
                        await session.refresh(default_srv)
                        logger.info(f"πŸ†• Auto-created default service for tenant {tenant_id}")
                    
                    # AUTO-CANCEL OLD BOOKINGS for this lead
                    old_appts_stmt = select(Appointment).where(
                        Appointment.lead_id == lead_id,
                        Appointment.status == AppointmentStatus.SCHEDULED
                    )
                    old_appts_result = await session.execute(old_appts_stmt)
                    old_appointments = old_appts_result.scalars().all()
                    
                    is_rescheduled = len(old_appointments) > 0  # Track if this is a reschedule
                    
                    for old_appt in old_appointments:
                        old_time = old_appt.start_time
                        old_appt.status = AppointmentStatus.CANCELLED
                        old_appt.notes = f"[ΠŸΠ΅Ρ€Π΅Π½Π΅ΡΠ΅Π½ΠΎ Π½Π° {start_time.strftime('%d.%m Π² %H:%M')}] {old_appt.notes or ''}"
                        session.add(old_appt)
                        logger.info(f"πŸ”„ Auto-cancelled old appointment {old_appt.id} for lead {lead_id}")
                        
                        # πŸ”” NOTIFY ADMIN about reschedule
                        try:
                            from app.services.notification import notification_service
                            old_appt.lead = lead
                            await notification_service.notify_reschedule(
                                tenant=tenant,
                                old_appointment=old_appt,
                                old_time=old_time,
                                new_time=start_time,
                                lead_name=lead.name or "ΠšΠ»ΠΈΠ΅Π½Ρ‚"
                            )
                        except Exception as ns_err:
                            logger.error(f"⚠️ Reschedule notification failed: {ns_err}")
                    
                    if old_appointments:
                        await session.commit()
                    
                    # CHECK FOR TIME SLOT CONFLICT
                    conflict_stmt = select(Appointment).where(
                        Appointment.tenant_id == tenant_id,
                        Appointment.status == AppointmentStatus.SCHEDULED,
                        Appointment.start_time == start_time
                    )
                    conflict_result = await session.execute(conflict_stmt)
                    existing_booking = conflict_result.scalar_one_or_none()
                    
                    if existing_booking:
                        # Slot is taken - find alternatives and suggest them
                        logger.warning(f"⚠️ Time slot {start_time} already taken, searching alternatives")
                        
                        # Find next 3 available slots
                        available_slots = await _find_available_slots(
                            session=session,
                            tenant_id=tenant_id,
                            requested_time=start_time,
                            count=3
                        )
                        
                        ai_text = ai_text.replace(booking_match.group(0), "").strip()
                        
                        if available_slots:
                            # Format slots nicely
                            slots_formatted = []
                            for slot in available_slots:
                                slots_formatted.append(slot.strftime("%d.%m Π² %H:%M"))
                            
                            ai_text += f"\n\n⚠️ К соТалСнию, это врСмя ΡƒΠΆΠ΅ занято.\n\nπŸ“… Π‘Π»ΠΈΠΆΠ°ΠΉΡˆΠΈΠ΅ свободныС слоты:\nβ€’ " + "\nβ€’ ".join(slots_formatted) + "\n\nКакоС врСмя Π²Π°ΠΌ ΠΏΠΎΠ΄Ρ…ΠΎΠ΄ΠΈΡ‚?"
                        else:
                            ai_text += "\n\n⚠️ К соТалСнию, это врСмя ΡƒΠΆΠ΅ занято. ΠŸΠΎΠΆΠ°Π»ΡƒΠΉΡΡ‚Π°, ΠΏΡ€Π΅Π΄Π»ΠΎΠΆΠΈΡ‚Π΅ Π΄Ρ€ΡƒΠ³ΠΎΠ΅ врСмя."
                        
                        ai_response["text"] = ai_text
                    else:
                        # CHECK FOR DUPLICATE: Same lead + same time = already booked
                        duplicate_stmt = select(Appointment).where(
                            Appointment.lead_id == lead_id,
                            Appointment.status == AppointmentStatus.SCHEDULED,
                            Appointment.start_time == start_time
                        )
                        duplicate_result = await session.execute(duplicate_stmt)
                        existing_for_lead = duplicate_result.scalar_one_or_none()
                        
                        if existing_for_lead:
                            # Already booked for this lead at this time - just confirm, don't create duplicate
                            logger.info(f"πŸ“… Booking already exists for lead {lead_id} at {start_time}, skipping duplicate")
                            # Remove the BOOK_CONFIRMED tag from response since booking already exists
                            ai_text = ai_text.replace(booking_match.group(0), "").strip()
                            ai_response["text"] = ai_text
                        else:
                            # Create new appointment with comprehensive notes
                            booking_info = _extract_booking_info_from_conversation(conversation_history, lead, user_text)
                        
                            # Build informative notes
                            notes_parts = [booking_info["name"]]
                            if booking_info["phone"]:
                                notes_parts.append(f"πŸ“ž {booking_info['phone']}")
                            notes_parts.append(f"Π’Π΅ΠΌΠ°: {booking_info['topic']}")
                            notes = " | ".join(notes_parts)
                            
                            # RESOURCE LOOKUP: Find resource by name if specified in tag
                            resource_name = booking_match.group(2) if booking_match.lastindex >= 2 else None
                            resource_id = None
                            selected_resource = None
                            
                            if resource_name:
                                resource_name = resource_name.strip()
                                # Search for resource by name (case-insensitive partial match)
                                resource_stmt = select(Resource).where(
                                    Resource.tenant_id == tenant_id,
                                    Resource.is_active == True,
                                    Resource.name.ilike(f"%{resource_name}%")
                                )
                                resource_result = await session.execute(resource_stmt)
                                selected_resource = resource_result.scalar_one_or_none()
                                
                                if selected_resource:
                                    resource_id = selected_resource.id
                                    logger.info(f"πŸ“Œ Booking to resource: {selected_resource.name} (ID: {resource_id})")
                                else:
                                    logger.warning(f"⚠️ Resource '{resource_name}' not found, booking without resource")
                            
                            new_appt = Appointment(
                                tenant_id=tenant_id,
                                lead_id=lead_id,
                                service_id=default_srv.id,
                                resource_id=resource_id,  # Now saves resource!
                                start_time=start_time,
                                end_time=end_time,
                                status=AppointmentStatus.SCHEDULED,
                                notes=notes
                            )
                            session.add(new_appt)
                            await session.commit()
                            
                            logger.info(f"πŸ“… AI Booked Appointment: {date_str} for Lead {lead_id}" + 
                                       (f" with Resource {resource_name}" if resource_name else ""))
                            
                            # πŸ”” NOTIFY: Send to resource owner if telegram_chat_id set, else to tenant
                            if not is_rescheduled:
                                try:
                                    from app.services.notification import notification_service
                                    new_appt.lead = lead
                                    new_appt.service = default_srv
                                    
                                    # Determine notification target
                                    resource_telegram_id = None
                                    if selected_resource and selected_resource.telegram_chat_id:
                                        resource_telegram_id = selected_resource.telegram_chat_id
                                        logger.info(f"πŸ“± Sending notification to resource: {selected_resource.name} ({resource_telegram_id})")
                                    
                                    # Pass AI summary and resource notification target
                                    await notification_service.notify_new_appointment(
                                        tenant, 
                                        new_appt, 
                                        ai_summary=lead.ai_summary_json,
                                        resource_telegram_id=resource_telegram_id  # New: notify resource directly
                                    )
                                except Exception as ns_err:
                                    logger.error(f"⚠️ Notification failed: {ns_err}")
                            else:
                                logger.info(f"πŸ“… Skipping notification for rescheduled appointment {new_appt.id}")

                            # Remove tag from text
                            ai_text = ai_text.replace(booking_match.group(0), "").strip()
                            ai_text += "\n\nβœ… (БистСма: Π—Π°ΠΏΠΈΡΡŒ создана ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ!)"
                            
                            # Update response text in object
                            ai_response["text"] = ai_text
                    
                except Exception as e:
                    logger.error(f"❌ Failed to process AI booking tag: {e}")
                    ai_response["text"] += "\n\n⚠️ (БистСма: Ошибка ΠΏΡ€ΠΈ сохранСнии записи. ΠœΠ΅Π½Π΅Π΄ΠΆΠ΅Ρ€ свяТСтся с Π²Π°ΠΌΠΈ.)"
            # --- BOOKING INTERCEPTION END ---


            # --- ORDER INTERCEPTION START ---
            import json
            from app.models.order import Order, OrderItem, OrderStatus
            from app.models.product import Product

            order_match = re.search(r'\[CREATE_ORDER:\s*({.*?})\]', ai_text, re.DOTALL)
            
            if order_match:
                try:
                    json_str = order_match.group(1)
                    # Sanitize JSON if needed (AI might leave trailing commas)
                    # For now assume valid JSON from Gemini 1.5
                    order_data = json.loads(json_str)
                    
                    logger.info(f"πŸ›’ Processing Order Request: {json_str}")
                    
                    # 1. Create Order Shell
                    new_order = Order(
                        tenant_id=tenant_id,
                        lead_id=lead_id,
                        status=OrderStatus.NEW,
                        total_amount=0.0
                    )
                    session.add(new_order)
                    await session.flush() # Get ID
                    
                    total_sum = 0.0
                    items_info_text = []
                    currency = "USD"

                    # 2. Process Items
                    for item in order_data.get("items", []):
                        p_name = item.get("product_name")
                        qty = int(item.get("quantity", 1))
                        
                        # Find product (Best Effort Fuzzy Match)
                        # We use ILIKE for case-insensitive partial match
                        p_stmt = select(Product).where(
                            Product.tenant_id == tenant_id,
                            Product.name.ilike(f"%{p_name}%")
                        ).limit(1)
                        p_res = await session.execute(p_stmt)
                        product = p_res.scalar_one_or_none()
                        
                        price = 0.0
                        p_id = None
                        
                        if product:
                            price = product.price
                            p_id = product.id
                            currency = product.currency # Use last product's currency
                        else:
                            # Fallback if product not found by name
                             logger.warning(f"⚠️ Product '{p_name}' not found in DB")
                        
                        line_total = price * qty
                        total_sum += line_total
                        
                        order_item = OrderItem(
                            order_id=new_order.id,
                            product_id=p_id,
                            product_name=p_name,
                            quantity=qty,
                            unit_price=price,
                            total_price=line_total
                        )
                        session.add(order_item)
                        items_info_text.append(f"{p_name} x{qty}")

                    # 3. Update Order Total and Customer details if provided
                    new_order.total_amount = total_sum
                    
                    customer_info = order_data.get("customer", {})
                    notes = order_data.get("notes", "")
                    
                    # Update Lead info if missing using gathered data
                    if customer_info.get("name") and not lead.name:
                         lead.name = customer_info.get("name")
                         session.add(lead)
                         
                    # Save order notes
                    if notes:
                         # You might want a 'notes' field in Order model, currently absent?
                         # I defined Order model earlier. Did I add notes?
                         # Let's check model definition. Assuming NO for now, log it.
                         logger.info(f"πŸ“ Order Notes: {notes}")

                    session.add(new_order)
                    await session.commit()
                    
                    logger.info(f"βœ… AI Created Order {new_order.id} for Lead {lead_id}")
                    
                    # 4. Clean up response & Add Confirmation
                    ai_text = ai_text.replace(order_match.group(0), "").strip()
                    confirmation_msg = f"\n\nβœ… Π—Π°ΠΊΠ°Π· β„–{str(new_order.id)[:8]} ΠΎΡ„ΠΎΡ€ΠΌΠ»Π΅Π½!\nπŸ“¦ Π’ΠΎΠ²Π°Ρ€Ρ‹: {', '.join(items_info_text)}\nπŸ’° Π˜Ρ‚ΠΎΠ³ΠΎ: {total_sum:.2f} {currency}"
                    ai_text += confirmation_msg
                    
                    # Update response text object
                    ai_response["text"] = ai_text

                    # πŸ”” NOTIFY ADMIN
                    try:
                        from app.services.notification import notification_service
                        await notification_service.notify_new_order(tenant, new_order, '\n'.join(items_info_text))
                    except Exception as ns_err:
                        logger.error(f"⚠️ Notification failed: {ns_err}")
                    
                except Exception as e:
                    logger.error(f"❌ Failed to process AI Order tag: {e}")
                    import traceback
                    traceback.print_exc()
                    # Fallback message
                    # Don't fail the chat, just append error note
                    ai_text = ai_text.replace(order_match.group(0), "").strip()
                    ai_text += "\n\n⚠️ (БистСма: Заявка принята, Π½ΠΎ ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка автоматичСской рСгистрации. ΠœΠ΅Π½Π΅Π΄ΠΆΠ΅Ρ€ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΡ‚ Π²Ρ€ΡƒΡ‡Π½ΡƒΡŽ.)"
                    ai_response["text"] = ai_text
            
            # --- ORDER INTERCEPTION END ---

            # --- BANNED WORDS POST-CHECK ---
            # Extra safety: replace banned words even if AI ignores the prompt rule
            if tenant.banned_words:
                ai_text = ai_response["text"]
                for word in tenant.banned_words:
                    if word and word.lower() in ai_text.lower():
                        # Case-insensitive replacement
                        import re
                        pattern = re.compile(re.escape(word), re.IGNORECASE)
                        ai_text = pattern.sub("***", ai_text)
                        logger.warning(f"🚫 Replaced banned word: {word}")
                ai_response["text"] = ai_text
            # --- BANNED WORDS POST-CHECK END ---

            # --- MARKDOWN STRIPPING (STRICT PLAIN TEXT) ---
            # Remove **bold**, __bold__, ## Headers to ensure plain text
            if ai_response.get("text"):
                txt = ai_response["text"]
                import re
                
                # 1. Remove Headers (## Title)
                txt = re.sub(r'^#+\s+', '', txt, flags=re.MULTILINE)
                
                # 2. Remove **Bold** / __Bold__
                # Note: We replace **text** with text.
                txt = re.sub(r'\*\*(.*?)\*\*', r'\1', txt)
                txt = re.sub(r'__(.*?)__', r'\1', txt)
                
                # 3. Remove "Photo 1:" style hallucinations if standard pattern
                # (Optional, but user complained about it)
                txt = re.sub(r'\*?\*?Π€ΠΎΡ‚ΠΎ \d+:.*?\*?\*?', '', txt, flags=re.IGNORECASE)
                
                ai_response["text"] = txt.strip()
            # --- MARKDOWN STRIPPING END ---

            # --- CLEAN UP INTERNAL TAGS BEFORE SAVE ---
            # Remove [SEND_VOICE] tag so it doesn't appear in UI
            if "[SEND_VOICE]" in ai_response["text"]:
                ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip()
            
            # Process [SEND_MEDIA:ID] tags - extract media IDs to send
            media_ids_to_send = []
            media_pattern = r'\[SEND_MEDIA:([a-f0-9-]+)\]'
            media_matches = re.findall(media_pattern, ai_response["text"], re.IGNORECASE)
            if media_matches:
                media_ids_to_send = list(set(media_matches))  # Unique IDs
                logger.info(f"πŸ“ AI wants to send {len(media_ids_to_send)} media files: {media_ids_to_send}")
                # Clean tags from response
                ai_response["text"] = re.sub(media_pattern, '', ai_response["text"]).strip()
            
            ai_message = Message(
                tenant_id=tenant.id,
                conversation_id=conversation.id,
                sender_type="ai",
                content=ai_response["text"],
                status=MessageStatus.PENDING,  # Initialize as PENDING
                prompt_tokens=ai_response["prompt_tokens"],
                completion_tokens=ai_response["completion_tokens"],
                model_used=settings.GEMINI_MODEL
            )
            session.add(ai_message)
            await session.commit()
            await session.refresh(ai_message)
            
            # Notify WebSocket clients about AI response (real-time updates)
            try:
                from app.api.websocket_chat import notify_new_message
                await notify_new_message(str(lead_id), {
                    "id": str(ai_message.id),
                    "content": ai_message.content,
                    "sender_type": "ai",
                    "created_at": ai_message.created_at.isoformat() if ai_message.created_at else None,
                    "media_url": None,
                    "media_type": None
                })
                logger.debug(f"πŸ“‘ WebSocket notified: AI message {ai_message.id}")
            except Exception as e:
                logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}")
            
            # Send response to Telegram
            logger.info(
                "πŸ“€ Sending AI response to Telegram",
                chat_id=chat_id,
                response_length=len(ai_response["text"])
            )
            
            # Determine Channel
            channel = conversation.channel if conversation.channel else 'telegram'
            send_success = False
            
            try:
                if channel == 'telegram':
                    # Pre-send Media (Images / Files) so we can reply to them
                    media_reply_id = None
                    
                    # 1. Product Images
                    prod_msg_id = await send_product_images_if_mentioned(
                        session=session,
                        tenant_id=tenant.id,
                        bot_token=tenant.telegram_bot_token,
                        chat_id=chat_id,
                        ai_text=ai_response["text"],
                        conversation_id=conversation.id
                    )
                    if prod_msg_id:
                        media_reply_id = prod_msg_id
                        
                    # 2. Media Files ([SEND_MEDIA:ID])
                    if media_ids_to_send:
                        media_msg_id = await send_media_files(
                            session=session,
                            tenant_id=tenant.id,
                            lead_id=lead_id,
                            bot_token=tenant.telegram_bot_token,
                            chat_id=chat_id,
                            media_ids=media_ids_to_send,
                            conversation_id=conversation.id
                        )
                        if media_msg_id:
                            media_reply_id = media_msg_id # Prioritize explicit media for reply

                    # Count AI messages to detect first message
                    ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai'])
                    is_first_message = ai_msg_count == 0
                    
                    # Check if AI wants to send voice (proactive) or user sent voice (reactive)
                    # AI can add [SEND_VOICE] tag when it detects persuasion/trust moment
                    ai_wants_voice = "[SEND_VOICE]" in ai_response["text"]
                    
                    # === CHECK USER'S LATEST VOICE PREFERENCE ===
                    # Use smart detection from response_generator which tracks LATEST preference
                    # (handles both "no voice" and "yes voice" requests, using the most recent one)
                    user_requested_no_voice = ai_response.get("user_requested_no_voice", False)
                    
                    if user_requested_no_voice:
                        logger.info("πŸ”‡ USER REQUESTED NO VOICE (latest preference from response_generator)")
                    
                    # If user requested no voice, disable all voice triggers
                    if user_requested_no_voice:
                        ai_wants_voice = False
                        respond_with_voice = False
                        logger.info("πŸ”‡ Voice DISABLED because user requested no voice messages")
                    
                    # === SMART VOICE DETECTION (LLM-based semantic analysis) ===
                    voice_trigger_reason = None
                    user_text_lower = user_text.lower() if user_text else ""
                    ai_text_lower = ai_response["text"].lower()
                    
                    # Count recent voice messages to limit frequency
                    recent_ai_voice_count = 0
                    for msg in conversation_history[-10:]:  # Last 10 messages
                        if getattr(msg, 'sender_type', None) == 'ai':
                            if getattr(msg, 'media_type', None) == 'voice' or getattr(msg, 'media_url', None):
                                recent_ai_voice_count += 1
                    
                    # FREQUENCY LIMIT: Only 1 voice per 5+ messages
                    voice_allowed_by_frequency = recent_ai_voice_count < 1 or ai_msg_count % 5 == 0
                    
                    # 0. USER EXPLICITLY REQUESTED VOICE - highest priority, bypasses frequency limit
                    user_requested_voice = ai_response.get("user_requested_voice", False)
                    if not ai_wants_voice and tenant.voice_enabled and not user_requested_no_voice and user_requested_voice:
                        voice_trigger_reason = "USER_REQUESTED"
                        ai_wants_voice = True
                        logger.info("πŸŽ™οΈ Voice triggered: USER explicitly requested voice (bypasses frequency limit)")
                    
                    # Smart triggers (subject to frequency limit)
                    elif not ai_wants_voice and tenant.voice_enabled and not user_requested_no_voice and voice_allowed_by_frequency:
                        # 1. FIRST MESSAGE - greeting (always voice for trust)
                        if is_first_message:
                            voice_trigger_reason = "FIRST_MESSAGE"
                            ai_wants_voice = True
                        
                        # 2. SMART LLM ANALYSIS for critical moments
                        else:
                            try:
                                voice_ai_core = get_ai_core()
                                
                                voice_analysis = await voice_ai_core.llm.generate_response(
                                    prompt=f"""Is this a CRITICAL MOMENT that requires a personal voice message to build trust?

User's message: "{user_text}"
AI's response: "{ai_response['text'][:200]}..."

Critical moments are ONLY:
- OBJECTION: Client has serious doubts, concerns about price/quality, hesitation (not just questions)
- UPSET: Client is frustrated, angry, disappointed, complaining
- DEAL_CLOSING: Client explicitly agrees to buy, pay, book, sign up

Answer with ONE word:
- OBJECTION - if client has serious doubts/objections
- UPSET - if client is frustrated/angry
- DEAL_CLOSING - if client agrees to purchase/book
- NONE - if this is just a normal conversation (most messages)""",
                                    system_instruction="Output only: OBJECTION, UPSET, DEAL_CLOSING, or NONE. Most messages should be NONE.",
                                    context=None,
                                    chat_history=[]
                                )
                                
                                llm_result = voice_analysis["text"].strip().upper()
                                if "OBJECTION" in llm_result:
                                    voice_trigger_reason = "CLIENT_OBJECTION"
                                    ai_wants_voice = True
                                elif "UPSET" in llm_result:
                                    voice_trigger_reason = "CLIENT_UPSET"
                                    ai_wants_voice = True
                                elif "DEAL_CLOSING" in llm_result:
                                    voice_trigger_reason = "DEAL_CLOSING"
                                    ai_wants_voice = True
                                else:
                                    logger.info(f"🧠 LLM: No critical moment detected (NONE)")
                            except Exception as e:
                                logger.warning(f"Voice LLM analysis failed: {e}")
                    
                    # Log if voice was blocked by frequency
                    if not voice_allowed_by_frequency and not user_requested_no_voice:
                        logger.info(f"πŸ”‡ Voice blocked by frequency limit (recent voice count: {recent_ai_voice_count})")
                    
                    if voice_trigger_reason:
                        logger.info(f"πŸŽ™οΈ Smart voice trigger: {voice_trigger_reason}")
                    
                    should_send_voice = (
                        tenant.voice_enabled and 
                        (respond_with_voice or ai_wants_voice)
                    )
                    
                    logger.info(f"πŸ”Š Voice decision: enabled={tenant.voice_enabled}, trigger={voice_trigger_reason}, ai_wants={ai_wants_voice}, RESULT={should_send_voice}")
                    
                    # Clean up voice tag from response text
                    if ai_wants_voice:
                        ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip()
                    
                    if should_send_voice:
                        try:
                            from app.services.voice_service import voice_service
                            from app.services.telegram_service import telegram_service
                            
                            # Generate speech using tenant's selected voice
                            voice_id = getattr(tenant, 'voice_id', 'professional_male')
                            custom_voice_url = getattr(tenant, 'voice_reference_url', None)
                            logger.info(f"πŸŽ™οΈ Generating voice response (voice={voice_id})...")
                            audio_bytes, extracted_items = await voice_service.generate_audio(
                                text=ai_response["text"],
                                voice=voice_id,
                                custom_voice_url=custom_voice_url
                            )
                            
                            # Upload audio to Supabase for platform playback
                            try:
                                from app.core.supabase import supabase_client
                                import time
                                
                                if supabase_client and audio_bytes:
                                    bucket = "chat-attachments"
                                    ts = int(time.time())
                                    path = f"{tenant_id}/{conversation_id}/{ts}_ai_voice.mp3"
                                    
                                    supabase_client.storage.from_(bucket).upload(
                                        path=path,
                                        file=audio_bytes,
                                        file_options={"content-type": "audio/mpeg"}
                                    )
                                    voice_media_url = supabase_client.storage.from_(bucket).get_public_url(path)
                                    
                                    # Update AI message with media_url
                                    ai_message.media_url = voice_media_url
                                    ai_message.media_type = "audio/mpeg"
                                    ai_message.media_name = "ai_voice.mp3"
                                    session.add(ai_message)
                                    await session.commit()
                                    
                                    logger.info(f"βœ… AI voice uploaded to Supabase: {voice_media_url[:60]}...")
                                    
                                    # Notify WebSocket again with updated media_url
                                    try:
                                        await notify_new_message(str(lead_id), {
                                            "id": str(ai_message.id),
                                            "content": ai_message.content,
                                            "sender_type": "ai",
                                            "created_at": ai_message.created_at.isoformat() if ai_message.created_at else None,
                                            "media_url": voice_media_url,
                                            "media_type": "audio/mpeg",
                                            "media_name": "ai_voice.mp3"
                                        })
                                        logger.debug(f"πŸ“‘ WebSocket updated with AI voice media_url")
                                    except Exception as ws_err:
                                        logger.warning(f"⚠️ WebSocket voice update failed: {ws_err}")
                            except Exception as upload_err:
                                logger.warning(f"⚠️ AI voice upload to Supabase failed: {upload_err}")
                            
                            # Send voice message to Telegram
                            # Use dict return and reply_to_message_id
                            voice_result = await telegram_service.send_voice(
                                token=tenant.telegram_bot_token,
                                chat_id=chat_id,
                                audio_bytes=audio_bytes,
                                reply_to_message_id=media_reply_id
                            )
                            send_success = voice_result.get("success", False)
                            
                            if send_success:
                                logger.info(f"🎀 Voice response sent to chat {chat_id}")
                                
                                # πŸ“ SEND EXTRACTED SENSITIVE DATA AS SEPARATE TEXT MESSAGE
                                if extracted_items:
                                    # Format extracted items for text message
                                    text_parts = []
                                    for item in extracted_items:
                                        item_type = item.get("type", "")
                                        value = item.get("value", "")
                                        if item_type == "link":
                                            text_parts.append(f"πŸ”— {value}")
                                        elif item_type == "card":
                                            text_parts.append(f"πŸ’³ {value}")
                                        elif item_type == "email":
                                            text_parts.append(f"πŸ“§ {value}")
                                        elif item_type == "iban":
                                            text_parts.append(f"🏦 {value}")
                                        else:
                                            text_parts.append(value)
                                    
                                    if text_parts:
                                        extracted_text = "\n".join(text_parts)
                                        logger.info(f"πŸ“ Sending {len(extracted_items)} extracted items as text")
                                        await send_telegram_message(
                                            bot_token=tenant.telegram_bot_token,
                                            chat_id=chat_id,
                                            text=extracted_text,
                                            reply_to_message_id=media_reply_id
                                        )
                            else:
                                # Fallback to text if voice fails
                                logger.warning("⚠️ Voice send failed, falling back to text")
                                send_success = await send_telegram_message(
                                    bot_token=tenant.telegram_bot_token,
                                    chat_id=chat_id,
                                    text=ai_response["text"],
                                    reply_to_message_id=media_reply_id
                                )
                        except Exception as voice_err:
                            logger.error(f"❌ Voice generation failed: {voice_err}, falling back to text")
                            send_success = await send_telegram_message(
                                bot_token=tenant.telegram_bot_token,
                                chat_id=chat_id,
                                text=ai_response["text"],
                                reply_to_message_id=media_reply_id
                            )
                    else:
                        # Standard text response
                        send_success = await send_telegram_message(
                            bot_token=tenant.telegram_bot_token,
                            chat_id=chat_id,
                            text=ai_response["text"],
                            reply_to_message_id=media_reply_id
                        )
                elif channel == 'linkedin':
                    from app.services.linkedin_service import linkedin_service
                    if lead.linkedin_urn:
                        li_config = tenant.linkedin_config or {}
                        send_success = await linkedin_service.send_message(
                            recipient_urn=lead.linkedin_urn,
                            text=ai_response["text"],
                            cookies=li_config
                        )
                    else:
                        logger.error("LinkedIn URN missing for lead, cannot send AI response")
                elif channel == 'whatsapp':
                    # Assuming WhatsApp service is available
                    from app.services.meta_whatsapp import whatsapp_cloud_service
                    
                    # Need tenant object for Cloud API
                    # tenant is already available in scope
                    try:
                        await whatsapp_cloud_service.send_text_message(
                            tenant=tenant,
                            to_phone=lead.telegram_id, # Re-using ID field 
                            text=ai_response["text"]
                        )
                        send_success = True
                    except Exception as e:
                        logger.error(f"WhatsApp Cloud send failed: {e}")
                        send_success = False

                # Update Message Status
                if send_success:
                    ai_message.status = MessageStatus.SENT
                    logger.info(
                        "βœ… AI response sent successfully to Telegram",
                        chat_id=chat_id,
                        lead_id=str(lead.id)
                    )
                else:
                    ai_message.status = MessageStatus.FAILED
                    logger.error(
                        "❌ Failed to send AI response to Telegram",
                        chat_id=chat_id,
                        lead_id=str(lead.id)
                    )
                
                session.add(ai_message)
                await session.commit()
                
            except Exception as e:
                logger.error(f"❌ Exception during message sending: {e}")
                ai_message.status = MessageStatus.FAILED
                session.add(ai_message)
                await session.commit()

            # --- SMART ESCALATION CHECK ---
            # Analyze conversation for need of human intervention
            try:
                from app.services.escalation_service import escalation_service
                
                # Build conversation history for analysis
                conv_history = []
                if conversation_history:
                    for msg in conversation_history[-10:]:  # Last 10 messages
                        conv_history.append({
                            "sender_type": msg.sender_type,
                            "content": msg.content or ""
                        })
                
                # Analyze the exchange
                escalation_result = await escalation_service.analyze_message(
                    user_message=user_text or "",
                    ai_response=ai_response["text"],
                    conversation_history=conv_history,
                    heat_score=getattr(lead, 'heat_score', 50) or 50,
                    current_stage=getattr(lead, 'current_stage_id', None)
                )
                
                if escalation_result.should_escalate:
                    # CHANGED: Only notify manager, DON'T disable AI
                    # AI continues to work, manager gets notification
                    # conversation.human_takeover = True  # REMOVED - AI keeps working
                    lead.needs_attention = True
                    lead.escalation_reason = escalation_result.reason.value
                    lead.escalation_at = datetime.utcnow()
                    # session.add(conversation)  # Not modifying conversation
                    session.add(lead)
                    await session.commit()
                    
                    logger.warning(
                        f"🚨 ESCALATION - NOTIFYING MANAGER (AI continues): {escalation_result.reason.value}",
                        lead_id=str(lead.id),
                        details=escalation_result.details
                    )
                    
                    # Send notifications to manager
                    await escalation_service.send_escalation_notification(
                        lead_id=str(lead.id),
                        lead_name=lead.name or "Unknown",
                        reason=escalation_result.reason,
                        urgency=escalation_result.urgency,
                        details=escalation_result.details,
                        last_message=user_text or "",
                        tenant_id=str(tenant.id),
                        channel=channel
                    )
                    
                elif escalation_result.notify_only:
                    # High-value deal - just notify, don't takeover
                    logger.info(
                        f"🟒 HIGH-VALUE ALERT: {escalation_result.details}",
                        lead_id=str(lead.id)
                    )
                    await escalation_service.send_escalation_notification(
                        lead_id=str(lead.id),
                        lead_name=lead.name or "Unknown",
                        reason=escalation_result.reason,
                        urgency=escalation_result.urgency,
                        details=escalation_result.details,
                        last_message=user_text or "",
                        tenant_id=str(tenant.id),
                        channel=channel
                    )
                    
            except Exception as esc_err:
                logger.warning(f"⚠️ Escalation check failed (non-critical): {esc_err}")
            # --- END ESCALATION CHECK ---

            # TASK 3: AUTO-ANALYZE LEAD after AI response (UPDATE AI SUMMARY)
            # This runs analyze_lead() to update the 11-point summary
            logger.info(
                "🧠 Starting automatic lead analysis (updating summary)...",
                lead_id=str(lead.id)
            )
            
            try:
                # Set status to analyzing
                lead.processing_status = "analyzing"
                session.add(lead)
                await session.commit()
                
                # Re-fetch conversation history (now includes AI response)
                analysis_stmt = select(Message).where(
                    Message.conversation_id == conversation.id
                ).order_by(Message.created_at)
                
                analysis_result = await session.execute(analysis_stmt)
                all_messages = list(analysis_result.scalars().all())
                
                # Run analysis (updates psychotype, heat_score, ai_summary_json)
                analysis = await ai_core.analyze_lead(
                    session=session,
                    lead=lead,
                    conversation_history=all_messages
                )
                
                logger.info(
                    "βœ… Lead analysis complete",
                    lead_id=str(lead.id),
                    heat_score=analysis.get('heat_score'),
                    psychotype=analysis.get('psychotype'),
                    summary_generated=analysis.get('summary_generated')
                )
                
                # πŸ“‘ REAL-TIME SUMMARY UPDATE via WebSocket
                try:
                    from app.api.websocket_chat import notify_lead_updated
                    await notify_lead_updated(str(lead.id), {
                        "id": str(lead.id),
                        "ai_summary_json": lead.ai_summary_json,
                        "heat_score": lead.heat_score,
                        "heat_level": lead.heat_level.value if lead.heat_level else "unknown",
                        "psychotype": lead.psychotype.value if lead.psychotype else "unknown",
                        "name": lead.name,
                        "current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None
                    })
                    logger.debug(f"πŸ“‘ WebSocket: Real-time summary update sent for lead {lead.id}")
                except Exception as ws_err:
                    logger.warning(f"⚠️ WebSocket summary update failed (non-critical): {ws_err}")
                
            except Exception as analysis_error:
                logger.error(
                    "❌ Auto-analysis failed (non-critical)",
                    lead_id=str(lead.id),
                    error=str(analysis_error),
                    exc_info=True
                )
            
            # Set back to IDLE
            lead.processing_status = "idle"
            session.add(lead)
            await session.commit()
            
            logger.info(
                "AI response sent to Telegram",
                chat_id=chat_id,
                lead_id=str(lead.id)
            )
            
        except Exception as e:
            logger.error(
                "Background AI processing failed",
                lead_id=str(lead_id),
                error=str(e),
                exc_info=True
            )
            # Set error status
            try:
                lead = await session.get(Lead, lead_id)
                if lead:
                    lead.processing_status = "error"
                    session.add(lead)
                    await session.commit()
            except:
                pass


async def analyze_lead_background(
    lead_id: UUID,
    conversation_id: UUID
):
    """
    Background task to analyze lead.
    Creates its own database session.
    Updates psychotype, heat score, and AI summary.
    """
    from app.core.database import async_session_maker
    
    async with async_session_maker() as session:
        try:
            # Get lead
            lead = await session.get(Lead, lead_id)
            if not lead:
                return
            
            # Set analyzing status
            lead.processing_status = "analyzing"
            session.add(lead)
            await session.commit()
            
            # Get conversation history
            stmt = select(Message).where(
                Message.conversation_id == conversation_id
            ).order_by(Message.created_at)
            
            result = await session.execute(stmt)
            messages = result.scalars().all()
            
            if len(messages) < 3:
                lead.processing_status = "idle"
                session.add(lead)
                await session.commit()
                return
            
            # Run analysis
            ai_core = get_ai_core()
            analysis = await ai_core.analyze_lead(
                session=session,
                lead=lead,
                conversation_history=list(messages)
            )
            
            # Set back to IDLE after analysis complete
            lead.processing_status = "idle"
            session.add(lead)
            await session.commit()
            
            logger.info(
                "Lead analysis complete",
                lead_id=str(lead.id),
                heat_score=lead.heat_score,
                heat_level=lead.heat_level.value,
                psychotype=lead.psychotype.value
            )
            
            # Send email notification if HOT lead
            if lead.heat_score >= settings.HOT_LEAD_THRESHOLD:
                logger.warning(
                    "Hot lead detected",
                    lead_id=str(lead.id),
                    lead_name=lead.name,
                    heat_score=lead.heat_score
                )
                
                # Get lead owner (first user of tenant) for notification
                from app.models import User
                user_stmt = select(User).where(
                    User.tenant_id == lead.tenant_id,
                    User.is_active == True
                ).limit(1)
                user_result = await session.execute(user_stmt)
                owner = user_result.scalar_one_or_none()
                
                if owner and owner.email:
                    email_service = get_email_service()
                    await email_service.send_hot_lead_notification(
                        manager_email=owner.email,
                        lead_name=lead.name or "Unknown Lead",
                        lead_id=str(lead.id),
                        heat_score=lead.heat_score,
                        summary=lead.ai_summary_json or {}
                    )
                    logger.info(
                        "Hot lead notification sent",
                        to_email=owner.email,
                        lead_id=str(lead.id)
                    )
        
        except Exception as e:
            logger.error(
                "Background analysis failed",
                lead_id=str(lead_id),
                error=str(e),
                exc_info=True
            )
            
            # Set error status
            try:
                lead = await session.get(Lead, lead_id)
                if lead:
                    lead.processing_status = "error"
                    session.add(lead)
                    await session.commit()
            except:
                pass