Spaces:
Running

File size: 113,620 Bytes
cd61bf7
 
22ede4b
cd61bf7
 
 
 
 
 
 
1c28cfd
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
8a72cf3
 
33256ac
101c2eb
6d3b96e
 
101c2eb
 
 
8a72cf3
101c2eb
 
 
 
 
 
 
 
 
 
33256ac
101c2eb
a5a659b
 
 
 
 
 
 
 
101c2eb
33256ac
101c2eb
a5a659b
 
 
 
 
 
 
101c2eb
a5a659b
 
 
 
 
8a72cf3
 
 
a5a659b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a72cf3
 
6d3b96e
 
 
10e7b9a
6d3b96e
 
 
 
 
 
10e7b9a
 
 
 
 
 
 
 
33256ac
10e7b9a
 
 
 
 
33256ac
 
 
8a72cf3
a5a659b
8a72cf3
 
 
 
 
a5a659b
 
 
 
 
 
 
10e7b9a
 
33256ac
10e7b9a
 
 
 
 
 
 
 
6d3b96e
10e7b9a
6d3b96e
10e7b9a
 
6d3b96e
 
 
 
33256ac
 
101c2eb
 
df97a07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
e9f9cca
80c9efd
8b679a2
 
 
80c9efd
8b679a2
 
 
36378a5
 
 
 
8b679a2
 
 
 
 
 
e9f9cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b679a2
 
 
 
 
 
80c9efd
8b679a2
 
80c9efd
 
e9f9cca
 
2cc83d8
e9f9cca
ab96df2
e9f9cca
 
ab96df2
 
e9f9cca
 
 
 
 
 
8b679a2
 
 
80c9efd
 
cca9494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a54992
 
 
a76cbc6
 
5a54992
 
 
 
 
 
 
 
 
 
a76cbc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a54992
 
a76cbc6
cd61bf7
cca9494
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
 
 
 
34739db
41be229
34739db
41be229
 
 
cd61bf7
 
 
 
41be229
 
 
 
cd61bf7
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41be229
b6db670
 
 
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
 
bc09d91
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b38cc4d
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04373b4
 
 
 
 
 
 
 
80c9efd
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dba971d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333903b
 
 
 
 
 
 
cd61bf7
 
 
 
dba971d
cd61bf7
 
 
464c219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6404030
 
 
bc65edb
6404030
 
bc65edb
 
6404030
 
 
 
 
 
 
 
 
 
 
 
 
df4fd36
 
 
 
 
 
 
 
 
 
 
 
 
 
aecbce0
c6f8a06
aecbce0
e3cd75f
07ef569
c6f8a06
07ef569
aecbce0
 
 
 
 
 
 
 
c6f8a06
aecbce0
 
 
 
 
 
 
 
 
c6f8a06
aecbce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f8a06
aecbce0
 
 
 
07ef569
c6f8a06
 
 
 
 
 
 
 
 
 
 
9fb267a
39ac4b7
c6f8a06
 
 
 
 
 
 
 
 
 
 
39ac4b7
449cfa0
c6f8a06
39ac4b7
 
fda4900
39ac4b7
 
 
 
 
 
 
bc65edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ac4b7
 
 
 
bc65edb
39ac4b7
 
 
 
 
 
 
 
bc65edb
 
39ac4b7
bc65edb
39ac4b7
 
 
 
 
bc65edb
 
 
 
 
 
 
 
39ac4b7
 
 
bc65edb
 
39ac4b7
 
 
 
 
 
 
 
 
 
 
 
6404030
 
 
 
 
 
bc65edb
c56f47b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3e0ab
 
 
 
 
 
 
 
 
 
 
 
 
 
b82c62a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7167be0
 
b69431c
6a43a6e
 
 
 
 
7167be0
 
 
 
c6f1711
 
 
 
6404030
cd34c6f
 
8c1ffc7
 
cd34c6f
 
 
 
8c1ffc7
 
cd34c6f
df97a07
 
 
 
 
 
 
 
 
30ba090
 
 
 
 
 
 
 
 
df97a07
a345825
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
2fd367f
cd61bf7
 
cc60d0c
cd61bf7
 
 
34739db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
e4d238f
 
 
 
2fd367f
 
33256ac
 
 
 
 
 
 
 
 
 
8a72cf3
33256ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97a07
 
 
 
 
 
 
 
 
 
 
 
 
30ba090
 
 
 
 
 
 
 
 
 
 
33256ac
22169b1
 
 
 
d6efaed
 
 
22169b1
6df5db6
 
 
81b3ca5
 
6df5db6
 
df6fb4c
 
 
 
 
 
 
fc80520
abc13a7
 
 
 
f673563
 
 
 
 
 
 
 
7e95eff
f673563
d5ac7bd
 
 
 
 
 
 
 
 
72e0729
 
abc13a7
 
 
fc80520
 
 
af3b3ec
fc80520
af3b3ec
fc80520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abc13a7
f673563
 
 
 
abc13a7
 
22169b1
d6efaed
 
 
 
 
abc13a7
22169b1
79c4ca3
 
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c28cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87b355
1c28cfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a0b194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95641e0
4a0b194
 
 
 
 
 
b5833df
4a0b194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95641e0
4a0b194
 
 
 
 
 
 
 
 
 
 
 
95641e0
4a0b194
 
 
 
 
 
 
 
 
 
95641e0
 
 
 
4a0b194
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import func
from sqlmodel import select
from typing import Dict, Any, Optional
from datetime import datetime
from uuid import UUID
import httpx
import hmac
import hashlib
import asyncio

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,
    lead_id: UUID,  # NEW: for media tracking
    conversation_id: UUID = None
) -> 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.services.telegram_service import telegram_service
    from app.services.ai_core.media_tracker import media_tracker  # Import tracker
    
    # 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
    
    import re
    
    # Fetch lead to access/update DB persistence
    from app.models.lead import Lead
    lead = await session.get(Lead, lead_id)
    if not lead:
        return None
        
    ai_text_lower = ai_text.lower()
    last_message_id = None
    
    # Load persistent sent products: { "product_id": "message_id" }
    summary = lead.ai_summary_json or {}
    sent_products_db = summary.get("sent_products", {})
    # Ensure it's a dict (migration from older list format if any)
    if isinstance(sent_products_db, list):
        sent_products_db = {pid: None for pid in sent_products_db}
    
    for product in products:
        # Strict Regex Match (Word Boundary) to avoid "Start" matching "Start your day"
        # Escape special chars in product name
        pattern = r'(?<!\w)' + re.escape(product.name.lower()) + r'(?!\w)'
        
        if re.search(pattern, ai_text_lower):
            product_id_str = str(product.id)
            lead_id_str = str(lead_id)
            
            # 1. Check DB Persistence (Primary)
            cached_msg_id_db = sent_products_db.get(product_id_str)
            
            # 2. Check RAM Persistence (Secondary/Fallback)
            cached_msg_id_ram = media_tracker.get_message_id_for_product(lead_id_str, product_id_str)
            
            cached_msg_id = cached_msg_id_db or cached_msg_id_ram
            
            if cached_msg_id:
                logger.info(f"♻️ Product {product.name} already sent (DB/RAM cache). Using msg_id {cached_msg_id} for reply.")
                try:
                    last_message_id = int(cached_msg_id)
                    return last_message_id 
                except:
                    pass
                continue

            # 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})")
                    
                    # TRACK SENT STATUS (RAM)
                    media_tracker.mark_product_sent(
                        lead_id_str, 
                        product_id_str, 
                        message_id=str(last_message_id)
                    )
                    
                    # TRACK SENT STATUS (DB)
                    sent_products_db[product_id_str] = str(last_message_id)
                    summary["sent_products"] = sent_products_db
                    lead.ai_summary_json = summary
                    session.add(lead)
                    await session.commit()
                
                # 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_payment_qr_codes(
    session,
    tenant_id: UUID,
    bot_token: str,
    chat_id: str,
    payment_qr_ids: list,
    conversation_id: UUID = None
) -> Optional[int]:
    """
    Send payment QR codes from PaymentMethod when AI uses [SEND_PAYMENT_QR:ID] tag.
    """
    from app.models.knowledge import PaymentMethod
    from app.services.telegram_service import telegram_service
    
    last_sent_message_id = None
    
    for qr_id_short in payment_qr_ids:
        try:
            # Find payment method by ID prefix (first 8 chars)
            stmt = select(PaymentMethod).where(
                PaymentMethod.tenant_id == tenant_id,
                PaymentMethod.is_active == True
            )
            result = await session.execute(stmt)
            all_payments = result.scalars().all()
            
            # Find matching payment by ID prefix
            payment = None
            for pm in all_payments:
                if str(pm.id).startswith(qr_id_short):
                    payment = pm
                    break
            
            if not payment:
                logger.warning(f"⚠️ Payment method not found: {qr_id_short}")
                continue
            
            if not payment.image_url:
                logger.warning(f"⚠️ Payment method {payment.name} has no QR image")
                continue
            
            # Send QR code image
            try:
                result = await telegram_service.send_photo(
                    token=bot_token,
                    chat_id=chat_id,
                    photo_url=payment.image_url,
                    caption=f"💳 {payment.name}"
                )
                if result and result.get("message_id"):
                    last_sent_message_id = result["message_id"]
                    logger.info(f"📱 Payment QR sent: {payment.name}, message_id: {last_sent_message_id}")
            except Exception as e:
                logger.error(f"❌ Failed to send payment QR {payment.name}: {e}")
                
        except Exception as e:
            logger.error(f"❌ Failed to process payment QR {qr_id_short}: {e}")
    
    return last_sent_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 /start COMMAND - Send welcome message instantly AND save to history
        if user_text.strip().lower() == '/start':
            from app.services.telegram_service import telegram_service
            
            # Get custom welcome message or build template
            welcome_message = getattr(tenant, 'telegram_welcome_message', None)
            
            if not welcome_message:
                # Build template: "Здравствуйте! Я [AI_NAME], чем могу помочь?"
                # FIXED: ai_identity is stored INSIDE ai_settings, not as direct tenant field
                ai_settings = tenant.ai_settings or {}
                ai_identity = ai_settings.get('ai_identity', {})
                ai_name = ai_identity.get('name', '').strip()  # 'name' is the bot name field
                
                if ai_name:
                    welcome_message = f"Здравствуйте! Я {ai_name}, чем могу помочь?"
                else:
                    welcome_message = "Здравствуйте! Чем могу помочь?"
            
            # Create or get lead and conversation BEFORE sending (so we can save to history)
            lead = await get_or_create_lead(
                session=session,
                tenant_id=tenant_id,
                telegram_id=telegram_id,
                telegram_user=telegram_user
            )
            
            conversation = await get_or_create_conversation(
                session=session,
                tenant_id=tenant_id,
                lead_id=lead.id,
                channel="telegram"
            )
            
            # Send welcome message
            try:
                await telegram_service.send_message(
                    token=tenant.telegram_bot_token,
                    chat_id=chat_id,
                    text=welcome_message
                )
                logger.info(
                    "👋 Welcome message sent",
                    chat_id=chat_id,
                    tenant_id=str(tenant_id)
                )
                
                # SAVE to conversation history so AI knows what was said
                # Note: Message is already imported at top of file
                welcome_msg = Message(
                    tenant_id=tenant_id,  # Required field!
                    conversation_id=conversation.id,
                    sender_type="ai",
                    content=welcome_message,
                    status=MessageStatus.SENT
                )
                session.add(welcome_msg)
                await session.commit()
                
                logger.info("📝 Welcome message saved to conversation history")
                
            except Exception as e:
                logger.error(f"❌ Failed to send welcome message: {e}")
            
            return {"ok": True, "status": "welcome_sent"}
        
        # 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}")

        # NOTE: Automatic name extraction removed
        # Lead name = Telegram display name by default
        # Users can configure AI to ask for name in settings if needed
        
        # 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
    from app.services.voice_service import voice_service
    from app.services.telegram_service import telegram_service
    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
    
    # NOTE: Debounce removed for faster AI response
    # Message batching still works via the check on lines 1176-1202
    # which collects all user messages since last AI response
    
    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
            
            # 🔒 CHECK SUBSCRIPTION PLAN - AI only works for paid plans (start, growth, enterprise)
            # Trial accounts can save settings but AI doesn't respond
            subscription_plan = (tenant.subscription_plan or "trial").lower()
            if subscription_plan == "trial":
                logger.info(
                    "🔒 AI disabled for trial accounts - upgrade to Start/Growth/Enterprise",
                    tenant_id=str(tenant_id),
                    plan=subscription_plan
                )
                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
            # Send "typing" indicator so user sees bot is working
            await telegram_service.send_chat_action(
                token=tenant.telegram_bot_token,
                chat_id=chat_id,
                action="typing"
            )
            
            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}")
                    
                    # CHECK FOR DUPLICATE: Same lead + same time = already booked
                    # Use minute-level comparison to avoid seconds/milliseconds mismatches
                    duplicate_stmt = select(Appointment).where(
                        Appointment.lead_id == lead_id,
                        Appointment.status == AppointmentStatus.SCHEDULED,
                        func.date_trunc('minute', Appointment.start_time) == start_time
                    )
                    duplicate_result = await session.execute(duplicate_stmt)
                    existing_matching = duplicate_result.scalar_one_or_none()
                    
                    if existing_matching:
                        # Already booked for this lead at this time - just confirm, don't create duplicate or notify reschedule
                        logger.info(f"📅 Booking already exists for lead {lead_id} at {start_time}, skipping duplicate logic")
                        # Remove the tag and add confirmation (so user knows it's active)
                        ai_text = ai_text.replace(booking_match.group(0), "").strip()
                        if "(Система: Запись уже подтверждена!)" not in ai_text:
                            ai_text += "\n\n✅ (Система: Запись уже подтверждена!)"
                        ai_response["text"] = ai_text
                    else:
                        # NEW OR CHANGED TIME - Proceed with auto-cancel and new booking
                        
                        # AUTO-CANCEL OLD BOOKINGS for this lead (other than the same time which we checked above)
                        old_appts_stmt = select(Appointment).where(
                            Appointment.lead_id == lead_id,
                            Appointment.status == AppointmentStatus.SCHEDULED,
                            func.date_trunc('minute', Appointment.start_time) != start_time # Explicitly different time
                        )
                        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 (with OTHER leads)
                        conflict_stmt = select(Appointment).where(
                            Appointment.tenant_id == tenant_id,
                            Appointment.status == AppointmentStatus.SCHEDULED,
                            func.date_trunc('minute', Appointment.start_time) == start_time,
                            Appointment.lead_id != lead_id # Not us
                        )
                        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} taken by another client, 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:
                            # ALL CLEAR - CREATE NEW APPOINTMENT
                            # 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 ---

            # --- REMOVE INTERNAL AI STAGES (Chain of Thought leak protection) ---
            # If AI accidentally outputs its internal analysis, strip it
            # IMPORTANT: Only remove if it looks like actual internal analysis (has specific markers)
                # Delete [NEED_HUMAN] and common internal markers
                txt = re.sub(r'\[NEED_HUMAN\]', '', txt, flags=re.IGNORECASE)
                txt = re.sub(r'\[НУЖЕН_ЧЕЛОВЕК\]', '', txt, flags=re.IGNORECASE)
                txt = re.sub(r'\[WILL_NOTIFY\]', '', txt, flags=re.IGNORECASE)
                txt = re.sub(r'\[УВЕДОМЛЮ\]', '', txt, flags=re.IGNORECASE)
                
                ai_response["text"] = txt.strip()
            # --- INTERNAL STAGES REMOVAL 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 = []
            # Flexible pattern: handles [SEND_MEDIA:ID], SEND_MEDIA:ID, SEND_MEDIA: ID (with space)
            media_pattern = r'\[?SEND_MEDIA:\s*([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 (both formats)
                ai_response["text"] = re.sub(r'\[?SEND_MEDIA:\s*[a-f0-9-]+\]?', '', ai_response["text"]).strip()
            
            # Process [SEND_PAYMENT_QR:ID] tags - extract payment QR IDs to send
            payment_qr_ids_to_send = []
            payment_qr_pattern = r'\[SEND_PAYMENT_QR:([a-f0-9-]+)\]'
            payment_qr_matches = re.findall(payment_qr_pattern, ai_response["text"], re.IGNORECASE)
            if payment_qr_matches:
                payment_qr_ids_to_send = list(set(payment_qr_matches))  # Unique IDs
                logger.info(f"📱 AI wants to send {len(payment_qr_ids_to_send)} payment QR codes: {payment_qr_ids_to_send}")
                # Clean tags from response
                ai_response["text"] = re.sub(payment_qr_pattern, '', ai_response["text"]).strip()

            # Process [REPLY_TO_MEDIA:ID] tags
            reply_to_media_id = None
            reply_pattern = r'\[REPLY_TO_MEDIA:([a-f0-9-]+)\]'
            reply_match = re.search(reply_pattern, ai_response["text"], re.IGNORECASE)
            if reply_match:
                reply_to_media_id = reply_match.group(1)
                logger.info(f"↩️ AI wants to reply to media {reply_to_media_id}")
                ai_response["text"] = re.sub(reply_pattern, '', ai_response["text"]).strip()
            
            # Process [BOOK_SLOT: YYYY-MM-DD HH:MM] tags - auto-create appointment
            book_slot_pattern = r'\[BOOK_SLOT:\s*(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?:\s+(.+?))?\s*\]'
            book_slot_match = re.search(book_slot_pattern, ai_response["text"], re.IGNORECASE)
            if book_slot_match:
                try:
                    from datetime import datetime, timedelta
                    from app.models.booking import Appointment, Resource
                    
                    slot_date = book_slot_match.group(1)  # 2024-12-09
                    slot_time = book_slot_match.group(2)  # 10:00
                    resource_hint = book_slot_match.group(3)  # Optional: resource name
                    
                    # Parse datetime
                    start_dt = datetime.fromisoformat(f"{slot_date}T{slot_time}:00")
                    end_dt = start_dt + timedelta(minutes=tenant.booking_settings.get("slot_duration", 30) if tenant.booking_settings else 30)
                    
                    # Find resource if mentioned
                    resource_id = None
                    if resource_hint:
                        resource_stmt = select(Resource).where(
                            Resource.tenant_id == tenant.id,
                            Resource.is_active == True,
                            Resource.name.ilike(f"%{resource_hint.strip()}%")
                        )
                        resource_result = await session.execute(resource_stmt)
                        resource = resource_result.scalars().first()
                        if resource:
                            resource_id = resource.id
                            logger.info(f"📅 Found resource '{resource.name}' for booking")
                    
                    # Create appointment
                    new_appointment = Appointment(
                        tenant_id=tenant.id,
                        lead_id=lead_id,
                        start_time=start_dt,
                        end_time=end_dt,
                        resource_id=resource_id,
                        status="pending",
                        notes=f"Автоматическая запись через AI (диалог #{conversation.id})"
                    )
                    session.add(new_appointment)
                    await session.flush()
                    logger.info(f"📅 Created appointment: {slot_date} {slot_time} for lead {lead_id}, resource={resource_id}")
                    
                except Exception as e:
                    logger.error(f"❌ Failed to create booking slot: {e}")
                
                # Clean tag from response
                ai_response["text"] = re.sub(book_slot_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"],
                        lead_id=lead.id,  # Pass Lead ID
                        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
                    
                    # 3. Payment QR Codes ([SEND_PAYMENT_QR:ID])
                    if payment_qr_ids_to_send:
                        qr_msg_id = await send_payment_qr_codes(
                            session=session,
                            tenant_id=tenant.id,
                            bot_token=tenant.telegram_bot_token,
                            chat_id=chat_id,
                            payment_qr_ids=payment_qr_ids_to_send,
                            conversation_id=conversation.id
                        )
                        if qr_msg_id:
                            media_reply_id = qr_msg_id
                    
                    # 4. OVERRIDE: If AI wants to reply to a specific PREVIOUS media ID
                    if reply_to_media_id:
                        from app.services.ai_core.media_tracker import media_tracker
                        prev_msg_id = media_tracker.get_message_id_for_media(str(lead_id), reply_to_media_id)
                        if not prev_msg_id:
                            prev_msg_id = media_tracker.get_message_id_for_product(str(lead_id), reply_to_media_id)
                        
                        if prev_msg_id:
                            logger.info(f"↩️ Found Telegram message ID for reference: {prev_msg_id}")
                            media_reply_id = int(prev_msg_id)

                    # 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 (only if enabled in settings)
                        if is_first_message and getattr(tenant, 'voice_first_required', False):
                            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}")
                    
                    # ALWAYS clean up voice tag from response text (even if voice is disabled)
                    if "[SEND_VOICE]" in ai_response["text"]:
                        ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip()
                    
                    if should_send_voice:
                        try:
                            # 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()

            # --- ASYNC BACKGROUND PROCESSING ---
            # Launch background task for:
            # 1. Answer Delay (if needed) - handled by AI response time technically 
            # 2. Escalation Check
            # 3. Deep Analysis (Psychotype, Heat, Summary)
            
            asyncio.create_task(
                process_background_ai_tasks(
                    lead_id=lead.id,
                    conversation_id=conversation.id,
                    tenant_id=tenant.id,
                    user_message_text=user_text or "",
                    channel=channel
                )
            )
            
            logger.info(
                "🚀 Background AI analysis tasks launched",
                lead_id=str(lead.id),
                conversation_id=str(conversation.id)
            )

            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 process_background_ai_tasks(
    lead_id: UUID,
    conversation_id: UUID,
    tenant_id: UUID,
    user_message_text: str,
    channel: str
):
    """
    Background worker to handle:
    1. Smart Escalation Check
    2. Deep Lead Analysis (Psychotype, Heat, Summary)
    3. Real-time Frontend Updates
    """
    from app.core.database import async_session_maker
    from app.models.lead import Lead, Message
    from app.models.tenant import Tenant
    from app.services.ai_core import get_ai_core
    from app.services.escalation_service import escalation_service
    from app.services.notification_service import get_notification_service
    from app.api.websocket_chat import notify_lead_updated
    from sqlalchemy import select

    logger.info(
        "🚀 Starting background AI tasks",
        lead_id=str(lead_id),
        conversation_id=str(conversation_id)
    )
    
    async with async_session_maker() as session:
        try:
            lead = await session.get(Lead, lead_id)
            tenant = await session.get(Tenant, tenant_id)
            
            if not lead or not tenant:
                logger.warning(f"Background task aborted: Lead/Tenant not found")
                return

            # RE-FETCH Conversation History (including the AI response we just sent)
            stmt = select(Message).where(Message.conversation_id == conversation_id).order_by(Message.created_at)
            result = await session.execute(stmt)
            conversation_history = result.scalars().all()

            # 1. ESCALATION CHECK
            try:
                # Build context for escalation
                esc_history = []
                for msg in conversation_history[-10:]:
                    esc_history.append({"sender_type": msg.sender_type, "content": msg.content})
                
                # Get last AI response
                last_ai_response = ""
                if conversation_history:
                    last_msg = conversation_history[-1]
                    if last_msg.sender_type == 'ai':
                        last_ai_response = last_msg.content

                escalation_result = await escalation_service.analyze_message_smart(
                    user_message=user_message_text,
                    ai_response=last_ai_response,
                    conversation_history=esc_history,
                    heat_score=lead.heat_score or 0,
                    business_type=getattr(tenant, 'business_type', ''),
                    current_stage=None
                )
                
                if escalation_result.should_escalate:
                    logger.info(f"🚨 Escalation triggered in background: {escalation_result.reason}")
                    lead.needs_attention = True
                    lead.escalation_reason = escalation_result.reason
                    session.add(lead)
                    await session.commit()
                    
                    # Notify Manager using EscalationService directly
                    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_message_text,
                        tenant_id=str(tenant.id),
                        channel=channel
                    )
            except Exception as e:
                logger.error(f"Background escalation check failed: {e}")

            # 2. DEEP LEAD ANALYSIS (Psychotype, Heat, Summary)
            try:
                # Set status to analyzing
                lead.processing_status = "analyzing"
                session.add(lead)
                await session.commit()

                ai_core = get_ai_core()
                analysis = await ai_core.analyze_lead(
                    session=session,
                    lead=lead,
                    conversation_history=conversation_history,
                    tenant=tenant
                )
                
                logger.info(
                    "✅ Background analysis complete",
                    lead_id=str(lead.id),
                    heat_score=analysis.get('heat_score'),
                    summary_generated=analysis.get('summary_generated')
                )
                
                # Refresh lead to get latest data after internal commits in analyze_lead
                await session.refresh(lead)
                
                # 3. WEBSOCKET UPDATE
                try:
                    await notify_lead_updated(str(lead.id), {
                        "id": str(lead.id),
                        "ai_summary_json": lead.ai_summary_json,
                        "qualification_data": lead.qualification_data, # Added!
                        "qualification_complete": lead.qualification_complete, # Added!
                        "heat_score": lead.heat_score,
                        "heat_level": lead.heat_level.value if lead.heat_level and hasattr(lead.heat_level, 'value') else str(lead.heat_level),
                        "psychotype": lead.psychotype.value if lead.psychotype and hasattr(lead.psychotype, 'value') else str(lead.psychotype),
                        "name": lead.name,
                        "processing_status": "idle", # Explicitly set idle for UI
                        "needs_attention": lead.needs_attention,
                        "current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None
                    })
                except Exception as ws_err:
                    logger.warning(f"WebSocket update failed: {ws_err}")
                
            except Exception as e:
                logger.error(f"Background lead analysis failed: {e}")
            
            # Finally set status back to idle
            lead.processing_status = "idle"
            session.add(lead)
            await session.commit()
            
            logger.info(f"✅ All background tasks completed for lead {lead_id}")

        except Exception as e:
            logger.error(f"CRITICAL: Background task crash: {e}", exc_info=True)
            # Try to reset status if possible
            try:
                if lead:
                    lead.processing_status = "idle"
                    session.add(lead)
                    await session.commit()
            except: pass