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
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
from pydantic import BaseModel
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select, func
from typing import List, Optional
from uuid import UUID
from datetime import datetime

from app.core.database import get_session
from app.models.lead import Lead, Conversation, Message, LeadStatus, LeadHeat
from app.models.tenant import Tenant
from app.models import User
from app.models.knowledge import LeadContentProgress
from app.models.notification import Notification
from app.models.order import Order, OrderItem
from app.models.booking import Appointment
from app.models.ai_training import AIFeedback
from app.api.deps import get_current_user
from pydantic import BaseModel

router = APIRouter(prefix="/leads", tags=["Leads"])


class LeadResponse(BaseModel):
    """Lead response schema."""
    id: str
    tenant_id: str
    name: Optional[str]
    name: Optional[str]
    telegram_id: Optional[str]
    whatsapp_id: Optional[str]
    email: Optional[str]
    linkedin_profile: Optional[str]
    linkedin_urn: Optional[str]
    status: str
    heat_score: int
    heat_level: str
    psychotype: str
    budget: Optional[str]
    authority: Optional[str]
    need: Optional[str]
    timeline: Optional[str]
    ai_summary_json: dict
    first_message_at: datetime
    last_message_at: datetime
    created_at: datetime
    current_stage_id: Optional[str] = None
    last_message: Optional[str] = None  # Last message content for preview
    # Qualification Card Data
    qualification_data: dict = {}  # User-defined fields: {"Имя": "Иван", "Телефон": "..."}
    qualification_complete: bool = False  # All fields filled
    human_takeover: bool = False  # AI mode status


class ConversationResponse(BaseModel):
    """Conversation with messages."""
    id: str
    channel: str
    is_active: bool
    human_takeover: bool
    started_at: datetime
    messages: List[dict]


@router.get("", response_model=List[LeadResponse])
async def get_leads(
    status: Optional[LeadStatus] = None,
    heat_level: Optional[LeadHeat] = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Get leads for authenticated user's tenant with optional filtering.
    
    Query params:
    - status: Filter by lead status
    - heat_level: Filter by heat level (hot/warm/cold/junk)
    - skip/limit: Pagination
    """
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Build query
    stmt = select(Lead).where(Lead.tenant_id == tenant_id)
    
    if status:
        stmt = stmt.where(Lead.status == status)
    
    if heat_level:
        stmt = stmt.where(Lead.heat_level == heat_level)
    
    # Order by activity
    stmt = stmt.order_by(Lead.last_activity_at.desc())
    stmt = stmt.offset(skip).limit(limit)
    
    result = await session.execute(stmt)
    leads = result.scalars().all()
    
    # Fetch last messages for all leads in one query
    lead_ids = [lead.id for lead in leads]
    
    # Get ACTIVE conversations for these leads
    conv_stmt = select(Conversation).where(
        Conversation.lead_id.in_(lead_ids),
        Conversation.is_active == True
    )
    conv_result = await session.execute(conv_stmt)
    conversations = conv_result.scalars().all()
    conv_map = {c.lead_id: c.id for c in conversations}
    
    # Get last message for each conversation - OPTIMIZED: Single query instead of N+1
    last_messages = {}
    if conv_map:
        # Get all conversation IDs
        conv_ids = list(conv_map.values())
        
        # Bulk fetch last messages using window function
        from sqlalchemy import func, desc
        from sqlalchemy.orm import aliased
        
        # Subquery to get latest message per conversation
        subq = (
            select(
                Message.conversation_id,
                Message.content,
                func.row_number().over(
                    partition_by=Message.conversation_id,
                    order_by=desc(Message.created_at)
                ).label('rn')
            )
            .where(Message.conversation_id.in_(conv_ids))
            .subquery()
        )
        
        # Select only the first row (rn=1) for each conversation
        last_msg_stmt = select(subq.c.conversation_id, subq.c.content).where(subq.c.rn == 1)
        last_msg_result = await session.execute(last_msg_stmt)
        
        # Build reverse map: lead_id -> last_message
        conv_to_lead = {v: k for k, v in conv_map.items()}
        for conv_id, content in last_msg_result:
            lead_id = conv_to_lead.get(conv_id)
            if lead_id and content:
                last_messages[lead_id] = content[:100]
    
    return [
        LeadResponse(
            id=str(lead.id),
            tenant_id=str(lead.tenant_id),
            name=lead.name,

            telegram_id=lead.telegram_id,
            whatsapp_id=lead.whatsapp_id,
            email=lead.email,
            linkedin_profile=lead.linkedin_profile,
            linkedin_urn=lead.linkedin_urn,
            status=lead.status.value,
            heat_score=lead.heat_score,
            heat_level=lead.heat_level.value,
            psychotype=lead.psychotype.value,
            budget=lead.budget,
            authority=lead.authority,
            need=lead.need,
            timeline=lead.timeline,
            ai_summary_json=lead.ai_summary_json or {},
            first_message_at=lead.first_message_at,
            last_message_at=lead.last_message_at,
            created_at=lead.created_at,
            current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None,
            last_message=last_messages.get(lead.id),
            qualification_data=lead.qualification_data or {},
            qualification_complete=lead.qualification_complete or False,
            human_takeover=next((c.human_takeover for c in conversations if c.lead_id == lead.id), False)
        )
        for lead in leads
    ]


@router.get("/{lead_id}", response_model=LeadResponse)
async def get_lead(
    lead_id: UUID,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """Get single lead details for authenticated user's tenant."""
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    stmt = select(Lead).where(
        Lead.tenant_id == tenant_id,
        Lead.id == lead_id
    )
    result = await session.execute(stmt)
    lead = result.scalar_one_or_none()
    
    if not lead:
        raise HTTPException(status_code=404, detail="Lead not found")
    
    # Get active conversation to check AI mode
    conv_stmt = select(Conversation).where(
        Conversation.lead_id == lead_id,
        Conversation.is_active == True
    ).limit(1)
    conv_result = await session.execute(conv_stmt)
    conversation = conv_result.scalar_one_or_none()
    human_takeover = conversation.human_takeover if conversation else False
    
    return LeadResponse(
        id=str(lead.id),
        tenant_id=str(lead.tenant_id),
        name=lead.name,

        telegram_id=lead.telegram_id,
        whatsapp_id=lead.whatsapp_id,
        email=lead.email,
        linkedin_profile=lead.linkedin_profile,
        linkedin_urn=lead.linkedin_urn,
        status=lead.status.value,
        heat_score=lead.heat_score,
        heat_level=lead.heat_level.value,
        psychotype=lead.psychotype.value,
        budget=lead.budget,
        authority=lead.authority,
        need=lead.need,
        timeline=lead.timeline,
        ai_summary_json=lead.ai_summary_json or {},
        first_message_at=lead.first_message_at,
        last_message_at=lead.last_message_at,
        created_at=lead.created_at,
        current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None,
        qualification_data=lead.qualification_data or {},
        qualification_complete=lead.qualification_complete or False,
        human_takeover=human_takeover
    )


@router.get("/{lead_id}/conversation", response_model=ConversationResponse)
async def get_lead_conversation(
    lead_id: UUID,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """Get lead's conversation with all messages for authenticated user's tenant."""
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get active conversation
    stmt = select(Conversation).where(
        Conversation.tenant_id == tenant_id,
        Conversation.lead_id == lead_id,
        Conversation.is_active == True
    )
    result = await session.execute(stmt)
    conversation = result.scalar_one_or_none()
    
    if not conversation:
        raise HTTPException(status_code=404, detail="Conversation not found")
    
    # Get messages
    msg_stmt = select(Message).where(
        Message.conversation_id == conversation.id
    ).order_by(Message.created_at)
    
    msg_result = await session.execute(msg_stmt)
    messages = msg_result.scalars().all()
    
    return ConversationResponse(
        id=str(conversation.id),
        channel=conversation.channel,
        is_active=conversation.is_active,
        human_takeover=conversation.human_takeover,
        started_at=conversation.started_at,
        messages=[
            {
                "id": str(msg.id),
                "sender_type": msg.sender_type,
                "content": msg.content,
                "created_at": msg.created_at.isoformat(),
                "media_url": msg.media_url,
                "media_type": msg.media_type,
                "media_name": msg.media_name,
                "tokens": {
                    "prompt": msg.prompt_tokens,
                    "completion": msg.completion_tokens
                } if msg.sender_type == "ai" else None
            }
            for msg in messages
        ]
    )


class TakeoverRequest(BaseModel):
    """Request to takeover conversation."""
    manager_id: UUID


@router.post("/{lead_id}/takeover")
async def takeover_conversation(
    lead_id: UUID,
    request: TakeoverRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Human manager takes over the conversation.
    AI will stop responding.
    """
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get active conversation
    stmt = select(Conversation).where(
        Conversation.tenant_id == tenant_id,
        Conversation.lead_id == lead_id,
        Conversation.is_active == True
    )
    result = await session.execute(stmt)
    conversation = result.scalar_one_or_none()
    
    if not conversation:
        raise HTTPException(status_code=404, detail="Conversation not found")
    
    # Mark as taken over
    conversation.human_takeover = True
    conversation.taken_over_by = request.manager_id
    conversation.taken_over_at = datetime.utcnow()
    
    session.add(conversation)
    await session.commit()
    
    return {
        "ok": True,
        "message": "Conversation taken over by human manager",
        "conversation_id": str(conversation.id)
    }


class ToggleAIRequest(BaseModel):
    """Request to toggle AI autopilot mode."""
    is_ai_active: bool


@router.post("/{lead_id}/toggle-ai")
async def toggle_ai_mode(
    lead_id: UUID,
    request: ToggleAIRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Toggle AI autopilot mode for a conversation.
    
    - is_ai_active=True: AI responds automatically (human_takeover=False)
    - is_ai_active=False: Human mode, AI sleeps (human_takeover=True)
    """
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get active conversation
    stmt = select(Conversation).where(
        Conversation.tenant_id == tenant_id,
        Conversation.lead_id == lead_id,
        Conversation.is_active == True
    )
    result = await session.execute(stmt)
    conversation = result.scalar_one_or_none()
    
    if not conversation:
        raise HTTPException(status_code=404, detail="Conversation not found")
    
    # Toggle mode
    conversation.human_takeover = not request.is_ai_active
    
    if request.is_ai_active:
        # AI is now active, clear human takeover data
        conversation.taken_over_by = None
        conversation.taken_over_at = None
    else:
        # Human takes over
        conversation.taken_over_by = current_user.id
        conversation.taken_over_at = datetime.utcnow()
    
    session.add(conversation)
    await session.commit()
    await session.refresh(conversation)
    
    return {
        "ok": True,
        "is_ai_active": request.is_ai_active,
        "human_takeover": conversation.human_takeover,
        "message": "Автопилот ИИ" if request.is_ai_active else "Ручной режим",
        "conversation_id": str(conversation.id)
    }


@router.post("/{lead_id}/analyze")
async def force_analyze_lead(
    lead_id: UUID,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    **MANUAL ANALYSIS TRIGGER** for debugging AI pipeline (tenant-isolated).
    
    This endpoint:
    1. Fetches Lead + Tenant + Conversation History
    2. Calls AI Core synchronously (await)
    3. Logs everything to console for debugging
    4. Returns the generated summary or error details
    
    Use this to debug why 11-point summary isn't appearing in UI.
    """
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    print(f"\n{'='*80}")
    print(f"🔍 MANUAL ANALYSIS TRIGGERED: Lead {lead_id} | Tenant {tenant_id}")
    print(f"{'='*80}\n")
    
    try:
        # 1. FETCH LEAD
        lead = await session.get(Lead, lead_id)
        if not lead or lead.tenant_id != tenant_id:
            raise HTTPException(status_code=404, detail="Lead not found")
        
        print(f"✅ Lead found: {lead.name or 'Unnamed'} (ID: {lead.id})")
        print(f"   Current Heat: {lead.heat_score}, Psychotype: {lead.psychotype.value}")
        
        # 2. FETCH TENANT SETTINGS
        tenant = await session.get(Tenant, tenant_id)
        if not tenant:
            raise HTTPException(status_code=404, detail="Tenant not found")
        
        ai_settings = tenant.ai_settings or {}
        print(f"✅ Tenant settings loaded: {tenant.business_name or 'Unknown'}")
        print(f"   AI Settings: {ai_settings.keys() if ai_settings else 'None'}")
        
        # 3. FETCH CONVERSATION HISTORY
        conv_stmt = select(Conversation).where(
            Conversation.tenant_id == tenant_id,
            Conversation.lead_id == lead_id,
            Conversation.is_active == True
        )
        conv_result = await session.execute(conv_stmt)
        conversation = conv_result.scalar_one_or_none()
        
        if not conversation:
            raise HTTPException(status_code=404, detail="No active conversation found")
        
        # Get ALL messages (user, ai, human)
        msg_stmt = select(Message).where(
            Message.conversation_id == conversation.id
        ).order_by(Message.created_at)
        
        msg_result = await session.execute(msg_stmt)
        messages = list(msg_result.scalars().all())
        
        print(f"✅ Conversation history loaded: {len(messages)} messages")
        for i, msg in enumerate(messages[:5], 1):  # Show first 5
            print(f"   {i}. [{msg.sender_type.upper()}]: {msg.content[:60]}...")
        
        if len(messages) < 3:
            raise HTTPException(
                status_code=400,
                detail=f"Not enough messages to analyze. Need 3+, got {len(messages)}"
            )
        
        # 4. CALL AI CORE (SYNCHRONOUSLY)
        print(f"\n🤖 Calling AI Core to analyze lead...")
        
        from app.services.ai_core import get_ai_core
        ai_core = get_ai_core()
        
        # Run analysis
        analysis_result = await ai_core.analyze_lead(
            session=session,
            lead=lead,
            conversation_history=messages,
            tenant=tenant
        )
        
        print(f"\n✅ AI Core returned successfully!")
        print(f"   Psychotype: {analysis_result.get('psychotype')}")
        print(f"   Heat Score: {analysis_result.get('heat_score')}")
        print(f"   Summary Generated: {analysis_result.get('summary_generated')}")
        
        # 5. LOG GENERATED SUMMARY (RAW JSON)
        await session.refresh(lead)  # Reload to get updated ai_summary_json
        
        print(f"\n📊 RAW AI SUMMARY JSON (from database):")
        print(f"{'-'*80}")
        import json
        print(json.dumps(lead.ai_summary_json, indent=2, ensure_ascii=False))
        print(f"{'-'*80}\n")
        
        # 6. VALIDATE STRUCTURE
        summary = lead.ai_summary_json or {}
        expected_fields = [
            'intent', 'budget', 'timeline', 'authority',
            'pain_points', 'psychotype', 'heat_score',
            'objections', 'hidden_signals', 'recommendation', 'draft_reply'
        ]
        
        missing_fields = [f for f in expected_fields if f not in summary]
        if missing_fields:
            print(f"⚠️  WARNING: Missing fields in summary: {missing_fields}")
        else:
            print(f"✅ All 11 fields present in summary!")
        
        # 7. RETURN RESULT
        return {
            "success": True,
            "message": "Analysis completed successfully",
            "lead_id": str(lead.id),
            "analysis": {
                "psychotype": lead.psychotype.value,
                "heat_score": lead.heat_score,
                "heat_level": lead.heat_level.value,
                "messages_analyzed": len(messages)
            },
            "ai_summary_json": lead.ai_summary_json,
            "validation": {
                "all_fields_present": len(missing_fields) == 0,
                "missing_fields": missing_fields
            }
        }
        
    except HTTPException:
        raise
    
    except Exception as e:
        print(f"\n❌ CRITICAL ERROR during analysis:")
        print(f"   Type: {type(e).__name__}")
        print(f"   Message: {str(e)}")
        
        import traceback
        print(f"\n📄 Full traceback:")
        traceback.print_exc()
        
        raise HTTPException(
            status_code=500,
            detail={
                "error_type": type(e).__name__,
                "error_message": str(e),
                "hint": "Check backend console logs for full traceback"
            }
        )


@router.get("/stats")
async def get_lead_stats(
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """Get lead statistics for dashboard (tenant-isolated)."""
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Total leads
    total_stmt = select(func.count(Lead.id)).where(Lead.tenant_id == tenant_id)
    total_result = await session.execute(total_stmt)
    total_leads = total_result.scalar()
    
    # By heat level
    hot_stmt = select(func.count(Lead.id)).where(
        Lead.tenant_id == tenant_id,
        Lead.heat_level == LeadHeat.HOT
    )
    hot_result = await session.execute(hot_stmt)
    hot_leads = hot_result.scalar()
    
    warm_stmt = select(func.count(Lead.id)).where(
        Lead.tenant_id == tenant_id,
        Lead.heat_level == LeadHeat.WARM
    )
    warm_result = await session.execute(warm_stmt)
    warm_leads = warm_result.scalar()
    
    # By status
    qualified_stmt = select(func.count(Lead.id)).where(
        Lead.tenant_id == tenant_id,
        Lead.status == LeadStatus.QUALIFIED
    )
    qualified_result = await session.execute(qualified_stmt)
    qualified_leads = qualified_result.scalar()
    
    return {
        "total_leads": total_leads,
        "hot_leads": hot_leads,
        "warm_leads": warm_leads,
        "qualified_leads": qualified_leads,
        "conversion_rate": (qualified_leads / total_leads * 100) if total_leads > 0 else 0
    }


class UpdateStageRequest(BaseModel):
    """Request to update lead's current stage."""
    stage_id: UUID


@router.patch("/{lead_id}/stage")
async def update_lead_stage(
    lead_id: UUID,
    request: UpdateStageRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Update the current stage of a lead.
    Allows manual override by manager (tenant-isolated).
    """
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get lead
    stmt = select(Lead).where(
        Lead.tenant_id == tenant_id,
        Lead.id == lead_id
    )
    result = await session.execute(stmt)
    lead = result.scalar_one_or_none()
    
    if not lead:
        raise HTTPException(status_code=404, detail="Lead not found")
    
    # Update stage
    lead.current_stage_id = request.stage_id
    lead.updated_at = datetime.utcnow()
    
    session.add(lead)
    await session.commit()
    await session.refresh(lead)
    
    return {
        "message": "Stage updated successfully",
        "lead_id": str(lead.id),
        "current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None
    }


@router.delete("/{lead_id}")
async def delete_lead(
    lead_id: UUID,
    clear_cache: bool = Query(False, description="Clear AI memory cache for tenant"),
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Delete a lead and all associated data (conversations, messages).
    Tenant-isolated - users can only delete their own leads.
    Optional: clear_cache=true to invalidate AI memory cache.
    
    OPTIMIZED: Uses bulk SQL DELETE for speed.
    """
    from sqlalchemy import delete as sql_delete
    
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get lead
    stmt = select(Lead).where(
        Lead.tenant_id == tenant_id,
        Lead.id == lead_id
    )
    result = await session.execute(stmt)
    lead = result.scalar_one_or_none()
    
    if not lead:
        raise HTTPException(status_code=404, detail="Lead not found")
    
    lead_name = lead.name or "Unnamed"
    
    # Get conversation IDs for this lead (needed for message deletion)
    conv_stmt = select(Conversation.id).where(Conversation.lead_id == lead_id)
    conv_result = await session.execute(conv_stmt)
    conv_ids = [row[0] for row in conv_result.fetchall()]
    
    # Get order IDs for this lead (needed for order items deletion)
    order_stmt = select(Order.id).where(Order.lead_id == lead_id)
    order_result = await session.execute(order_stmt)
    order_ids = [row[0] for row in order_result.fetchall()]
    
    # BULK DELETE in correct order (foreign key dependencies)
    # 1. Delete order items first
    if order_ids:
        await session.execute(sql_delete(OrderItem).where(OrderItem.order_id.in_(order_ids)))
    
    # 2. Delete orders
    await session.execute(sql_delete(Order).where(Order.lead_id == lead_id))
    
    # 3. Delete notifications
    await session.execute(sql_delete(Notification).where(Notification.lead_id == lead_id))
    
    # 4. Delete appointments
    await session.execute(sql_delete(Appointment).where(Appointment.lead_id == lead_id))
    
    # 5. Delete content progress
    await session.execute(sql_delete(LeadContentProgress).where(LeadContentProgress.lead_id == lead_id))
    
    # 6. Delete AI feedback
    await session.execute(sql_delete(AIFeedback).where(AIFeedback.lead_id == lead_id))
    
    # 7. Delete messages (requires conversation IDs)
    if conv_ids:
        await session.execute(sql_delete(Message).where(Message.conversation_id.in_(conv_ids)))
    
    # 8. Delete conversations
    await session.execute(sql_delete(Conversation).where(Conversation.lead_id == lead_id))
    
    # 9. Finally delete lead
    await session.execute(sql_delete(Lead).where(Lead.id == lead_id))
    
    await session.commit()
    
    # Optionally clear AI cache
    cache_cleared = False
    if clear_cache:
        try:
            from app.services.ai_memory_manager import get_memory_manager
            tenant = await session.get(Tenant, tenant_id)
            if tenant and tenant.ai_cache_key:
                await get_memory_manager().invalidate_memory(session, tenant)
                cache_cleared = True
        except Exception as e:
            print(f"⚠️ Failed to clear AI cache: {e}")
    
    return {
        "ok": True,
        "message": f"Lead '{lead_name}' and all associated data deleted successfully",
        "lead_id": str(lead_id),
        "cache_cleared": cache_cleared
    }


@router.post("/{lead_id}/reset")
async def reset_lead(
    lead_id: UUID,
    current_user: User = Depends(get_current_user),
    session = Depends(get_session)
):
    """
    Reset a lead - clears conversation history and AI analysis.
    The lead record is preserved so new messages from the same contact
    will be treated as a fresh conversation.
    
    This is useful for testing different prompts with the same account.
    """
    # Use authenticated user's tenant_id (prevents tenant isolation breach)
    tenant_id = current_user.tenant_id
    
    # Get lead
    stmt = select(Lead).where(
        Lead.tenant_id == tenant_id,
        Lead.id == lead_id
    )
    result = await session.execute(stmt)
    lead = result.scalar_one_or_none()
    
    if not lead:
        raise HTTPException(status_code=404, detail="Lead not found")
    
    lead_name = lead.name or "Unnamed"
    messages_deleted = 0
    conversations_deleted = 0
    
    # 1. Cleanup AI Feedback related to this lead
    feedback_stmt = select(AIFeedback).where(AIFeedback.lead_id == lead_id)
    feedback_result = await session.execute(feedback_stmt)
    for feedback in feedback_result.scalars().all():
        await session.delete(feedback)

    # 2. Cleanup Conversations and Messages
    conv_stmt = select(Conversation).where(Conversation.lead_id == lead_id)
    conv_result = await session.execute(conv_stmt)
    conversations = conv_result.scalars().all()
    
    for conv in conversations:
        # Delete messages for this conversation
        msg_stmt = select(Message).where(Message.conversation_id == conv.id)
        msg_result = await session.execute(msg_stmt)
        messages = msg_result.scalars().all()
        for msg in messages:
            await session.delete(msg)
            messages_deleted += 1
        
        # Delete conversation
        await session.delete(conv)
        conversations_deleted += 1
    
    # Reset lead to initial state
    lead.ai_summary_json = {}  # Clear AI analysis
    lead.heat_score = 0
    lead.heat_level = LeadHeat.COLD
    lead.status = LeadStatus.NEW
    lead.psychotype = lead.psychotype  # Keep psychotype for now (will be re-analyzed)
    lead.first_message_at = datetime.utcnow()
    lead.last_message_at = datetime.utcnow()
    lead.updated_at = datetime.utcnow()
    
    session.add(lead)
    await session.commit()
    
    return {
        "ok": True,
        "message": f"Lead '{lead_name}' has been reset. Next message will start fresh.",
        "lead_id": str(lead_id),
        "messages_deleted": messages_deleted,
        "conversations_deleted": conversations_deleted
    }