Spaces:
Sleeping

File size: 43,986 Bytes
f0e1c07
 
 
 
 
 
 
 
5b233df
 
f0e1c07
 
2c5de26
 
75467da
f0e1c07
2c5de26
 
f0e1c07
 
 
 
 
 
 
 
 
 
 
 
 
5a46e32
 
f0e1c07
 
 
 
795384e
5a46e32
795384e
f0e1c07
 
 
 
 
 
5b233df
f0e1c07
 
 
9e8e3d1
f0e1c07
 
 
795384e
 
ff263d8
9e8e3d1
 
f0e1c07
 
 
 
 
cf33fb8
d990df1
 
cf33fb8
 
ff263d8
 
cf33fb8
9e8e3d1
5a46e32
ff263d8
f0e1c07
ff263d8
f0e1c07
ff263d8
f0e1c07
ff263d8
 
 
 
 
f0e1c07
5a46e32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff263d8
 
 
 
 
 
 
 
 
 
 
 
 
f0e1c07
ff263d8
 
 
 
 
 
 
 
f0e1c07
6babd88
795384e
 
6babd88
795384e
6babd88
 
 
795384e
 
 
 
 
 
 
 
6babd88
 
 
795384e
6babd88
9e8e3d1
 
 
 
 
 
 
 
 
 
 
 
f0e1c07
9e44e54
 
 
 
84103e7
 
9e44e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8e3d1
f0e1c07
795384e
 
9e44e54
f0e1c07
 
 
 
a9615a7
 
795384e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8e3d1
38a7c68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a2e3d
1bd37d2
25a2e3d
d990df1
 
 
38a7c68
 
 
 
 
 
 
 
d990df1
38a7c68
25a2e3d
38a7c68
 
25a2e3d
38a7c68
 
25a2e3d
38a7c68
25a2e3d
38a7c68
25a2e3d
38a7c68
 
25a2e3d
38a7c68
 
 
25a2e3d
38a7c68
25a2e3d
38a7c68
 
 
 
 
 
 
25a2e3d
5bb4c25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a2e3d
38a7c68
5bb4c25
ddfbf86
 
 
 
2c5de26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddfbf86
38a7c68
 
cf33fb8
d990df1
25a2e3d
d990df1
 
 
cf33fb8
bb3a0f2
 
 
 
38a7c68
 
cf33fb8
38a7c68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9615a7
795384e
a9615a7
7756d2d
a9615a7
 
 
 
38a7c68
 
a9615a7
7756d2d
a9615a7
 
38a7c68
a9615a7
 
 
 
 
 
 
7756d2d
 
a9615a7
 
 
 
 
 
 
 
 
 
597f927
a9615a7
17d53fb
 
2abcc5f
a9615a7
2c5de26
2621961
2c5de26
 
2621961
2c5de26
 
2621961
2c5de26
 
2621961
2c5de26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597f927
7756d2d
 
 
 
 
 
 
 
 
597f927
 
7756d2d
2c5de26
 
 
 
 
 
7756d2d
597f927
7756d2d
 
597f927
7756d2d
 
2c5de26
7756d2d
 
 
2abcc5f
7756d2d
 
2c5de26
7756d2d
 
 
 
 
 
 
 
 
52535fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7756d2d
 
2c5de26
7756d2d
 
 
2c5de26
7756d2d
 
52535fd
7756d2d
2c5de26
 
 
 
 
 
 
 
 
 
 
7756d2d
 
 
 
 
 
 
 
 
 
 
a9615a7
 
 
 
 
 
 
 
7756d2d
a9615a7
7756d2d
a9615a7
 
 
 
 
7756d2d
a9615a7
7756d2d
a9615a7
7756d2d
a9615a7
7756d2d
 
 
 
a9615a7
 
 
 
 
7756d2d
 
a9615a7
 
 
 
 
 
 
 
7756d2d
a9615a7
d990df1
a9615a7
7756d2d
 
 
 
 
 
 
 
a9615a7
 
7756d2d
 
 
 
 
 
 
 
a9615a7
 
7756d2d
 
 
 
 
 
 
 
a9615a7
a3e1c21
a9615a7
a3e1c21
a9615a7
7756d2d
 
 
 
 
 
 
a9615a7
 
a3e1c21
7756d2d
 
 
 
 
 
 
 
a9615a7
a3e1c21
a9615a7
a3e1c21
a9615a7
7756d2d
 
 
 
 
a3e1c21
7756d2d
 
ddfbf86
a9615a7
a3e1c21
a9615a7
 
 
 
 
 
 
 
 
 
a3e1c21
7756d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5de26
7756d2d
 
2c5de26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddfbf86
a9615a7
 
38a7c68
 
a9615a7
38a7c68
7756d2d
 
 
 
5bb4c25
 
7756d2d
38a7c68
7756d2d
a9615a7
 
38a7c68
 
7756d2d
 
a9615a7
 
 
 
 
38a7c68
 
7756d2d
a9615a7
38a7c68
a9615a7
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
"""
Demo Chat API - Test AI responses without saving to database
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import logging

from app.api.deps import get_current_user
from app.core.database import get_async_session
from app.models.user import User
from app.models.tenant import Tenant
from app.models.product import Product
from app.models.booking import Service
from app.services.ai_memory_manager import memory_manager
from app.core.config import settings
from sqlmodel import select


logger = logging.getLogger(__name__)
router = APIRouter(prefix="/demo", tags=["Demo"])


class DemoChatMessage(BaseModel):
    role: str  # 'user' or 'ai'
    content: str


class DemoChatRequest(BaseModel):
    message: str
    history: List[DemoChatMessage] = []
    corrections: List[str] = []  # Legacy, kept for backwards compatibility
    mode: str = "normal"  # "normal" = test like client, "correction" = owner mode with settings proposals


class DemoChatResponse(BaseModel):
    response: str
    pending_action: Optional[dict] = None  # Action waiting for user confirmation
    proposed_changes: List[dict] = []  # Changes proposed by AI in correction mode



@router.post("/chat", response_model=DemoChatResponse)
async def demo_chat(
    request: DemoChatRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_async_session)
):
    """
    Generate AI response for demo/testing purposes.
    NOW uses FULL AICore with all features: voice, products, booking, etc.
    Does NOT save to database - purely for testing AI behavior.
    """
    try:
        from app.services.ai_core.settings_assistant import parse_ai_action, execute_setting_change, remove_action_from_response, get_setting_display_name

        from google import genai
        import re
        
        # Get tenant
        tenant = await session.get(Tenant, current_user.tenant_id)
        if not tenant:
            raise HTTPException(status_code=404, detail="Tenant not found")
        
        # DEBUG: Log current settings
        # FIXED: ai_identity is stored in ai_settings by settings/brain page
        ai_identity = (tenant.ai_settings or {}).get("ai_identity", {})
        logger.info(f"🔍 Demo chat - bot_name from DB: {ai_identity.get('bot_name', 'NOT SET')}")
        
        # Build FULL context using memory manager (includes KB, products, settings)
        tenant_context = await memory_manager.build_tenant_context(session, tenant)

        
        # Add corrections to context if any (legacy support)
        corrections_prompt = ""
        if request.corrections:
            corrections_prompt = "\n\n[ВАЖНЫЕ ПРАВКИ ОТ ВЛАДЕЛЬЦА - СТРОГО СЛЕДУЙ]:\n"
            for i, correction in enumerate(request.corrections, 1):
                corrections_prompt += f"{i}. {correction}\n"
        
        # Build conversation history
        history_text = ""
        for msg in request.history[-10:]:
            role = "Клиент" if msg.role == "user" else "Ты"
            history_text += f"{role}: {msg.content}\n"
        
        # MODE SWITCH: Normal (client simulation) vs Correction (owner mode)
        if request.mode == "correction":
            # CORRECTION MODE: AI talks to business owner
            full_prompt = f"""Ты AI-консультант MicroFunnel. Ты общаешься с ВЛАДЕЛЬЦЕМ бизнеса, а НЕ с клиентом.

=== ТЕКУЩИЕ НАСТРОЙКИ БОТА ===
Имя бота: {ai_identity.get('bot_name', 'не задано')}
Роль: {ai_identity.get('bot_role', 'не задана')}
Пол: {ai_identity.get('bot_gender', 'не задан')}
Тон общения: {tenant.tone_of_voice or 'не задан'}
Методология: {tenant.sales_methodology or 'не задана'}
Инструкции: {(tenant.custom_instructions or 'нет')[:200]}

=== ИСТОРИЯ ОБСУЖДЕНИЯ С ВЛАДЕЛЬЦЕМ ===
{history_text}
Владелец: {request.message}

=== ТВОЯ ЗАДАЧА ===
1. Помоги владельцу настроить AI-ассистента
2. Если он просит изменить настройки — ОБСУДИ сначала, потом предложи конкретные изменения
3. Отвечай дружелюбно и экспертно
4. Если владелец говорит что-то вроде "ты теперь X" или "называй себя Y" — уточни: "Хотите изменить имя бота на X?"
5. НЕ применяй изменения сам — только ОБСУЖДАЙ и ПРЕДЛАГАЙ

Ответь как AI-консультант MicroFunnel:"""
        else:
            # NORMAL MODE: AI simulates client conversation
            full_prompt = f"""{tenant_context}

{corrections_prompt}

=== ИСТОРИЯ ДИАЛОГА ===
{history_text}
Клиент: {request.message}

=== ТВОЙ ОТВЕТ ===
Ответь как ассистент, следуя всем правилам выше.
"""
        
        # Generate response using Gemini
        client = genai.Client(api_key=settings.GEMINI_API_KEY)
        
        response = client.models.generate_content(
            model=settings.GEMINI_MODEL,
            contents=full_prompt
        )
        
        ai_response = response.text if response.text else "Не удалось сгенерировать ответ"
        ai_response = ai_response.strip()

        
        # ========================================================================
        # SMART SETTINGS ASSISTANT: Parse __AI_ACTION__ but DON'T execute yet
        # Return as pending_action for frontend confirmation
        # ========================================================================
        pending_action = None
        if "__AI_ACTION__" in ai_response:
            action = parse_ai_action(ai_response)
            if action:
                logger.info(f"🔧 Demo chat detected AI action (pending confirmation): {action}")
                # DON'T execute - return for user confirmation
                pending_action = {
                    "type": action.get("type"),
                    "path": action.get("path"),
                    "value": action.get("value"),
                    "display_path": get_setting_display_name(action.get("path", ""))
                }
            
            # Remove the action block from visible response
            ai_response = remove_action_from_response(ai_response)

        
        # Don't remove [SEND_VOICE] - let frontend handle it for demo
        # Just log what features were triggered
        has_voice = "[SEND_VOICE]" in ai_response
        has_media_match = re.search(r'\[SEND_MEDIA:([^\]]+)\]', ai_response)
        has_booking = "[BOOK_CONFIRMED:" in ai_response
        
        if has_voice:
            logger.info("🎤 Demo: Voice response requested")
        if has_media_match:
            logger.info(f"📎 Demo: Media requested: {has_media_match.group(1)}")
        if has_booking:
            logger.info("📅 Demo: Booking confirmed")
        
        # ========================================================================
        # ENRICHMENT: Add Product Cards and File Info for Frontend
        # ========================================================================
        from app.models.product import Product
        from app.models.knowledge import KnowledgeBase

        from sqlalchemy import select
        
        # 1. Detect Products mentioned in text (like webhook does)
        # Fetch all active products
        products_stmt = select(Product).where(Product.tenant_id == tenant.id, Product.is_active == True)
        products_result = await session.execute(products_stmt)
        products = products_result.scalars().all()
        
        ai_response_lower = ai_response.lower()
        shown_products = set()
        
        for product in products:
            if product.name.lower() in ai_response_lower:
                # Add SHOW_PRODUCT tag
                img_url = product.image_url or ""
                price = f"{product.price} {product.currency}"
                # Format: [SHOW_PRODUCT:ID|Name|Price|ImageURL]
                tag = f"\n[SHOW_PRODUCT:{product.id}|{product.name}|{price}|{img_url}]"
                ai_response += tag
                shown_products.add(product.id)
                logger.info(f"🛍️ Demo: Product detected: {product.name}")
        
        # 2. Enrich Media Tags [SEND_MEDIA:ID] -> [SHOW_FILE:ID|Name|Type]
        media_matches = re.finditer(r'\[SEND_MEDIA:([^\]]+)\]', ai_response)
        for match in media_matches:
            media_id_prefix = match.group(1)
            # Find file in KB
            # Since ID is shortened in tag, we search by prefix (or simulated lookup)
            # Actually AICore puts simplified ID. We need to find the real file.
            # Assuming id_prefix is enough to find via like or python filter
            stmt_kb = select(KnowledgeBase).where(
                KnowledgeBase.tenant_id == tenant.id,
                KnowledgeBase.id.cast(str).like(f"{media_id_prefix}%")
            )
            kb_res = await session.execute(stmt_kb)
            kb_file = kb_res.scalars().first()
            
            if kb_file:
                # Replace with rich tag: [SHOW_FILE:ID|Name|Type]
                rich_tag = f"[SHOW_FILE:{kb_file.id}|{kb_file.name}|{kb_file.file_type}]"
                ai_response = ai_response.replace(match.group(0), rich_tag)
                logger.info(f"📎 Demo: Enriched file tag: {kb_file.name}")
        
        logger.info(f"🎮 Demo chat FULL response generated for tenant {tenant.id}")
        
        return DemoChatResponse(response=ai_response.strip(), pending_action=pending_action)


        
    except Exception as e:
        logger.error(f"❌ Demo chat error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ============================================================================
# CONFIRM ACTION ENDPOINT - Execute pending settings change
# ============================================================================

class ConfirmActionRequest(BaseModel):
    action: dict  # The pending_action from chat response


class ConfirmActionResponse(BaseModel):
    success: bool
    message: str
    changed_path: Optional[str] = None
    old_value: Optional[str] = None
    new_value: Optional[str] = None


@router.post("/confirm-action", response_model=ConfirmActionResponse)
async def confirm_action(
    request: ConfirmActionRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_async_session)
):
    """
    Execute a pending settings change after user confirmation.
    Called when user clicks "Apply" button in the confirmation UI.
    """
    try:
        from app.services.ai_core.settings_assistant import execute_setting_change
        
        tenant = await session.get(Tenant, current_user.tenant_id)
        if not tenant:
            raise HTTPException(status_code=404, detail="Tenant not found")
        
        result = await execute_setting_change(session, tenant, request.action)
        
        if result.get("success"):
            logger.info(f"✅ Action confirmed and executed: {request.action.get('path')} = {request.action.get('value')}")
            return ConfirmActionResponse(
                success=True,
                message="Настройка успешно изменена",
                changed_path=result.get("changed_path"),
                old_value=str(result.get("old_value", "")),
                new_value=str(result.get("new_value", ""))
            )
        else:
            return ConfirmActionResponse(
                success=False,
                message=result.get("message", "Ошибка при изменении настройки")
            )
            
    except Exception as e:
        logger.error(f"❌ Confirm action error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ============================================================================
# CONFIRM SMART CORRECTION - Apply pending smart correction changes
# ============================================================================

class ConfirmSmartCorrectionRequest(BaseModel):
    pending_changes: List[dict]


@router.post("/confirm-smart-correction", response_model=ConfirmActionResponse)
async def confirm_smart_correction(
    request: ConfirmSmartCorrectionRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_async_session)
):
    """
    Apply pending smart correction changes after user confirmation.
    """
    try:
        tenant = await session.get(Tenant, current_user.tenant_id)
        if not tenant:
            raise HTTPException(status_code=404, detail="Tenant not found")
        
        # CRITICAL: Use deepcopy so SQLAlchemy detects changes to JSONB fields
        import copy
        
        # FIXED: ai_identity is stored INSIDE ai_settings by settings/brain page
        ai_settings = copy.deepcopy(tenant.ai_settings or {})
        ai_identity = ai_settings.get("ai_identity", {})
        
        applied_count = 0
        
        for change in request.pending_changes:
            field = change.get("field", "")
            new_value = change.get("new", "")
            
            # Map field names to settings paths
            # Bot identity goes to ai_settings.ai_identity
            if "Имя бота" in field:
                ai_identity["bot_name"] = new_value
                applied_count += 1
            elif "Роль бота" in field:
                ai_identity["bot_role"] = new_value
                applied_count += 1
            elif "Пол бота" in field:
                ai_identity["bot_gender"] = "female" if "Женский" in new_value else "male"
                applied_count += 1
            # These go to direct tenant fields
            elif "Тон общения" in field:
                tenant.tone_of_voice = new_value
                applied_count += 1
            elif "Методология продаж" in field:
                tenant.sales_methodology = new_value
                applied_count += 1
            elif "Запрещённые" in field:
                if new_value.startswith("+"):
                    banned = list(tenant.banned_words or [])
                    banned.append(new_value[1:])
                    tenant.banned_words = banned
                    applied_count += 1
            elif "Инструкции" in field or "инструкц" in field.lower():
                if "..." in new_value:
                    full_value = change.get("full_value", new_value.replace("...", ""))
                else:
                    full_value = new_value
                
                current = tenant.custom_instructions or ""
                
                # Smart instruction handling: detect and replace contradictions
                # Common contradicting patterns
                contradictions = [
                    (["на вы", "на «вы»", "обращайся на вы"], ["на ты", "на «ты»", "обращайся на ты"]),
                    (["мужского рода", "мужской род"], ["женского рода", "женский род"]),
                    (["формальн", "официальн"], ["неформальн", "разговорн"]),
                ]
                
                # Check if new instruction contradicts any existing ones
                lines = current.split("\n") if current else []
                new_lower = full_value.lower()
                
                # Find which pattern group the new instruction belongs to
                for group_a, group_b in contradictions:
                    in_a = any(p in new_lower for p in group_a)
                    in_b = any(p in new_lower for p in group_b)
                    
                    if in_a or in_b:
                        # Remove any existing contradicting instructions
                        opposite = group_b if in_a else group_a
                        lines = [line for line in lines 
                                 if not any(p in line.lower() for p in opposite + (group_a if in_a else group_b))]
                
                # Add new instruction (avoiding duplicates)
                if full_value.strip() not in "\n".join(lines):
                    lines.append(full_value.strip())
                
                # Limit total instructions to prevent bloat (max 10 lines)
                if len(lines) > 10:
                    lines = lines[-10:]
                
                tenant.custom_instructions = "\n".join(filter(None, lines))
                applied_count += 1

            elif "Идеальный клиент" in field or "клиент" in field.lower():
                full_value = change.get("full_value", new_value.replace("...", ""))
                ai_settings["ideal_customer_profile"] = full_value
                applied_count += 1
            
            elif "Описание бизнеса" in field or "бизнес" in field.lower():
                full_value = change.get("full_value", new_value.replace("...", ""))
                ai_settings["business_description"] = full_value
                applied_count += 1
            
            # PRODUCT ACTIONS
            action = change.get("action", "")
            
            if action == "update_product":
                product_id = change.get("product_id")
                product_field = change.get("product_field")
                product_value = change.get("product_value")
                if product_id and product_field and product_value is not None:
                    from uuid import UUID
                    product = await session.get(Product, UUID(product_id))
                    if product:
                        if product_field == "price":
                            product.price = float(product_value)
                        elif product_field == "name":
                            product.name = str(product_value)
                        elif product_field == "description":
                            product.description = str(product_value)
                        session.add(product)
                        applied_count += 1
            
            elif action == "add_product":
                product_name = change.get("product_name")
                product_price = change.get("product_price", 0)
                product_description = change.get("product_description", "")
                if product_name:
                    new_product = Product(
                        tenant_id=tenant.id,
                        name=product_name,
                        price=float(product_price),
                        description=product_description,
                        currency="RUB"
                    )
                    session.add(new_product)
                    applied_count += 1
            
            elif action == "delete_product":
                product_id = change.get("product_id")
                if product_id:
                    from uuid import UUID
                    product = await session.get(Product, UUID(product_id))
                    if product:
                        product.is_active = False
                        session.add(product)
                        applied_count += 1
            
            # SERVICE ACTIONS
            elif action == "update_service":
                service_id = change.get("service_id")
                service_field = change.get("service_field")
                service_value = change.get("service_value")
                if service_id and service_field and service_value is not None:
                    from uuid import UUID
                    service = await session.get(Service, UUID(service_id))
                    if service:
                        if service_field == "price":
                            service.price = float(service_value)
                        elif service_field == "name":
                            service.name = str(service_value)
                        elif service_field == "duration_minutes":
                            service.duration_minutes = int(service_value)
                        session.add(service)
                        applied_count += 1
            
            elif action == "add_service":
                service_name = change.get("service_name")
                service_price = change.get("service_price", 0)
                service_duration = change.get("service_duration", 30)
                if service_name:
                    new_service = Service(
                        tenant_id=tenant.id,
                        name=service_name,
                        price=float(service_price),
                        duration_minutes=int(service_duration),
                        currency="RUB"
                    )
                    session.add(new_service)
                    applied_count += 1

        
        if applied_count > 0:
            # DEBUG: Log what we're saving
            logger.info(f"🔧 Saving ai_identity to ai_settings: {ai_identity}")
            
            # FIXED: Save ai_identity INSIDE ai_settings where settings/brain reads from
            ai_settings["ai_identity"] = ai_identity
            tenant.ai_settings = ai_settings
            
            # CRITICAL: Mark JSONB field as modified so SQLAlchemy commits changes
            from sqlalchemy.orm.attributes import flag_modified
            flag_modified(tenant, "ai_settings")
            
            session.add(tenant)
            await session.commit()

            
            # Invalidate AI cache
            await memory_manager.invalidate_memory(session, tenant)
            
            logger.info(f"✅ Smart correction APPLIED for tenant {tenant.id}: {applied_count} changes")
            
            return ConfirmActionResponse(
                success=True,
                message=f"Применено {applied_count} изменений"
            )
        else:
            return ConfirmActionResponse(
                success=False,
                message="Нет изменений для применения"
            )
            
    except Exception as e:
        logger.error(f"❌ Confirm smart correction error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


class SmartCorrectionRequest(BaseModel):

    correction: str
    last_ai_response: Optional[str] = None  # What AI said that was wrong


class SmartCorrectionResponse(BaseModel):
    success: bool
    changes: List[dict]  # Applied changes (empty now - for backwards compat)
    pending_changes: List[dict] = []  # Changes waiting for confirmation
    message: str
    analysis: Optional[str] = None  # Why AI was wrong



@router.post("/smart-correct", response_model=SmartCorrectionResponse)
async def smart_correct(
    request: SmartCorrectionRequest,
    current_user: User = Depends(get_current_user),
    session = Depends(get_async_session)
):
    """
    AI-powered correction that analyzes WHY the bot responded incorrectly
    and modifies the appropriate tenant settings to fix it.
    """
    try:
        from google import genai
        import json
        import re
        
        tenant = await session.get(Tenant, current_user.tenant_id)
        if not tenant:
            raise HTTPException(status_code=404, detail="Tenant not found")
        
        # Get FULL settings context - READ FROM CORRECT FIELDS
        ai_settings = tenant.ai_settings or {}
        # FIXED: ai_identity is stored INSIDE ai_settings by settings/brain page
        ai_identity = ai_settings.get("ai_identity", {})
        playbook = ai_settings.get("playbook", {})
        
        # Fetch Products (catalog)
        products_result = await session.execute(
            select(Product).where(Product.tenant_id == tenant.id, Product.is_active == True).limit(20)
        )
        products = products_result.scalars().all()
        
        # Fetch Services (booking)
        services_result = await session.execute(
            select(Service).where(Service.tenant_id == tenant.id, Service.is_active == True).limit(20)
        )
        services = services_result.scalars().all()
        
        # Build products list
        products_text = ""
        for p in products:
            products_text += f"  - ID:{p.id} | {p.name} | {p.price} {p.currency}"
            if p.description:
                products_text += f" | {p.description[:50]}"
            products_text += "\n"
        if not products_text:
            products_text = "  (нет товаров)"
        
        # Build services list
        services_text = ""
        for s in services:
            services_text += f"  - ID:{s.id} | {s.name} | {s.price} {s.currency} | {s.duration_minutes} мин\n"
        if not services_text:
            services_text = "  (нет услуг)"
        
        # Build comprehensive context - USE CORRECT TENANT FIELDS
        current_config = f"""
=== ТЕКУЩИЕ НАСТРОЙКИ AI (tenant: {tenant.id}) ===

[ЛИЧНОСТЬ БОТА]
- Имя бота: {ai_identity.get('bot_name', 'AI Assistant')}
- Роль: {ai_identity.get('bot_role', 'Менеджер по продажам')}
- Пол: {ai_identity.get('bot_gender', 'female')}

[ТОН И СТИЛЬ]
- Тон общения: {tenant.tone_of_voice or 'Professional'}
- Методология продаж: {tenant.sales_methodology or 'Consultative'}

[КАТАЛОГ ТОВАРОВ]
{products_text}

[УСЛУГИ И ЗАПИСИ]
{services_text}

[ЗАПРЕТЫ]
- Запрещённые слова: {tenant.banned_words or []}

[ИНСТРУКЦИИ]
{(tenant.custom_instructions or '(пусто)')[:500]}

[PLAYBOOK - ЭТАПЫ ВОРОНКИ]
{json.dumps(playbook.get('stages', []), ensure_ascii=False, indent=2)[:500] if playbook.get('stages') else '(нет этапов)'}

[ДРУГОЕ]
- Идеальный клиент: {ai_settings.get('ideal_customer_profile', '(не задано)')[:200]}
- Описание бизнеса: {ai_settings.get('business_description', '(не задано)')[:200]}
"""


        # Build the analysis prompt
        parse_prompt = f"""Ты эксперт по настройке AI-ассистентов. Пользователь указал проблему с ответом бота.

{current_config}

=== ПРОБЛЕМА ПОЛЬЗОВАТЕЛЯ ===
"{request.correction}"
{f'Ответ бота который не понравился: "{request.last_ai_response}"' if request.last_ai_response else ''}

=== КРИТИЧЕСКИ ВАЖНЫЕ ПРАВИЛА ИНТЕРПРЕТАЦИИ ===

1. ИМЕНА И ЛИЧНОСТЬ:
   - "ты джарвис" / "тебя зовут X" / "твоё имя X" → action: "set_bot_name", value: "X"
   - "ты девушка" / "женский пол" → action: "set_bot_gender", value: "female"
   - "ты мужик" / "мужской пол" → action: "set_bot_gender", value: "male"
   - НЕ добавляй инструкции про имя — меняй само имя бота!

2. ТОН И СТИЛЬ:
   - "будь дружелюбнее" / "на ты" → action: "set_tone", value: "Friendly"
   - "формально" / "на вы" → action: "set_tone", value: "Professional"
   - "смело" / "агрессивно продавай" → action: "set_tone", value: "Bold"

3. ПОВЕДЕНИЕ:
   - "не говори X" / "не упоминай X" → action: "add_banned_word", value: "X"
   - "всегда делай X" / "обязательно Y" → action: "add_instruction", value: текст

ПРИМЕРЫ:
- Ввод: "ты джарвис" → {{"action": "set_bot_name", "value": "Джарвис", "reason": "Пользователь хочет имя бота Джарвис"}}
- Ввод: "называй себя Анна" → {{"action": "set_bot_name", "value": "Анна", "reason": "Смена имени бота"}}
- Ввод: "ты женщина" → {{"action": "set_bot_gender", "value": "female", "reason": "Смена пола бота"}}
- Ввод: "общайся на ты" → {{"action": "set_tone", "value": "Friendly", "reason": "Дружелюбный тон = на ты"}}
- Ввод: "не говори про скидки" → {{"action": "add_banned_word", "value": "скидки", "reason": "Запрет слова"}}

=== ДОСТУПНЫЕ ДЕЙСТВИЯ ===
НАСТРОЙКИ БОТА:
- "set_bot_name": изменить имя бота (value: новое имя)
- "set_bot_role": изменить роль (value: новая роль)
- "set_bot_gender": изменить пол (value: "male" или "female")
- "set_tone": изменить тон (value: Professional/Friendly/Empathetic/Bold)
- "add_banned_word": добавить запрет (value: слово)
- "remove_banned_word": убрать запрет (value: слово)
- "add_instruction": добавить инструкцию (value: текст) — ТОЛЬКО для сложных правил поведения
- "update_ideal_customer": обновить профиль клиента (value: описание)
- "update_business_description": обновить описание бизнеса (value: описание)

КАТАЛОГ (товары):
- "update_product": изменить товар (id: UUID товара, field: "name"/"price"/"description", value: новое значение)
- "add_product": добавить товар (name: название, price: цена, description: описание)
- "delete_product": удалить товар (id: UUID товара)

УСЛУГИ (записи):
- "update_service": изменить услугу (id: UUID услуги, field: "name"/"price"/"duration_minutes", value: новое значение)
- "add_service": добавить услугу (name: название, price: цена, duration_minutes: длительность)


=== ФОРМАТ ОТВЕТА ===
Верни JSON объект:
{{
  "analysis": "Краткое объяснение почему бот отвечал неправильно",
  "changes": [
    {{"action": "действие", "value": "значение", "reason": "почему это исправит проблему"}}
  ]
}}

ВАЖНО: Верни ТОЛЬКО валидный JSON, без ```json и без пояснений снаружи JSON.
"""

        client = genai.Client(api_key=settings.GEMINI_API_KEY)
        response = client.models.generate_content(
            model=settings.GEMINI_MODEL,
            contents=parse_prompt
        )
        
        ai_response = response.text.strip() if response.text else "{}"
        
        # Clean markdown
        ai_response = re.sub(r'```json\s*', '', ai_response)
        ai_response = re.sub(r'```\s*', '', ai_response)
        
        # Parse JSON
        try:
            result = json.loads(ai_response)
        except json.JSONDecodeError:
            match = re.search(r'\{.*\}', ai_response, re.DOTALL)
            if match:
                result = json.loads(match.group())
            else:
                result = {"analysis": "", "changes": []}
        
        analysis = result.get("analysis", "")
        changes = result.get("changes", [])
        
        if not changes:
            return SmartCorrectionResponse(
                success=False,
                changes=[],
                message="Не удалось определить какие настройки изменить",
                analysis=analysis
            )
        
        # Apply changes
        applied_changes = []
        
        for change in changes:
            action = change.get("action", "")
            value = change.get("value", "")
            reason = change.get("reason", "")
            
            # Bot identity - now correctly read from ai_settings.ai_identity
            if action == "set_bot_name" and value:
                old_value = ai_identity.get('bot_name', 'AI Assistant')
                applied_changes.append({
                    "field": "Имя бота",
                    "section": "AI Мозг → Личность",
                    "old": old_value,
                    "new": value,
                    "reason": reason
                })
            
            elif action == "set_bot_role" and value:
                old_value = ai_identity.get('bot_role', 'Менеджер')
                applied_changes.append({
                    "field": "Роль бота",
                    "section": "AI Мозг → Личность",
                    "old": old_value,
                    "new": value,
                    "reason": reason
                })
            
            elif action == "set_bot_gender" and value in ["male", "female"]:
                old_value = ai_identity.get('bot_gender', 'female')
                applied_changes.append({
                    "field": "Пол бота",
                    "section": "AI Мозг → Личность",
                    "old": "Женский" if old_value == "female" else "Мужской",
                    "new": "Женский" if value == "female" else "Мужской",
                    "reason": reason
                })
            
            # Banned words - read from tenant.banned_words (correct field)
            elif action == "add_banned_word" and value:
                banned = list(tenant.banned_words or [])
                if value.lower() not in [w.lower() for w in banned]:
                    applied_changes.append({
                        "field": "Запрещённые слова",
                        "section": "AI Мозг → Фильтры",
                        "old": "(не было)",
                        "new": f"+{value}",
                        "reason": reason
                    })
            
            elif action == "remove_banned_word" and value:
                banned = list(tenant.banned_words or [])
                if value.lower() in [w.lower() for w in banned]:
                    applied_changes.append({
                        "field": "Запрещённые слова",
                        "section": "AI Мозг → Фильтры",
                        "old": value,
                        "new": "(удалено)",
                        "reason": reason
                    })
            
            # Custom instructions - read from tenant.custom_instructions (correct field)
            elif action == "add_instruction" and value:
                current = tenant.custom_instructions or ""
                if value not in current:
                    applied_changes.append({
                        "field": "Инструкции",
                        "section": "AI Мозг → Глобальный промпт",
                        "old": "(добавлено новое)",
                        "new": value[:100] + ("..." if len(value) > 100 else ""),
                        "full_value": value,
                        "reason": reason
                    })

            
            # Tone - read from tenant.tone_of_voice (correct field)
            elif action == "set_tone" and value:
                valid_tones = ["Professional", "Friendly", "Empathetic", "Bold"]
                tone_map = {
                    "профессиональный": "Professional",
                    "дружелюбный": "Friendly",
                    "эмпатичный": "Empathetic",
                    "уверенный": "Bold"
                }
                mapped = tone_map.get(value.lower(), value)
                if mapped in valid_tones:
                    old_value = tenant.tone_of_voice or "Professional"
                    applied_changes.append({
                        "field": "Тон общения",
                        "section": "AI Мозг → Стиль",
                        "old": old_value,
                        "new": mapped,
                        "reason": reason
                    })
            
            elif action == "update_ideal_customer" and value:
                old_value = ai_settings.get("ideal_customer_profile", "")
                ai_settings["ideal_customer_profile"] = value
                applied_changes.append({
                    "field": "Идеальный клиент",
                    "section": "AI Мозг → Таргетинг",
                    "old": old_value[:50] + "..." if old_value else "(пусто)",
                    "new": value[:50] + "...",
                    "full_value": value,
                    "reason": reason
                })
            
            elif action == "update_business_description" and value:
                old_value = ai_settings.get("business_description", "")
                ai_settings["business_description"] = value
                applied_changes.append({
                    "field": "Описание бизнеса",
                    "section": "AI Мозг → О компании",
                    "old": old_value[:50] + "..." if old_value else "(пусто)",
                    "new": value[:50] + "...",
                    "full_value": value,
                    "reason": reason
                })
            
            # PRODUCT ACTIONS
            elif action == "update_product":
                product_id = change.get("id")
                field = change.get("field")
                if product_id and field and value:
                    # Find product by ID or name
                    product = None
                    for p in products:
                        if str(p.id) == str(product_id) or p.name.lower() == str(product_id).lower():
                            product = p
                            break
                    
                    if product:
                        old_value = getattr(product, field, None)
                        applied_changes.append({
                            "action": "update_product",
                            "field": f"Товар: {product.name}",
                            "section": "Каталог",
                            "old": f"{field}: {old_value}",
                            "new": f"{field}: {value}",
                            "product_id": str(product.id),
                            "product_field": field,
                            "product_value": value,
                            "reason": reason
                        })
            
            elif action == "add_product":
                name = change.get("name")
                price = change.get("price", 0)
                description = change.get("description", "")
                if name:
                    applied_changes.append({
                        "action": "add_product",
                        "field": f"Новый товар",
                        "section": "Каталог",
                        "old": "(нет)",
                        "new": f"{name} — {price}₽",
                        "product_name": name,
                        "product_price": float(price) if price else 0,
                        "product_description": description,
                        "reason": reason
                    })
            
            elif action == "delete_product":
                product_id = change.get("id")
                if product_id:
                    product = None
                    for p in products:
                        if str(p.id) == str(product_id) or p.name.lower() == str(product_id).lower():
                            product = p
                            break
                    if product:
                        applied_changes.append({
                            "action": "delete_product",
                            "field": f"Удаление товара",
                            "section": "Каталог",
                            "old": product.name,
                            "new": "(удалён)",
                            "product_id": str(product.id),
                            "reason": reason
                        })
            
            # SERVICE ACTIONS
            elif action == "update_service":
                service_id = change.get("id")
                field = change.get("field")
                if service_id and field and value:
                    service = None
                    for s in services:
                        if str(s.id) == str(service_id) or s.name.lower() == str(service_id).lower():
                            service = s
                            break
                    
                    if service:
                        old_value = getattr(service, field, None)
                        applied_changes.append({
                            "action": "update_service",
                            "field": f"Услуга: {service.name}",
                            "section": "Записи",
                            "old": f"{field}: {old_value}",
                            "new": f"{field}: {value}",
                            "service_id": str(service.id),
                            "service_field": field,
                            "service_value": value,
                            "reason": reason
                        })
            
            elif action == "add_service":
                name = change.get("name")
                price = change.get("price", 0)
                duration = change.get("duration_minutes", 30)
                if name:
                    applied_changes.append({
                        "action": "add_service",
                        "field": f"Новая услуга",
                        "section": "Записи",
                        "old": "(нет)",
                        "new": f"{name} — {price}₽, {duration} мин",
                        "service_name": name,
                        "service_price": float(price) if price else 0,
                        "service_duration": int(duration) if duration else 30,
                        "reason": reason
                    })

        
        if applied_changes:
            # DON'T save to database - return as pending for confirmation
            # Frontend will call /confirm-smart-correction to apply
            
            # Build detailed message for confirmation UI
            changes_lines = []
            for c in applied_changes:
                changes_lines.append(f"• {c['field']} ({c['section']}): {c['old']} → {c['new']}")
            
            message = f"Подтвердите изменения:\n" + "\n".join(changes_lines)

            
            logger.info(f"🔧 Smart correction PENDING for tenant {tenant.id}: {len(applied_changes)} changes")
            
            return SmartCorrectionResponse(
                success=True,
                changes=[],  # Empty - not applied yet
                pending_changes=applied_changes,  # Waiting for confirmation
                message=message,
                analysis=analysis
            )
        else:
            return SmartCorrectionResponse(
                success=False,
                changes=[],
                pending_changes=[],
                message="Изменения не найдены",
                analysis=analysis
            )

            
    except Exception as e:
        logger.error(f"❌ Smart correction error: {e}")
        raise HTTPException(status_code=500, detail=str(e))