Spaces:
Running

File size: 27,671 Bytes
cd61bf7
 
 
 
615c63b
cd61bf7
 
 
 
615c63b
cd61bf7
615c63b
 
cd61bf7
 
 
 
 
 
 
 
615c63b
 
cd61bf7
94437c8
0ce5872
cd61bf7
5b6905f
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94437c8
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94437c8
cd61bf7
 
 
94437c8
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b6905f
 
 
 
 
 
 
782696b
 
 
5b6905f
 
cd61bf7
 
 
 
 
 
 
 
94437c8
0ce5872
 
 
 
 
 
 
 
 
 
 
cd61bf7
94437c8
 
 
 
 
e4d238f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5152823
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce5872
615c63b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782696b
 
 
 
 
 
 
 
 
 
 
 
615c63b
 
 
 
 
 
 
f1ad673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615c63b
 
f1ad673
615c63b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5152823
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db2dc5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Chats API - Send messages from UI to customers.
"""

from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
from uuid import UUID
from datetime import datetime
from typing import Optional
from sqlmodel import select
import re
import time

from app.core.database import get_session
from app.core.logging import get_logger
from app.models.tenant import Tenant
from app.models.lead import Lead, Message, Conversation
from app.models import User
from app.api.deps import get_current_user
from app.services.ai_core import get_ai_core
from app.services.llm_client import get_llm_client
from app.core.supabase import supabase_client
from app.api.webhook import send_telegram_message
# from app.api.meta_webhooks import send_meta_message # DEPRECATED
from app.services.meta_whatsapp import whatsapp_cloud_service
import httpx
from app.api.websocket_chat import notify_new_message

logger = get_logger(__name__)


router = APIRouter(prefix="/chats", tags=["Chats"])


class SendMessageRequest(BaseModel):
    """Request to send message from manager to customer."""
    lead_id: UUID
    conversation_id: UUID
    message: str


class GenerateReplyRequest(BaseModel):
    """Request to generate AI reply and send it."""
    conversation_id: UUID


@router.post("/send", status_code=status.HTTP_201_CREATED)
async def send_message(
    request: SendMessageRequest,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Send message from Platform UI to customer via Telegram.
    
    CRITICAL FEATURES:
    1. Save message to DB with sender_type='human'
    2. Send to Telegram Bot API (robust error handling)
    3. Trigger AI analysis in background ALWAYS
    """
    
    # 1. GET TENANT FROM USER
    tenant = await session.get(Tenant, current_user.tenant_id)
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found for current user"
        )
    
    print(f"👤 User {current_user.email} from tenant {tenant.id}")
    
    # 2. CHECK BOT TOKEN EXISTS (Only for Telegram)
    # if not tenant.telegram_bot_token or not tenant.telegram_bot_token.strip():
    #     # For WhatsApp we don't need bot token here
    #     pass
    
    # 3. Validate lead exists and belongs to tenant
    lead = await session.get(Lead, request.lead_id)
    if not lead or lead.tenant_id != tenant.id:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Lead not found"
        )
    
    # 4. Validate conversation exists
    conversation = await session.get(Conversation, request.conversation_id)
    if not conversation or conversation.tenant_id != tenant.id:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Conversation not found"
        )
    
    # 5. Validate lead has Contact ID (Telegram ID or Phone)
    if not lead.telegram_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Lead has no Contact ID (Telegram ID/Phone) - cannot send message."
        )
    
    # 6. SAVE MESSAGE TO DB FIRST (Even if Telegram fails, we have record)
    human_message = Message(
        tenant_id=tenant.id,
        conversation_id=conversation.id,
        sender_type="human",  # CRITICAL: Mark as human manager
        content=request.message
    )
    session.add(human_message)
    
    # Update lead timestamps
    lead.last_message_at = datetime.utcnow()
    lead.last_activity_at = datetime.utcnow()
    session.add(lead)
    
    await session.commit()
    await session.refresh(human_message)
    
    print(f"💬 Human message saved: {human_message.id} for lead {lead.id}")
    
    # Notify WebSocket clients about new message
    await notify_new_message(str(lead.id), {
        "id": str(human_message.id),
        "content": human_message.content,
        "sender_type": "human",
        "created_at": human_message.created_at.isoformat(),
        "media_url": None,
        "media_type": None,
        "media_name": None,
        "conversation_id": str(conversation.id)
    })
    
    # 7. SEND TO APPROPRIATE CHANNEL (ROBUST ERROR HANDLING)
    send_success = False
    send_error_detail = None
    
    # Determine channel from conversation
    channel = conversation.channel if hasattr(conversation, 'channel') and conversation.channel else 'telegram'
    
    try:
        if channel == 'whatsapp':
            # Send via Meta WhatsApp Cloud API (Official)
            try:
                await whatsapp_cloud_service.send_text_message(
                    tenant=tenant,
                    to_phone=lead.telegram_id,  # Using telegram_id field for phone number
                    text=request.message
                )
                send_success = True
            except Exception as e:
                send_success = False
                send_error_detail = f"WhatsApp Cloud API error: {str(e)}"
                
        elif channel == 'instagram':
            # Instagram not yet implemented
            send_success = False
            send_error_detail = "Instagram integration not yet available"
            
        elif channel == 'linkedin':
            # SEND VIA LINKEDIN
            # Check if lead has valid URN
            if not lead.linkedin_urn:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Lead has no LinkedIn URN - cannot send message."
                )
            
            from app.services.linkedin_service import linkedin_service
            
            # Get tenant cookies
            li_config = tenant.linkedin_config or {}
            
            send_success = await linkedin_service.send_message(
                recipient_urn=lead.linkedin_urn,
                text=request.message,
                cookies=li_config  # Service will extract li_at/JSESSIONID
            )
            
            if not send_success:
                send_error_detail = "LinkedIn Service returned error (Check logs/cookies)"
            
        else:  # telegram (default)
            # Validate Telegram ID
            if not lead.telegram_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Lead has no Telegram ID - cannot send message."
                )
            
            url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage"
            
            payload = {
                "chat_id": lead.telegram_id,
                "text": request.message,
                "parse_mode": "Markdown"
            }
            
            print(f"📤 Sending to Telegram: chat_id={lead.telegram_id}")
            
            async with httpx.AsyncClient() as client:
                response = await client.post(url, json=payload, timeout=10.0)
                
                # Log full response for debugging
                print(f"📡 Telegram API Response: {response.status_code}")
                print(f"📡 Response Body: {response.text}")
                
                if response.status_code == 200:
                    send_success = True
                    print(f"✅ Message sent to Telegram: {lead.telegram_id}")
                else:
                    # Parse Telegram error
                    try:
                        error_data = response.json()
                        send_error_detail = error_data.get('description', response.text)
                    except:
                        send_error_detail = response.text
                    
                    print(f"⚠️ Telegram API Error ({response.status_code}): {send_error_detail}")
                    
    except httpx.TimeoutException:
        send_error_detail = f"{channel.capitalize()} API timeout (10s)"
        print(f"❌ {channel} timeout: {send_error_detail}")
        
    except httpx.RequestError as e:
        send_error_detail = f"Network error: {str(e)}"
        print(f"❌ {channel} request error: {send_error_detail}")
        
    except Exception as e:
        send_error_detail = f"Unexpected error: {str(e)}"
        print(f"❌ {channel} send error: {send_error_detail}")
        import traceback
        traceback.print_exc()
    
    # TASK: AUTO-ANALYZE LEAD after human message
    # Update AI summary to capture new information from manager's interaction
    try:
        from app.services.ai_core import get_ai_core
        
        # Get all messages for analysis
        msg_stmt = select(Message).where(
            Message.conversation_id == conversation.id
        ).order_by(Message.created_at)
        
        msg_result = await session.execute(msg_stmt)
        all_messages = list(msg_result.scalars().all())
        
        if len(all_messages) >= 3:  # Need minimum messages for analysis
            logger.info(
                "🧠 Auto-analyzing lead after human message",
                lead_id=str(lead.id),
                messages_count=len(all_messages)
            )
            
            # Set analyzing status
            lead.processing_status = "analyzing"
            session.add(lead)
            await session.commit()
            
            # Run analysis
            ai_core = get_ai_core()
            analysis = await ai_core.analyze_lead(
                session=session,
                lead=lead,
                conversation_history=all_messages,
                tenant=tenant
            )
            
            logger.info(
                "✅ Analysis complete after human message",
                lead_id=str(lead.id),
                heat_score=analysis.get('heat_score')
            )
            
            # Reset to idle
            lead.processing_status = "idle"
            session.add(lead)
            await session.commit()
            
    except Exception as analysis_error:
        logger.error(
            "❌ Auto-analysis failed (non-critical)",
            lead_id=str(lead.id),
            error=str(analysis_error),
            exc_info=True
        )
        # Reset status on error
        try:
            lead.processing_status = "idle"
            session.add(lead)
            await session.commit()
        except:
            pass
    
    # IMPORTANT: Return response to UI
    return {
        "success": True,
        "message_id": str(human_message.id),
        "channel": channel,
        "sent": send_success,
        "error": send_error_detail if not send_success else None,
        "message": {
            "id": str(human_message.id),
            "content": human_message.content,
            "sender_type": "human",
            "created_at": human_message.created_at.isoformat()
        }
    }


@router.post("/send-media", status_code=status.HTTP_201_CREATED)
async def send_media_message(
    lead_id: UUID = Form(...),
    conversation_id: UUID = Form(...),
    message: str = Form(""),
    file: Optional[UploadFile] = File(None),
    audio: Optional[UploadFile] = File(None),
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Send MULTIMODAL message (File/Voice) + Text.
    """
    # 1. Validation
    tenant = await session.get(Tenant, current_user.tenant_id)
    if not tenant: raise HTTPException(404, "Tenant not found")
    
    lead = await session.get(Lead, lead_id)
    if not lead or lead.tenant_id != tenant.id: raise HTTPException(404, "Lead not found")
    
    conversation = await session.get(Conversation, conversation_id)
    if not conversation or conversation.tenant_id != tenant.id: raise HTTPException(404, "Conversation not found")

    if not lead.telegram_id: raise HTTPException(400, "Lead has no Contact ID")

    # 2. Process Media
    media_url = None
    media_type = None
    media_name = None
    final_text = message or ""

    target_file = audio if audio else file
    if target_file:
        try:
            # Read file
            content_bytes = await target_file.read()
            media_type = target_file.content_type
            media_name = target_file.filename

            # A) Transcribe if audio
            if audio:
                try:
                    logger.info("🎤 Transcribing voice message...")
                    # Transcription
                    transcript = await get_llm_client().transcribe_audio(content_bytes)
                    if transcript:
                        final_text = (final_text + "\n" if final_text else "") + f"🎤 [Голосовое]: {transcript}"
                except Exception as e:
                    logger.error(f"Transcription error: {e}")
                    final_text += " (Ошибка транскрипции)"

            # B) Upload to Supabase
            if supabase_client:
                bucket = "chat-attachments"
                ts = int(time.time())
                safe_name = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', media_name)
                path = f"{tenant.id}/{conversation.id}/{ts}_{safe_name}"
                
                try:
                    # Try uploading to 'chat-attachments' (must exist)
                    supabase_client.storage.from_(bucket).upload(
                        path=path,
                        file=content_bytes,
                        file_options={"content-type": media_type}
                    )
                    media_url = supabase_client.storage.from_(bucket).get_public_url(path)
                except Exception as up_err:
                    logger.error(f"Upload failed (check bucket '{bucket}'): {up_err}")
                    pass
        except Exception as e:
            logger.error(f"File processing error: {e}")

    # 3. Create Message Record
    human_message = Message(
        tenant_id=tenant.id,
        conversation_id=conversation.id,
        sender_type="human",
        content=final_text,
        media_url=media_url,
        media_type=media_type,
        media_name=media_name
    )
    session.add(human_message)
    
    lead.last_message_at = datetime.utcnow()
    lead.last_activity_at = datetime.utcnow()
    session.add(lead)
    
    await session.commit()
    await session.refresh(human_message)

    # Notify WebSocket clients about new media message
    await notify_new_message(str(lead.id), {
        "id": str(human_message.id),
        "content": human_message.content,
        "sender_type": "human",
        "created_at": human_message.created_at.isoformat(),
        "media_url": media_url,
        "media_type": media_type,
        "media_name": media_name,
        "conversation_id": str(conversation.id)
    })

    # 4. Send to Channel (Telegram/WhatsApp)
    channel = conversation.channel or 'telegram'
    send_success = False
    error_detail = None

    try:
        if channel == 'telegram':
            async with httpx.AsyncClient(timeout=30.0) as client:
                # Check if we have media to send
                if target_file and content_bytes:
                    # Determine media type and use appropriate Telegram API
                    if audio and media_type and 'audio' in media_type.lower():
                        # Send as voice message
                        url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendVoice"
                        files = {"voice": (media_name or "voice.ogg", content_bytes, media_type)}
                        data = {"chat_id": lead.telegram_id}
                        if message:
                            data["caption"] = message[:1024]
                        res = await client.post(url, files=files, data=data)
                        logger.info(f"📤 Sent voice to Telegram: {res.status_code}")
                    
                    elif media_type and 'image' in media_type.lower():
                        # Send as photo
                        url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendPhoto"
                        files = {"photo": (media_name or "photo.jpg", content_bytes, media_type)}
                        data = {"chat_id": lead.telegram_id}
                        if message:
                            data["caption"] = message[:1024]
                        res = await client.post(url, files=files, data=data)
                        logger.info(f"📤 Sent photo to Telegram: {res.status_code}")
                    
                    else:
                        # Send as document
                        url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendDocument"
                        files = {"document": (media_name or "file", content_bytes, media_type)}
                        data = {"chat_id": lead.telegram_id}
                        if message:
                            data["caption"] = message[:1024]
                        res = await client.post(url, files=files, data=data)
                        logger.info(f"📤 Sent document to Telegram: {res.status_code}")
                    
                    send_success = res.status_code == 200
                    if not send_success:
                        error_detail = res.text
                
                else:
                    # No media, just text
                    url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage"
                    payload = {"chat_id": lead.telegram_id, "text": final_text}
                    res = await client.post(url, json=payload, timeout=10)
                    send_success = res.status_code == 200
                    if not send_success:
                        error_detail = res.text
        
        elif channel == 'whatsapp':
            await whatsapp_cloud_service.send_text_message(tenant, lead.telegram_id, final_text)
            send_success = True
            
    except Exception as e:
        error_detail = str(e)
        logger.error(f"Send error: {e}")

    # Return Result
    return {
        "success": True,
        "message_id": str(human_message.id),
        "sent": send_success,
        "media_url": media_url,
        "transcript": final_text if audio else None,
        "message": human_message
    }


@router.post("/{lead_id}/generate_reply", status_code=status.HTTP_201_CREATED)
async def generate_ai_reply(
    lead_id: UUID,
    request: GenerateReplyRequest,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Delegate to AI: Generate and SEND reply automatically.
    
    This endpoint allows a human manager to hand control back to the bot.
    The AI will:
    1. Analyze conversation history
    2. Generate contextually appropriate response
    3. Send it to Telegram immediately
    """
    
    # 1. GET TENANT FROM USER
    tenant = await session.get(Tenant, current_user.tenant_id)
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    print(f"🤖 AI Delegation request from {current_user.email} for lead {lead_id}")
    
    # 2. CHECK BOT TOKEN
    if not tenant.telegram_bot_token or not tenant.telegram_bot_token.strip():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Telegram Bot not connected"
        )
    
    # 3. Validate lead
    lead = await session.get(Lead, lead_id)
    if not lead or lead.tenant_id != tenant.id:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Lead not found"
        )
    
    # 4. Validate conversation
    conversation = await session.get(Conversation, request.conversation_id)
    if not conversation or conversation.tenant_id != tenant.id:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Conversation not found"
        )
    
    # 5. Validate Telegram ID
    if not lead.telegram_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Lead has no Telegram ID"
        )
    
    # 6. SET GENERATING STATUS
    lead.processing_status = "generating"
    session.add(lead)
    await session.commit()
    
    try:
        # 7. GET CONVERSATION HISTORY
        stmt = select(Message).where(
            Message.conversation_id == conversation.id
        ).order_by(Message.created_at)
        
        result = await session.execute(stmt)
        messages = list(result.scalars().all())
        
        if len(messages) == 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No messages in conversation"
            )
        
        print(f"💬 Processing {len(messages)} messages for AI generation")
        
        # 8. GENERATE AI RESPONSE
        ai_core = get_ai_core()
        last_user_message = next(
            (msg.content for msg in reversed(messages) if msg.sender_type == "user"),
            "Продолжите диалог"
        )
        
        ai_response = await ai_core.generate_sales_response(
            session=session,
            tenant=tenant,
            lead=lead,
            user_message=last_user_message,
            conversation_history=messages
        )
        
        # 9. SAVE AI MESSAGE TO DB
        ai_message = Message(
            tenant_id=tenant.id,
            conversation_id=conversation.id,
            sender_type="ai",
            content=ai_response["text"],
            prompt_tokens=ai_response["prompt_tokens"],
            completion_tokens=ai_response["completion_tokens"],
            model_used="gemini-pro"
        )
        session.add(ai_message)
        
        # Update lead timestamps
        lead.last_message_at = datetime.utcnow()
        lead.last_activity_at = datetime.utcnow()
        session.add(lead)
        
        await session.commit()
        await session.refresh(ai_message)
        
        print(f"🤖 AI message generated: {ai_message.id}")
        
        # 10. SEND TO TELEGRAM
        telegram_success = False
        telegram_error = None
        
        try:
            url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage"
            payload = {
                "chat_id": lead.telegram_id,
                "text": ai_response["text"],
                "parse_mode": "Markdown"
            }
            
            async with httpx.AsyncClient() as client:
                response = await client.post(url, json=payload, timeout=10.0)
                
                if response.status_code == 200:
                    telegram_success = True
                    print(f"✅ AI reply sent to Telegram: {lead.telegram_id}")
                else:
                    error_data = response.json()
                    telegram_error = error_data.get('description', response.text)
                    print(f"⚠️ Telegram error: {telegram_error}")
                    
        except Exception as e:
            telegram_error = str(e)
            print(f"❌ Telegram send failed: {telegram_error}")
        
        # TASK: AUTO-ANALYZE LEAD after AI generation
        # Update AI summary with new context from generated message
        try:
            logger.info(
                "🧠 Auto-analyzing lead after AI generation",
                lead_id=str(lead.id)
            )
            
            # Set analyzing status
            lead.processing_status = "analyzing"
            session.add(lead)
            await session.commit()
            
            # Re-fetch messages (now includes AI response)
            analysis_stmt = select(Message).where(
                Message.conversation_id == conversation.id
            ).order_by(Message.created_at)
            
            analysis_result = await session.execute(analysis_stmt)
            all_messages = list(analysis_result.scalars().all())
            
            # Run analysis
            analysis = await ai_core.analyze_lead(
                session=session,
                lead=lead,
                conversation_history=all_messages,
                tenant=tenant
            )
            
            logger.info(
                "✅ Analysis complete after AI generation",
                lead_id=str(lead.id),
                heat_score=analysis.get('heat_score')
            )
            
        except Exception as analysis_error:
            logger.error(
                "❌ Auto-analysis failed (non-critical)",
                lead_id=str(lead.id),
                error=str(analysis_error),
                exc_info=True
            )
        
        # 12. SET BACK TO IDLE
        lead.processing_status = "idle"
        session.add(lead)
        await session.commit()
        
        return {
            "success": True,
            "message_id": str(ai_message.id),
            "telegram_sent": telegram_success,
            "telegram_error": telegram_error,
            "ai_response": {
                "id": str(ai_message.id),
                "content": ai_message.content,
                "sender_type": "ai",
                "created_at": ai_message.created_at.isoformat(),
                "tokens_used": ai_response["total_tokens"]
            }
        }
        
    except HTTPException:
        raise
    
    except Exception as e:
        print(f"❌ AI generation failed: {e}")
        import traceback
        traceback.print_exc()
        
        # Set error status
        lead.processing_status = "error"
        session.add(lead)
        await session.commit()
        
        raise HTTPException(
            status_code=500,
            detail=f"AI generation failed: {str(e)}"
        )


@router.delete("/messages/{message_id}", status_code=status.HTTP_200_OK)
async def delete_message(
    message_id: UUID,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Delete a message from chat.
    
    Only allows deletion of messages with sender_type='human' (manager's own messages).
    AI and user messages cannot be deleted.
    """
    
    # 1. Get tenant from user
    tenant = await session.get(Tenant, current_user.tenant_id)
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    # 2. Find message
    message = await session.get(Message, message_id)
    if not message:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Message not found"
        )
    
    # 3. Check message belongs to tenant
    if message.tenant_id != tenant.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not authorized to delete this message"
        )
    
    # 4. Only allow deletion of human messages (manager's own messages)
    if message.sender_type != "human":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Only your own messages can be deleted"
        )
    
    # 5. Delete message
    await session.delete(message)
    await session.commit()
    
    logger.info(
        "🗑️ Message deleted",
        message_id=str(message_id),
        user_email=current_user.email,
        tenant_id=str(tenant.id)
    )
    
    return {
        "success": True,
        "message_id": str(message_id),
        "deleted": True
    }