Spaces:
Running

File size: 33,325 Bytes
cd61bf7
 
 
 
 
 
 
 
 
 
 
80c9efd
cd61bf7
 
 
 
 
80c9efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e454398
80c9efd
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c9efd
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c9efd
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c9efd
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c9efd
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4b8d4
d087150
cd61bf7
 
cb4b8d4
d087150
cd61bf7
 
 
 
6c1643e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55d1a1a
 
6c1643e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d087150
 
6c1643e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7167be0
 
6c1643e
 
7167be0
 
6c1643e
7167be0
 
 
 
 
 
 
b40dcb1
 
 
6c1643e
 
 
 
b40dcb1
 
6c1643e
7167be0
 
 
 
 
 
 
 
6c1643e
 
 
76d56a5
6c1643e
76d56a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c1643e
 
 
76d56a5
 
 
 
 
6c1643e
 
7167be0
 
 
76d56a5
 
 
7167be0
 
 
 
 
 
 
 
 
 
 
 
6c1643e
 
 
 
 
 
 
 
 
 
 
 
239a249
cd0d86d
7167be0
239a249
cd0d86d
 
 
 
 
7167be0
 
 
cd0d86d
7167be0
6c1643e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c9efd
 
 
8b679a2
 
 
6c1643e
 
8b679a2
6c1643e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from pydantic import BaseModel
from typing import List, Optional, Dict
from uuid import UUID
from datetime import datetime

from app.core.database import get_async_session
from app.api.deps import get_current_user
from app.models import User, SalesStage, Tenant
from sqlalchemy.orm.attributes import flag_modified


router = APIRouter(prefix="/playbook", tags=["Playbook"])


# ============================================================================
# Sync Helper
# ============================================================================

async def sync_tenant_qualification_fields(session: AsyncSession, tenant_id: UUID):
    """
    Collect all unique exit_criteria from active stages and merge them into
    tenant.ai_settings["qualification_fields"]. This ensures AI extraction
    uses the same fields defined in the funnel.
    """
    # Get all active stages
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.tenant_id == tenant_id)
        .where(SalesStage.is_active == True)
    )
    stages = result.scalars().all()
    
    # Collect unique criteria from all stages
    all_criteria = set()
    for stage in stages:
        for criterion in (stage.exit_criteria or []):
            if criterion and criterion.strip():
                all_criteria.add(criterion.strip())
    
    # Get tenant
    tenant = await session.get(Tenant, tenant_id)
    if not tenant:
        return
    
    # Merge with existing qualification_fields (preserve user additions)
    ai_settings = tenant.ai_settings or {}
    existing_fields = set(ai_settings.get("qualification_fields", []))
    
    # Combine: all stage criteria + existing fields
    merged_fields = list(all_criteria | existing_fields)
    
    # Update tenant
    ai_settings["qualification_fields"] = merged_fields
    ai_settings["custom_fields"] = merged_fields  # Backward compat in ai_settings JSON
    tenant.ai_settings = ai_settings
    flag_modified(tenant, "ai_settings")
    
    session.add(tenant)
    await session.commit()
    
    print(f"✅ Synced {len(merged_fields)} qualification fields for tenant {tenant_id}")


# ============================================================================
# Schemas
# ============================================================================

class SalesStageCreate(BaseModel):
    name: str
    description: Optional[str] = None
    ai_goal: str
    exit_criteria: List[str] = []


class SalesStageUpdate(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    ai_goal: Optional[str] = None
    exit_criteria: Optional[List[str]] = None


class ReorderRequest(BaseModel):
    stage_ids: List[UUID]  # New order of stage IDs


class TemplateInfo(BaseModel):
    id: str
    name: str


class TemplatesResponse(BaseModel):
    templates: List[TemplateInfo]


class TemplateType(str):
    """Playbook template types."""
    REAL_ESTATE = "real_estate"
    B2B_SAAS = "b2b_saas"
    CONSULTING = "consulting"
    ECOMMERCE = "ecommerce"
    FINANCIAL = "financial"


class SalesStageResponse(BaseModel):
    id: UUID
    tenant_id: UUID
    name: str
    description: Optional[str]
    order_index: int
    ai_goal: str
    exit_criteria: List[str]
    is_active: bool
    created_at: datetime
    updated_at: datetime


# ============================================================================
# Endpoints
# ============================================================================

@router.get("/stages", response_model=List[SalesStageResponse])
async def list_stages(
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    List all sales stages for current tenant, ordered by order_index.
    """
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.tenant_id == current_user.tenant_id)
        .where(SalesStage.is_active == True)
        .order_by(SalesStage.order_index)
    )
    stages = result.scalars().all()
    
    return [
        SalesStageResponse(
            id=stage.id,
            tenant_id=stage.tenant_id,
            name=stage.name,
            description=stage.description,
            order_index=stage.order_index,
            ai_goal=stage.ai_goal,
            exit_criteria=stage.exit_criteria or [],
            is_active=stage.is_active,
            created_at=stage.created_at,
            updated_at=stage.updated_at
        )
        for stage in stages
    ]


@router.post("/stages", response_model=SalesStageResponse, status_code=status.HTTP_201_CREATED)
async def create_stage(
    request: SalesStageCreate,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Create a new sales stage for current tenant.
    Automatically assigns next order_index.
    """
    # Get max order_index
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.tenant_id == current_user.tenant_id)
        .order_by(SalesStage.order_index.desc())
    )
    last_stage = result.scalars().first()
    next_order = (last_stage.order_index + 1) if last_stage else 1
    
    # Create new stage
    new_stage = SalesStage(
        tenant_id=current_user.tenant_id,
        name=request.name,
        description=request.description,
        ai_goal=request.ai_goal,
        exit_criteria=request.exit_criteria,
        order_index=next_order,
        is_active=True
    )
    
    session.add(new_stage)
    await session.commit()
    await session.refresh(new_stage)
    
    # Sync exit criteria to tenant qualification fields
    await sync_tenant_qualification_fields(session, current_user.tenant_id)
    
    return SalesStageResponse(
        id=new_stage.id,
        tenant_id=new_stage.tenant_id,
        name=new_stage.name,
        description=new_stage.description,
        order_index=new_stage.order_index,
        ai_goal=new_stage.ai_goal,
        exit_criteria=new_stage.exit_criteria or [],
        is_active=new_stage.is_active,
        created_at=new_stage.created_at,
        updated_at=new_stage.updated_at
    )


@router.put("/stages/{stage_id}", response_model=SalesStageResponse)
async def update_stage(
    stage_id: UUID,
    request: SalesStageUpdate,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Update an existing sales stage.
    """
    # Get stage
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.id == stage_id)
        .where(SalesStage.tenant_id == current_user.tenant_id)
    )
    stage = result.scalar_one_or_none()
    
    if not stage:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stage not found"
        )
    
    # Update fields
    if request.name is not None:
        stage.name = request.name
    if request.description is not None:
        stage.description = request.description
    if request.ai_goal is not None:
        stage.ai_goal = request.ai_goal
    if request.exit_criteria is not None:
        stage.exit_criteria = request.exit_criteria
    
    stage.updated_at = datetime.utcnow()
    
    session.add(stage)
    await session.commit()
    await session.refresh(stage)
    
    # Sync exit criteria to tenant qualification fields
    await sync_tenant_qualification_fields(session, current_user.tenant_id)
    
    return SalesStageResponse(
        id=stage.id,
        tenant_id=stage.tenant_id,
        name=stage.name,
        description=stage.description,
        order_index=stage.order_index,
        ai_goal=stage.ai_goal,
        exit_criteria=stage.exit_criteria or [],
        is_active=stage.is_active,
        created_at=stage.created_at,
        updated_at=stage.updated_at
    )


@router.post("/stages/reorder", status_code=status.HTTP_200_OK)
async def reorder_stages(
    request: ReorderRequest,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Reorder stages by providing list of IDs in new order.
    """
    # Verify all stages belong to current tenant
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.id.in_(request.stage_ids))
        .where(SalesStage.tenant_id == current_user.tenant_id)
    )
    stages = result.scalars().all()
    
    if len(stages) != len(request.stage_ids):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Some stages not found or not owned by tenant"
        )
    
    # Update order_index for each stage
    stage_map = {stage.id: stage for stage in stages}
    
    for new_index, stage_id in enumerate(request.stage_ids, start=1):
        stage = stage_map[stage_id]
        stage.order_index = new_index
        stage.updated_at = datetime.utcnow()
        session.add(stage)
    
    await session.commit()
    
    return {"message": "Stages reordered successfully"}


@router.delete("/stages/{stage_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_stage(
    stage_id: UUID,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Soft delete a sales stage (sets is_active=False).
    """
    # Get stage
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.id == stage_id)
        .where(SalesStage.tenant_id == current_user.tenant_id)
    )
    stage = result.scalar_one_or_none()
    
    if not stage:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Stage not found"
        )
    
    # Soft delete
    stage.is_active = False
    stage.updated_at = datetime.utcnow()
    
    session.add(stage)
    await session.commit()
    
    # Sync exit criteria to tenant qualification fields (recalculate)
    await sync_tenant_qualification_fields(session, current_user.tenant_id)
    
    return None


# ============================================================================
# Template Presets
# ============================================================================

PLAYBOOK_TEMPLATES: Dict[str, List[Dict]] = {
    "real_estate": [
        {
            "name": "Первый контакт",
            "description": "Знакомство с клиентом и выявление интереса",
            "ai_goal": "Установить контакт, узнать, что именно ищет клиент (квартира/дом, район, бюджет). Создать доверительную атмосферу.",
            "exit_criteria": ["Тип недвижимости", "Район", "Бюджет"]
        },
        {
            "name": "Квалификация",
            "description": "Глубокое понимание потребностей",
            "ai_goal": "Выявить критерии выбора (количество комнат, этаж, инфраструктура). Узнать срочность покупки и способ оплаты (ипотека/наличные).",
            "exit_criteria": ["Срочность", "Способ оплаты", "Критерии выбора"]
        },
        {
            "name": "Показ объектов",
            "description": "Презентация подходящих вариантов",
            "ai_goal": "Согласовать время показа, рассказать о преимуществах объектов. Собрать обратную связь после показа.",
            "exit_criteria": ["Дата показа", "Обратная связь"]
        },
        {
            "name": "Принятие решения",
            "description": "Работа с возражениями и сделка",
            "ai_goal": "Ответить на вопросы, развеять сомнения. Обсудить условия сделки, помочь с документами.",
            "exit_criteria": ["Готовность к сделке"]
        }
    ],
    "b2b_saas": [
        {
            "name": "Discovery",
            "description": "Выявление потребностей бизнеса",
            "ai_goal": "Понять текущие процессы клиента, проблемы, которые он хочет решить. Узнать размер команды и бюджет.",
            "exit_criteria": ["Боли клиента", "Размер команды", "Бюджет"]
        },
        {
            "name": "Demo",
            "description": "Демонстрация продукта",
            "ai_goal": "Показать, как наш продукт решает конкретные проблемы клиента. Собрать вопросы и возражения.",
            "exit_criteria": ["Дата демо", "Заинтересованность"]
        },
        {
            "name": "Trial",
            "description": "Тестовый период",
            "ai_goal": "Помочь с onboarding, ответить на вопросы. Узнать feedback и готовность к покупке.",
            "exit_criteria": ["Статус триала", "Feedback"]
        },
        {
            "name": "Negotiation",
            "description": "Обсуждение условий",
            "ai_goal": "Обсудить тариф, условия оплаты, интеграции. Подготовить договор.",
            "exit_criteria": ["Тариф выбран", "Договор согласован"]
        }
    ],
    "consulting": [
        {
            "name": "Консультация",
            "description": "Первичная встреча",
            "ai_goal": "Понять запрос клиента, его текущую ситуацию. Рассказать о нашем опыте в похожих проектах.",
            "exit_criteria": ["Запрос клиента", "Бюджет проекта"]
        },
        {
            "name": "Анализ",
            "description": "Глубинный анализ задачи",
            "ai_goal": "Собрать дополнительную информацию, провести аудит. Выявить scope of work.",
            "exit_criteria": ["Scope проекта", "Сроки"]
        },
        {
            "name": "Proposal",
            "description": "Коммерческое предложение",
            "ai_goal": "Представить план работы, стоимость, этапы. Ответить на вопросы.",
            "exit_criteria": ["Proposal отправлен", "Feedback получен"]
        },
        {
            "name": "Договор",
            "description": "Подписание контракта",
            "ai_goal": "Согласовать условия, подписать договор, запланировать старт проекта.",
            "exit_criteria": ["Договор подписан"]
        }
    ],
    "ecommerce": [
        {
            "name": "Интерес",
            "description": "Клиент заинтересовался товаром",
            "ai_goal": "Ответить на вопросы о товаре, характеристиках, доставке. Помочь с выбором.",
            "exit_criteria": ["Товар выбран"]
        },
        {
            "name": "Корзина",
            "description": "Добавление в корзину",
            "ai_goal": "Предложить сопутствующие товары, рассказать о скидках. Напомнить о товаре, если клиент ушёл.",
            "exit_criteria": ["В корзине"]
        },
        {
            "name": "Оформление",
            "description": "Процесс заказа",
            "ai_goal": "Помочь с оформлением, ответить на вопросы о доставке и оплате.",
            "exit_criteria": ["Адрес указан", "Способ оплаты выбран"]
        },
        {
            "name": "Оплата",
            "description": "Завершение покупки",
            "ai_goal": "Подтвердить заказ, сообщить номер отслеживания. Попросить оставить отзыв после получения.",
            "exit_criteria": ["Заказ оплачен"]
        }
    ],
    "financial": [
        {
            "name": "Знакомство",
            "description": "Первый контакт",
            "ai_goal": "Понять финансовые цели клиента (накопления, инвестиции, кредит). Оценить его текущую ситуацию.",
            "exit_criteria": ["Финансовая цель", "Доход"]
        },
        {
            "name": "Анализ",
            "description": "Финансовый анализ",
            "ai_goal": "Собрать данные о доходах, расходах, активах. Оценить риск-профиль.",
            "exit_criteria": ["Финансовая ситуация", "Риск-профиль"]
        },
        {
            "name": "Рекомендации",
            "description": "Предложение продуктов",
            "ai_goal": "Предложить подходящие финансовые продукты (вклады, инвестиции, страхование). Объяснить условия.",
            "exit_criteria": ["Продукт выбран"]
        },
        {
            "name": "Оформление",
            "description": "Заключение договора",
            "ai_goal": "Помочь с документами, ответить на юридические вопросы. Оформить продукт.",
            "exit_criteria": ["Договор подписан"]
        }
    ]
}


@router.get("/templates", response_model=TemplatesResponse)
async def get_template_types():
    """
    Get list of available playbook templates.
    """
    return TemplatesResponse(
        templates=[
            TemplateInfo(id="real_estate", name="🏠 Недвижимость"),
            TemplateInfo(id="b2b_saas", name="💼 B2B SaaS"),
            TemplateInfo(id="consulting", name="🎯 Консалтинг"),
            TemplateInfo(id="ecommerce", name="🛒 E-commerce"),
            TemplateInfo(id="financial", name="💰 Финансы")
        ]
    )


@router.post("/stages/template/{template_type}", status_code=status.HTTP_201_CREATED)
async def load_template(
    template_type: str,
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Load a predefined playbook template.
    Deletes existing stages and creates new ones from template.
    """
    if template_type not in PLAYBOOK_TEMPLATES:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Template '{template_type}' not found"
        )
    
    # Delete existing stages (soft delete)
    result = await session.execute(
        select(SalesStage)
        .where(SalesStage.tenant_id == current_user.tenant_id)
    )
    existing_stages = result.scalars().all()
    
    for stage in existing_stages:
        stage.is_active = False
        session.add(stage)
    
    # Create new stages from template
    template_stages = PLAYBOOK_TEMPLATES[template_type]
    created_stages = []
    
    for order_index, stage_data in enumerate(template_stages, start=1):
        new_stage = SalesStage(
            tenant_id=current_user.tenant_id,
            name=stage_data["name"],
            description=stage_data.get("description"),
            ai_goal=stage_data["ai_goal"],
            exit_criteria=stage_data["exit_criteria"],
            order_index=order_index,
            is_active=True
        )
        session.add(new_stage)
        created_stages.append(new_stage)
    
    await session.commit()
    
    # Refresh to get IDs
    for stage in created_stages:
        await session.refresh(stage)
    
    # Sync exit criteria to tenant qualification fields
    await sync_tenant_qualification_fields(session, current_user.tenant_id)
    
    return {
        "message": f"Template '{template_type}' loaded successfully",
        "stages_created": len(created_stages),
        "stages": [
            SalesStageResponse(
                id=stage.id,
                tenant_id=stage.tenant_id,
                name=stage.name,
                description=stage.description,
                order_index=stage.order_index,
                ai_goal=stage.ai_goal,
                exit_criteria=stage.exit_criteria or [],
                is_active=stage.is_active,
                created_at=stage.created_at,
                updated_at=stage.updated_at
            )
            for stage in created_stages
        ]
    }


@router.get("/custom-fields", response_model=List[str])
async def get_custom_fields(
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Get custom_fields from tenant's AI settings.
    These are the available fields for exit_criteria.
    """
    # Get tenant
    result = await session.execute(
        select(Tenant).where(Tenant.id == current_user.tenant_id)
    )
    tenant = result.scalar_one_or_none()
    
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    # Extract qualification_fields from ai_settings
    default_fields = ["Имя", "Контакт", "Бюджет", "Срочность"]
    
    if tenant.ai_settings and isinstance(tenant.ai_settings, dict):
        # We exclusively use qualification_fields now, with fallback to legacy custom_fields
        custom_fields = tenant.ai_settings.get("qualification_fields") or tenant.ai_settings.get("custom_fields", default_fields)
    else:
        custom_fields = default_fields
    
    return custom_fields


# ============================================================================
# AI Generation Endpoint
# ============================================================================

class GeneratedStage(BaseModel):
    name: str
    description: str
    ai_goal: str
    exit_criteria: List[str]


class GenerateFunnelResponse(BaseModel):
    success: bool
    stages: List[SalesStageResponse]
    message: str


@router.post("/stages/generate", status_code=status.HTTP_201_CREATED)
async def generate_funnel_with_ai(
    current_user: User = Depends(get_current_user),
    session: AsyncSession = Depends(get_async_session)
):
    """
    Generate optimal sales funnel stages using AI.
    
    Analyzes:
    - Tenant's business settings (type, description, selling style)
    - Knowledge base content
    - Products/services
    - Custom fields
    
    Returns generated stages tailored to the specific business.
    """
    import json
    from app.models.knowledge import KnowledgeBase
    from app.models.product import Product
    
    # Get tenant
    result = await session.execute(
        select(Tenant).where(Tenant.id == current_user.tenant_id)
    )
    tenant = result.scalar_one_or_none()
    
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Tenant not found"
        )
    
    # Gather business context
    business_type = tenant.business_type or "general"
    ai_settings = tenant.ai_settings or {}
    business_description = ai_settings.get("business_description", "")
    selling_style = ai_settings.get("selling_style", "Consultative")
    # Use qualification_fields (current) with fallback to custom_fields (legacy)
    custom_fields = ai_settings.get("qualification_fields") or ai_settings.get("custom_fields", ["Имя", "Контакт", "Бюджет", "Срочность"])
    
    # Get knowledge base
    kb_result = await session.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.tenant_id == tenant.id)
        .where(KnowledgeBase.is_active == True)
        .limit(20)
    )
    kb_items = kb_result.scalars().all()
    kb_summary = "\n".join([f"- [{item.category}] {item.content_chunk[:200]}..." for item in kb_items]) if kb_items else "Нет данных"
    
    # Get products/services
    prod_result = await session.execute(
        select(Product)
        .where(Product.tenant_id == tenant.id)
        .where(Product.is_active == True)
        .limit(10)
    )
    products = prod_result.scalars().all()
    products_summary = "\n".join([f"- {p.name}: {p.price} {p.currency}" + (f" — {p.description[:100]}" if p.description else "") for p in products]) if products else "Нет товаров/услуг"
    
    # Build AI prompt
    prompt = f"""Ты эксперт по построению воронок продаж. Проанализируй бизнес и создай оптимальную воронку продаж.

=== ИНФОРМАЦИЯ О БИЗНЕСЕ ===
Тип бизнеса: {business_type}
Описание: {business_description or "Не указано"}
Стиль продаж: {selling_style}

=== ТОВАРЫ/УСЛУГИ ===
{products_summary}

=== БАЗА ЗНАНИЙ (выдержки) ===
{kb_summary}

=== ТЕКУЩИЕ ПОЛЯ ДЛЯ СБОРА ===
{', '.join(custom_fields) if custom_fields else 'Не указаны'}

=== ЗАДАЧА ===
1. Создай воронку продаж из 3-5 этапов, оптимизированную под этот бизнес.
2. Предложи поля квалификации — какую информацию AI должен собирать у каждого клиента.

Для каждого ЭТАПА укажи:
- name — название этапа (короткое, 1-2 слова)
- description — описание перехода клиента на этот этап
- ai_goal — подробная инструкция для AI: что узнавать, как вести диалог, какие техники использовать
- exit_criteria — список полей которые нужно собрать чтобы перейти на следующий этап

Для ПОЛЕЙ КВАЛИФИКАЦИИ (qualification_fields):
МИНИМАЛЬНЫЙ набор полей для CRM.
Обязательно: "Имя", "Контакт" (телефон или email).
Сгенерируй РОВНО 4-6 полей, не больше. Только самые важные для продаж.

ВАЖНО:
- ai_goal должен быть очень подробным (минимум 2-3 предложения)
- Включи конкретные техники продаж в ai_goal
- exit_criteria — 1-2 критерия на этап (не больше!)
- qualification_fields — РОВНО 4-6 полей, все с галочками

Верни JSON объект в формате:
{{
  "stages": [
    {{"name": "...", "description": "...", "ai_goal": "...", "exit_criteria": ["поле1", "поле2"]}},
    ...
  ],
  "qualification_fields": ["Имя", "Контакт", "Бюджет", ...]
}}

Верни ТОЛЬКО JSON, без markdown и пояснений."""

    # Call LLM via existing client with higher token limit
    try:
        import re
        import asyncio
        from google import genai
        from google.genai import types
        from app.core.config import settings
        
        # Use direct API call with higher token limit for long response
        client = genai.Client(api_key=settings.GEMINI_API_KEY)
        
        config = types.GenerateContentConfig(
            temperature=0.7,
            max_output_tokens=4000,  # Higher limit for JSON array
        )
        
        loop = asyncio.get_event_loop()
        response = await loop.run_in_executor(
            None,
            lambda: client.models.generate_content(
                model="gemini-2.0-flash",
                contents=prompt,
                config=config
            )
        )
        
        raw_text = response.text.strip()
        
        # Clean up JSON if wrapped in markdown
        if raw_text.startswith("```"):
            parts = raw_text.split("```")
            if len(parts) >= 2:
                raw_text = parts[1]
                if raw_text.startswith("json"):
                    raw_text = raw_text[4:]
        raw_text = raw_text.strip()
        
        # Try to extract JSON object with regex as fallback
        if not raw_text.startswith("{"):
            match = re.search(r'\{[\s\S]*\}', raw_text)
            if match:
                raw_text = match.group(0)
        
        # Parse generated response
        ai_result = json.loads(raw_text)
        
        # Handle both old format (array) and new format (object with stages/qualification_fields)
        if isinstance(ai_result, list):
            # Old format - just stages array
            generated_stages = ai_result
            generated_qualification_fields = None
        else:
            # New format - object with stages and qualification_fields
            generated_stages = ai_result.get("stages", [])
            generated_qualification_fields = ai_result.get("qualification_fields", None)
        
    except json.JSONDecodeError as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to parse AI response: {str(e)}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"AI generation error: {str(e)}"
        )
    
    # Save generated qualification_fields to tenant.ai_settings
    # MERGE with existing fields instead of replacing
    saved_qual_fields = False
    if generated_qualification_fields:
        existing_fields = set(ai_settings.get("qualification_fields", []))
        # Merge: keep existing + add new unique ones
        merged_fields = list(existing_fields | set(generated_qualification_fields))
        ai_settings["qualification_fields"] = merged_fields
        ai_settings["custom_fields"] = merged_fields
        tenant.ai_settings = ai_settings
        session.add(tenant)
        saved_qual_fields = True
        generated_qualification_fields = merged_fields  # Update for count
    
    # Soft delete existing stages
    existing_result = await session.execute(
        select(SalesStage)
        .where(SalesStage.tenant_id == current_user.tenant_id)
    )
    existing_stages = existing_result.scalars().all()
    
    for stage in existing_stages:
        stage.is_active = False
        session.add(stage)
    
    # Create new stages from AI response
    created_stages = []
    
    for order_index, stage_data in enumerate(generated_stages, start=1):
        new_stage = SalesStage(
            tenant_id=current_user.tenant_id,
            name=stage_data.get("name", f"Этап {order_index}"),
            description=stage_data.get("description"),
            ai_goal=stage_data.get("ai_goal", "Продвигать клиента по воронке"),
            exit_criteria=stage_data.get("exit_criteria", []),
            order_index=order_index,
            is_active=True
        )
        session.add(new_stage)
        created_stages.append(new_stage)
    
    await session.commit()
    
    # Refresh to get IDs
    for stage in created_stages:
        await session.refresh(stage)
    
    # Sync all exit criteria to tenant qualification fields
    await sync_tenant_qualification_fields(session, current_user.tenant_id)
    
    # Count actual qualification fields saved
    qual_fields_count = len(generated_qualification_fields) if generated_qualification_fields else 0
    
    return GenerateFunnelResponse(
        success=True,
        message=f"Сгенерировано {len(created_stages)} этапов воронки" + (f" и {qual_fields_count} полей квалификации" if qual_fields_count > 0 else ""),
        stages=[
            SalesStageResponse(
                id=stage.id,
                tenant_id=stage.tenant_id,
                name=stage.name,
                description=stage.description,
                order_index=stage.order_index,
                ai_goal=stage.ai_goal,
                exit_criteria=stage.exit_criteria or [],
                is_active=stage.is_active,
                created_at=stage.created_at,
                updated_at=stage.updated_at
            )
            for stage in created_stages
        ]
    )