File size: 75,453 Bytes
33514db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
import os
import json
import requests
import xml.etree.ElementTree as ET
import warnings
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from fastapi import FastAPI, Request
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse

# Yeni modüller - Basit sistem
from prompts import get_prompt_content_only
from whatsapp_renderer import extract_product_info_whatsapp
from whatsapp_passive_profiler import (
    analyze_user_message, get_user_profile_summary, get_personalized_recommendations
)

# LOGGING EN BAŞA EKLENDİ
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Import improved WhatsApp search for BF space
# DISABLED - Using GPT-5 smart warehouse search instead
USE_IMPROVED_SEARCH = False
# try:
#     from whatsapp_improved_chatbot import WhatsAppImprovedChatbot
#     USE_IMPROVED_SEARCH = True
# except ImportError:
#     print("Improved WhatsApp chatbot not available, using basic search")
#     USE_IMPROVED_SEARCH = False

# Import GPT-5 powered smart warehouse search - complete BF algorithm
try:
    from smart_warehouse_with_price import get_warehouse_stock_smart_with_price
    USE_GPT5_SEARCH = True
    logger.info("✅ GPT-5 complete smart warehouse with price (BF algorithm) loaded")
except ImportError:
    USE_GPT5_SEARCH = False
    logger.info("❌ GPT-5 search not available")

warnings.simplefilter('ignore')

# Import Media Queue V2
try:
    from media_queue_v2 import media_queue
    USE_MEDIA_QUEUE = True
    logger.info("✅ Media Queue V2 loaded successfully")
except ImportError:
    USE_MEDIA_QUEUE = False
    logger.info("❌ Media Queue V2 not available")

# Import Store Notification System
try:
    from store_notification import (
        notify_product_reservation,
        notify_price_inquiry,
        notify_stock_inquiry,
        send_test_notification,
        send_store_notification,
        should_notify_mehmet_bey
    )
    USE_STORE_NOTIFICATION = True
    logger.info("✅ Store Notification System loaded")
except ImportError:
    USE_STORE_NOTIFICATION = False
    logger.info("❌ Store Notification System not available")

# Import Intent Analyzer
try:
    from intent_analyzer import (
        analyze_customer_intent,
        should_notify_store,
        get_smart_notification_message
    )
    USE_INTENT_ANALYZER = True
    logger.info("✅ GPT-5 Intent Analyzer loaded")
except ImportError:
    USE_INTENT_ANALYZER = False
    logger.info("❌ Intent Analyzer not available")

# API ayarları
API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
logger.info(f"OpenAI API Key var mı: {'Evet' if OPENAI_API_KEY else 'Hayır'}")

# Twilio WhatsApp ayarları
TWILIO_ACCOUNT_SID = os.getenv("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
TWILIO_MESSAGING_SERVICE_SID = os.getenv("TWILIO_MESSAGING_SERVICE_SID")
TWILIO_WHATSAPP_NUMBER = "whatsapp:+905332047254"

logger.info(f"Twilio SID var mı: {'Evet' if TWILIO_ACCOUNT_SID else 'Hayır'}")
logger.info(f"Twilio Auth Token var mı: {'Evet' if TWILIO_AUTH_TOKEN else 'Hayır'}")
logger.info(f"Messaging Service SID var mı: {'Evet' if TWILIO_MESSAGING_SERVICE_SID else 'Hayır'}")

if not TWILIO_ACCOUNT_SID or not TWILIO_AUTH_TOKEN:
    logger.error("❌ Twilio bilgileri eksik!")
    twilio_client = None
else:
    try:
        twilio_client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
        logger.info("✅ Twilio client başarıyla oluşturuldu!")
    except Exception as e:
        logger.error(f"❌ Twilio client hatası: {e}")
        twilio_client = None

# Mağaza stok bilgilerini çekme fonksiyonu
def get_warehouse_stock(product_name):
    """B2B API'den mağaza stok bilgilerini çek - GPT-5 enhanced"""
    # Try GPT-5 complete smart search (BF algorithm)
    if USE_GPT5_SEARCH:
        try:
            gpt5_result = get_warehouse_stock_smart_with_price(product_name)
            if gpt5_result and isinstance(gpt5_result, list):
                # Return directly if it's already formatted strings
                if all(isinstance(item, str) for item in gpt5_result):
                    return gpt5_result
                # Format for WhatsApp if dict format
                warehouse_info = []
                for item in gpt5_result:
                    if isinstance(item, dict):
                        info = f"📦 {item.get('name', '')}"
                        if item.get('variant'):
                            info += f" ({item['variant']})"
                        if item.get('warehouses'):
                            info += f"\n📍 Mevcut: {', '.join(item['warehouses'])}"
                        if item.get('price'):
                            info += f"\n💰 {item['price']}"
                        warehouse_info.append(info)
                    else:
                        warehouse_info.append(str(item))
                return warehouse_info if warehouse_info else None
        except Exception as e:
            logger.error(f"GPT-5 warehouse search error: {e}")
            # Continue to fallback search
    
    # Fallback to original search
    try:
        import re
        warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
        response = requests.get(warehouse_url, verify=False, timeout=15)
        
        if response.status_code != 200:
            return None
            
        root = ET.fromstring(response.content)
        
        # Turkish character normalization function
        turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}
        
        def normalize_turkish(text):
            import unicodedata
            text = unicodedata.normalize('NFD', text)
            text = ''.join(char for char in text if unicodedata.category(char) != 'Mn')
            for tr_char, en_char in turkish_map.items():
                text = text.replace(tr_char, en_char)
            return text
        
        # Normalize search product name
        search_name = normalize_turkish(product_name.lower().strip())
        search_name = search_name.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
        search_words = search_name.split()
        
        best_matches = []
        exact_matches = []
        variant_matches = []
        candidates = []
        
        # Separate size/color words from product words
        size_color_words = ['s', 'm', 'l', 'xl', 'xs', 'small', 'medium', 'large', 
                           'turuncu', 'siyah', 'beyaz', 'mavi', 'kirmizi', 'yesil', 
                           'orange', 'black', 'white', 'blue', 'red', 'green']
        
        variant_words = [word for word in search_words if word in size_color_words]
        product_words = [word for word in search_words if word not in size_color_words]
        
        # Check if this is a size/color specific query
        is_size_color_query = len(variant_words) > 0 and len(search_words) <= 4
        
        # İlk geçiş: Variant alanında beden/renk araması
        if is_size_color_query:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                variant_elem = product.find('ProductVariant')
                
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    normalized_product_name = normalize_turkish(xml_product_name.lower())
                    
                    # If there are product words, check if they match the product name
                    product_name_matches = True
                    if product_words:
                        product_name_matches = all(word in normalized_product_name for word in product_words)
                    
                    # Only proceed if product name matches (or no product context)
                    if product_name_matches:
                        # Variant field check
                        if variant_elem is not None and variant_elem.text:
                            variant_text = normalize_turkish(variant_elem.text.lower().replace('-', ' '))
                            
                            # Check if all variant words are in variant field
                            if all(word in variant_text for word in variant_words):
                                variant_matches.append((product, xml_product_name, variant_text))
            
            if variant_matches:
                candidates = variant_matches
            else:
                # Fallback to normal product name search
                is_size_color_query = False
        
        # İkinci geçiş: Normal ürün adı tam eşleşmeleri (variant match yoksa)
        if not is_size_color_query or not candidates:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    normalized_xml = normalize_turkish(xml_product_name.lower())
                    normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
                    xml_words = normalized_xml.split()
                    
                    # Tam eşleşme kontrolü - ilk iki kelime tam aynı olmalı
                    if len(search_words) >= 2 and len(xml_words) >= 2:
                        search_key = f"{search_words[0]} {search_words[1]}"
                        xml_key = f"{xml_words[0]} {xml_words[1]}"
                        
                        if search_key == xml_key:
                            exact_matches.append((product, xml_product_name, normalized_xml))
            
            # Eğer variant match varsa onu kullan, yoksa exact matches kullan
            if not candidates:
                candidates = exact_matches if exact_matches else []
        
        # Eğer hala bir match yoksa, fuzzy matching yap
        if not candidates:
            for product in root.findall('Product'):
                product_name_elem = product.find('ProductName')
                if product_name_elem is not None and product_name_elem.text:
                    xml_product_name = product_name_elem.text.strip()
                    normalized_xml = normalize_turkish(xml_product_name.lower())
                    normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
                    xml_words = normalized_xml.split()
                    
                    # Ortak kelime sayısını hesapla
                    common_words = set(search_words) & set(xml_words)
                    
                    # En az 2 ortak kelime olmalı VE ilk kelime aynı olmalı (marka kontrolü)
                    if (len(common_words) >= 2 and 
                        len(search_words) > 0 and len(xml_words) > 0 and 
                        search_words[0] == xml_words[0]):
                        best_matches.append((product, xml_product_name, normalized_xml, len(common_words)))
            
            # En çok ortak kelimeye sahip olanları seç
            if best_matches:
                max_common = max(match[3] for match in best_matches)
                candidates = [(match[0], match[1], match[2]) for match in best_matches if match[3] == max_common]
        
        # Stok bilgilerini topla ve tekrarları önle
        warehouse_stock_map = {}  # warehouse_name -> total_stock
        
        for product, xml_name, _ in candidates:
            # New B2B API structure: Warehouse elements are direct children of Product
            for warehouse in product.findall('Warehouse'):
                name_elem = warehouse.find('Name')
                stock_elem = warehouse.find('Stock')
                
                if name_elem is not None and stock_elem is not None:
                    warehouse_name = name_elem.text if name_elem.text else "Bilinmeyen"
                    try:
                        stock_count = int(stock_elem.text) if stock_elem.text else 0
                        if stock_count > 0:
                            # Aynı mağaza için stokları topla
                            if warehouse_name in warehouse_stock_map:
                                warehouse_stock_map[warehouse_name] += stock_count
                            else:
                                warehouse_stock_map[warehouse_name] = stock_count
                    except (ValueError, TypeError):
                        pass
        
        if warehouse_stock_map:
            # Mağaza stoklarını liste halinde döndür
            all_warehouse_info = []
            for warehouse_name, total_stock in warehouse_stock_map.items():
                all_warehouse_info.append(f"{warehouse_name}: Stokta var")
            return all_warehouse_info
        else:
            return ["Hiçbir mağazada stokta bulunmuyor"]
        
    except Exception as e:
        print(f"Mağaza stok bilgisi çekme hatası: {e}")
        return None

# Trek bisiklet ürünlerini çekme - DÜZELTİLMİŞ VERSİYON
try:
    # All XML debug prints disabled to reduce noise
    url = 'https://www.trekbisiklet.com.tr/output/8582384479'
    response = requests.get(url, verify=False, timeout=10)
    
    # XML parsing - all debug prints disabled
    content_preview = response.content[:500].decode('utf-8', errors='ignore')
    root = ET.fromstring(response.content)
    all_items = root.findall('item')
    
    # Item analysis disabled for production
    
    # Marlin arama testi
    marlin_count = 0
    products = []
    
    for item in all_items:
        # Değişkenleri önceden tanımla
        stock_number = 0
        stock_amount = "stokta değil"
        price = ""
        price_eft = ""
        product_link = ""
        
        rootlabel = item.find('rootlabel')
        if rootlabel is None or not rootlabel.text:
            continue
            
        full_name = rootlabel.text.strip()
        name_words = full_name.lower().split()
        name = name_words[0] if name_words else "unknown"
        
        # STOK KONTROLÜ - SAYISAL KARŞILAŞTIRMA
        stock_element = item.find('stockAmount')
        if stock_element is not None and stock_element.text:
            try:
                stock_number = int(stock_element.text.strip())
                stock_amount = "stokta" if stock_number > 0 else "stokta değil"
            except (ValueError, TypeError):
                stock_number = 0
                stock_amount = "stokta değil"
        
        # Marlin kontrolü
        if 'marlin' in full_name.lower():
            marlin_count += 1
            pass
        
        # Stokta olan ürünler için fiyat bilgilerini al
        if stock_amount == "stokta":
            # Normal fiyat
            price_element = item.find('priceTaxWithCur')
            price_str = price_element.text if price_element is not None and price_element.text else "0"
            
            # Kampanya fiyatı
            price_rebate_element = item.find('priceRebateWithTax')
            price_rebate_str = price_rebate_element.text if price_rebate_element is not None and price_rebate_element.text else ""
            
            # Kampanya fiyatı varsa onu kullan, yoksa normal fiyatı kullan
            final_price_str = price_str
            if price_rebate_str:
                try:
                    normal_price = float(price_str)
                    rebate_price = float(price_rebate_str)
                    # Kampanya fiyatı normal fiyattan farklı ve düşükse kullan
                    if rebate_price < normal_price:
                        final_price_str = price_rebate_str
                except (ValueError, TypeError):
                    final_price_str = price_str
            
            # EFT fiyatı
            price_eft_element = item.find('priceEft')
            price_eft_str = price_eft_element.text if price_eft_element is not None and price_eft_element.text else ""
            
            # Ürün linki
            link_element = item.find('productLink')
            product_link = link_element.text if link_element is not None and link_element.text else ""
            
            # Fiyat formatting (kampanya fiyatı veya normal fiyat)
            try:
                price_float = float(final_price_str)
                if price_float > 200000:
                    price = str(round(price_float / 5000) * 5000)
                elif price_float > 30000:
                    price = str(round(price_float / 1000) * 1000)
                elif price_float > 10000:
                    price = str(round(price_float / 100) * 100)
                else:
                    price = str(round(price_float / 10) * 10)
            except (ValueError, TypeError):
                price = final_price_str
            
            # EFT fiyat formatting
            if price_eft_str:
                try:
                    price_eft_float = float(price_eft_str)
                    if price_eft_float > 200000:
                        price_eft = str(round(price_eft_float / 5000) * 5000)
                    elif price_eft_float > 30000:
                        price_eft = str(round(price_eft_float / 1000) * 1000)
                    elif price_eft_float > 10000:
                        price_eft = str(round(price_eft_float / 100) * 100)
                    else:
                        price_eft = str(round(price_eft_float / 10) * 10)
                except (ValueError, TypeError):
                    price_eft = price_eft_str
            else:
                try:
                    price_eft_float = float(price_str)
                    price_eft = str(round(price_eft_float * 0.975 / 10) * 10)
                except:
                    price_eft = ""
        
        # Ürün bilgilerini tuple olarak oluştur
        item_info = (stock_amount, price, product_link, price_eft, str(stock_number))
        products.append((name, item_info, full_name))
    
    # Summary disabled for production
    
    # Initialize improved WhatsApp chatbot for BF space
    global improved_whatsapp_bot
    improved_whatsapp_bot = None
    if USE_IMPROVED_SEARCH:
        try:
            improved_whatsapp_bot = WhatsAppImprovedChatbot(products)
            # print("✅ BF Space: Improved WhatsApp product search initialized successfully")
        except Exception as e:
            logger.error(f"BF Space: Failed to initialize improved WhatsApp search: {e}")
            USE_IMPROVED_SEARCH = False
            improved_whatsapp_bot = None
    
    # Enhanced features kaldırıldı - GPT-4 doğal dil anlama kullanacak
    # print("✅ Basit sistem aktif - GPT-4 doğal dil anlama")
    
    # Marlin debug reports disabled for production
    if marlin_count == 0:
        pass  # No Marlin products found
    else:
        # Marlin stok raporu
        marlin_products = [p for p in products if 'marlin' in p[2].lower()]
        marlin_in_stock = [p for p in marlin_products if p[1][0] == "stokta"]
        marlin_out_of_stock = [p for p in marlin_products if p[1][0] == "stokta değil"]
        
        # Product lists disabled for production
        pass

except Exception as e:
    logger.error(f"Ürün yükleme hatası: {e}")
    import traceback
    traceback.print_exc()
    products = []

# ===============================
# STOK API ENTEGRASYONU
# ===============================

STOCK_API_BASE = "https://video.trek-turkey.com/bizimhesap-proxy.php"

# Stock cache (5 dakikalık cache)
stock_cache = {}
CACHE_DURATION = 300  # 5 dakika (saniye cinsinden)

def normalize_turkish(text):
    """Türkçe karakterleri normalize et"""
    if not text:
        return ""
    replacements = {
        'ı': 'i', 'İ': 'i', 'ş': 's', 'Ş': 's',
        'ğ': 'g', 'Ğ': 'g', 'ü': 'u', 'Ü': 'u',
        'ö': 'o', 'Ö': 'o', 'ç': 'c', 'Ç': 'c'
    }
    text = text.lower()
    for tr_char, eng_char in replacements.items():
        text = text.replace(tr_char, eng_char)
    return text

def fetch_warehouse_inventory(warehouse, product_name, search_terms):
    """Tek bir mağazanın stok bilgisini al"""
    try:
        warehouse_id = warehouse['id']
        warehouse_name = warehouse['title']
        
        # DSW'yi ayrı tut (gelecek stok için)
        is_dsw = 'DSW' in warehouse_name or 'ÖN SİPARİŞ' in warehouse_name.upper()
        
        # Mağaza stoklarını al
        inventory_url = f"{STOCK_API_BASE}?action=inventory&warehouse={warehouse_id}&endpoint=inventory/{warehouse_id}"
        inventory_response = requests.get(inventory_url, timeout=3, verify=False)
        
        if inventory_response.status_code != 200:
            return None
            
        inventory_data = inventory_response.json()
        
        # API yanıtını kontrol et
        if 'data' not in inventory_data or 'inventory' not in inventory_data['data']:
            return None
        
        products = inventory_data['data']['inventory']
        
        # Beden terimleri kontrolü
        size_terms = ['xs', 's', 'm', 'ml', 'l', 'xl', 'xxl', '2xl', '3xl', 'small', 'medium', 'large']
        size_numbers = ['44', '46', '48', '50', '52', '54', '56', '58', '60']
        
        # Arama terimlerinde beden var mı kontrol et
        has_size_query = False
        size_query = None
        for term in search_terms:
            if term in size_terms or term in size_numbers:
                has_size_query = True
                size_query = term
                break
        
        # Eğer sadece beden sorgusu varsa (ör: "m", "xl")
        is_only_size_query = len(search_terms) == 1 and has_size_query
        
        # Ürünü ara
        warehouse_variants = []
        dsw_stock_count = 0
        
        for product in products:
            product_title = normalize_turkish(product.get('title', '')).lower()
            original_title = product.get('title', '')
            
            # Eğer sadece beden sorgusu ise
            if is_only_size_query:
                # Beden terimini ürün başlığında ara (parantez içinde veya dışında)
                if size_query in product_title.split() or f'({size_query})' in product_title or f' {size_query} ' in product_title or product_title.endswith(f' {size_query}'):
                    qty = int(product.get('qty', 0))
                    stock = int(product.get('stock', 0))
                    actual_stock = max(qty, stock)
                    
                    if actual_stock > 0:
                        if is_dsw:
                            dsw_stock_count += actual_stock
                            continue
                        warehouse_variants.append(f"{original_title}: ✓ Stokta")
            else:
                # Normal ürün araması - tüm terimler eşleşmeli
                # Ama beden terimi varsa özel kontrol yap
                if has_size_query:
                    # Beden hariç diğer terimleri kontrol et
                    non_size_terms = [t for t in search_terms if t != size_query]
                    product_matches = all(term in product_title for term in non_size_terms)
                    
                    # Beden kontrolü - daha esnek
                    size_matches = size_query in product_title.split() or f'({size_query})' in product_title or f' {size_query} ' in product_title or product_title.endswith(f' {size_query}')
                    
                    if product_matches and size_matches:
                        qty = int(product.get('qty', 0))
                        stock = int(product.get('stock', 0))
                        actual_stock = max(qty, stock)
                        
                        if actual_stock > 0:
                            if is_dsw:
                                dsw_stock_count += actual_stock
                                continue
                            
                            # Varyant bilgisini göster
                            variant_info = original_title
                            possible_names = [
                                product_name.upper(), 
                                product_name.lower(), 
                                product_name.title(),
                                product_name.upper().replace('I', 'İ'),
                                product_name.upper().replace('İ', 'I'),
                            ]
                            
                            if 'fx sport' in product_name.lower():
                                possible_names.extend(['FX Sport AL 3', 'FX SPORT AL 3', 'Fx Sport Al 3'])
                            
                            for possible_name in possible_names:
                                variant_info = variant_info.replace(possible_name, '').strip()
                            
                            variant_info = ' '.join(variant_info.split())
                            
                            if variant_info and variant_info != original_title:
                                warehouse_variants.append(f"{variant_info}: ✓ Stokta")
                            else:
                                warehouse_variants.append(f"{original_title}: ✓ Stokta")
                else:
                    # Beden sorgusu yoksa normal kontrol
                    if all(term in product_title for term in search_terms):
                        qty = int(product.get('qty', 0))
                        stock = int(product.get('stock', 0))
                        actual_stock = max(qty, stock)
                        
                        if actual_stock > 0:
                            if is_dsw:
                                dsw_stock_count += actual_stock
                                continue
                            
                            variant_info = original_title
                            possible_names = [
                                product_name.upper(), 
                                product_name.lower(), 
                                product_name.title(),
                                product_name.upper().replace('I', 'İ'),
                                product_name.upper().replace('İ', 'I'),
                            ]
                            
                            if 'fx sport' in product_name.lower():
                                possible_names.extend(['FX Sport AL 3', 'FX SPORT AL 3', 'Fx Sport Al 3'])
                            
                            for possible_name in possible_names:
                                variant_info = variant_info.replace(possible_name, '').strip()
                            
                            variant_info = ' '.join(variant_info.split())
                            
                            if variant_info and variant_info != original_title:
                                warehouse_variants.append(f"{variant_info}: ✓ Stokta")
                            else:
                                warehouse_variants.append(f"{original_title}: ✓ Stokta")
        
        # Sonuç döndür
        if warehouse_variants and not is_dsw:
            return {'warehouse': warehouse_name, 'variants': warehouse_variants, 'is_dsw': False}
        elif dsw_stock_count > 0:
            return {'dsw_stock': dsw_stock_count, 'is_dsw': True}
        
        return None
        
    except Exception:
        return None

def get_realtime_stock_parallel(product_name):
    """API'den gerçek zamanlı stok bilgisini çek - Paralel versiyon with cache"""
    try:
        # Cache kontrolü
        cache_key = normalize_turkish(product_name).lower()
        current_time = time.time()
        
        if cache_key in stock_cache:
            cached_data, cached_time = stock_cache[cache_key]
            # Cache hala geçerli mi?
            if current_time - cached_time < CACHE_DURATION:
                logger.info(f"Cache'den döndürülüyor: {product_name}")
                return cached_data
        
        # Önce mağaza listesini al
        warehouses_url = f"{STOCK_API_BASE}?action=warehouses&endpoint=warehouses"
        warehouses_response = requests.get(warehouses_url, timeout=3, verify=False)
        
        if warehouses_response.status_code != 200:
            logger.error(f"Mağaza listesi alınamadı: {warehouses_response.status_code}")
            return None
            
        warehouses_data = warehouses_response.json()
        
        # API yanıtını kontrol et
        if 'data' not in warehouses_data or 'warehouses' not in warehouses_data['data']:
            logger.error("Mağaza verisi bulunamadı")
            return None
        
        warehouses = warehouses_data['data']['warehouses']
        
        # Ürün adını normalize et
        search_terms = normalize_turkish(product_name).lower().split()
        logger.info(f"Aranan ürün: {product_name} -> {search_terms}")
        
        stock_info = {}
        total_dsw_stock = 0
        total_stock = 0
        
        # Paralel olarak tüm mağazaları sorgula
        with ThreadPoolExecutor(max_workers=10) as executor:
            # Tüm mağazalar için görev oluştur
            futures = {
                executor.submit(fetch_warehouse_inventory, warehouse, product_name, search_terms): warehouse 
                for warehouse in warehouses
            }
            
            # Sonuçları topla
            for future in as_completed(futures):
                result = future.result()
                if result:
                    if result.get('is_dsw'):
                        total_dsw_stock += result.get('dsw_stock', 0)
                    else:
                        warehouse_name = result['warehouse']
                        stock_info[warehouse_name] = result['variants']
                        total_stock += 1  # En az bir mağazada var
        
        # Sonucu oluştur
        if not stock_info:
            # Mağazada yok ama DSW'de varsa
            if total_dsw_stock > 0:
                result = f"{product_name}: Şu anda mağazalarda stokta yok, ancak yakında gelecek. Ön sipariş verebilirsiniz."
            else:
                result = f"{product_name}: Şu anda hiçbir mağazada stokta bulunmuyor."
        else:
            # Minimal prompt oluştur - varyant detaylarıyla
            prompt_lines = [f"{product_name} stok durumu:"]
            for warehouse, variants in stock_info.items():
                if isinstance(variants, list):
                    prompt_lines.append(f"- {warehouse}:")
                    for variant in variants:
                        prompt_lines.append(f"  • {variant}")
                else:
                    prompt_lines.append(f"- {warehouse}: {variants}")
            
            # Güvenlik: Toplam adet bilgisi gösterme
            if total_stock > 0:
                prompt_lines.append(f"✓ Ürün stokta mevcut")
            
            result = "\n".join(prompt_lines)
        
        # Sonucu cache'e kaydet
        stock_cache[cache_key] = (result, current_time)
        
        return result
    
    except Exception as e:
        logger.error(f"API hatası: {e}")
        return None

def is_stock_query(message):
    """Mesajın stok sorgusu olup olmadığını kontrol et"""
    stock_keywords = ['stok', 'stock', 'var mı', 'mevcut mu', 'kaç adet', 
                      'kaç tane', 'bulunuyor mu', 'hangi mağaza', 
                      'nerede var', 'beden', 'numara']
    message_lower = message.lower()
    return any(keyword in message_lower for keyword in stock_keywords)

# Sistem mesajları - Modüler prompts'tan yükle
def get_system_messages():
    return get_prompt_content_only()  # prompts.py'dan yükle

# ===============================
# SOHBET HAFIZASI SİSTEMİ
# ===============================

# Sohbet hafızası için basit bir dictionary
conversation_memory = {}

def get_conversation_context(phone_number):
    """Kullanıcının sohbet geçmişini getir"""
    if phone_number not in conversation_memory:
        conversation_memory[phone_number] = {
            "messages": [],
            "current_category": None,
            "last_activity": None
        }
    return conversation_memory[phone_number]

def add_to_conversation(phone_number, user_message, ai_response):
    """Sohbet geçmişine ekle"""
    import datetime
    
    context = get_conversation_context(phone_number)
    context["last_activity"] = datetime.datetime.now()
    
    context["messages"].append({
        "user": user_message,
        "ai": ai_response,
        "timestamp": datetime.datetime.now()
    })
    
    # Sadece son 10 mesajı tut
    if len(context["messages"]) > 10:
        context["messages"] = context["messages"][-10:]
    
    detect_category(phone_number, user_message, ai_response)

def detect_category(phone_number, user_message, ai_response):
    """Konuşulan kategoriyi tespit et"""
    context = get_conversation_context(phone_number)
    
    categories = {
        "marlin": ["marlin", "marlin+"],
        "madone": ["madone"],
        "emonda": ["emonda", "émonda"],
        "domane": ["domane"],
        "checkpoint": ["checkpoint"],
        "fuel": ["fuel", "fuel ex", "fuel exe"],
        "procaliber": ["procaliber"],
        "supercaliber": ["supercaliber"],
        "fx": ["fx"],
        "ds": ["ds", "dual sport"],
        "powerfly": ["powerfly"],
        "rail": ["rail"],
        "verve": ["verve"],
        "townie": ["townie"]
    }
    
    user_lower = user_message.lower()
    for category, keywords in categories.items():
        for keyword in keywords:
            if keyword in user_lower:
                context["current_category"] = category
                return category
    
    return context.get("current_category")

def build_context_messages(phone_number, current_message):
    """Sohbet geçmişi ile sistem mesajlarını oluştur"""
    context = get_conversation_context(phone_number)
    system_messages = get_system_messages()
    
    # Mevcut kategori varsa, sistem mesajına ekle
    if context.get("current_category"):
        category_msg = f"Kullanıcı şu anda {context['current_category'].upper()} kategorisi hakkında konuşuyor. Tüm cevaplarını bu kategori bağlamında ver. Kullanıcı yeni bir kategori belirtmediği sürece {context['current_category']} hakkında bilgi vermek istediğini varsay."
        system_messages.append({"role": "system", "content": category_msg})
    
    # Son 3 mesaj alışverişini ekle
    recent_messages = context["messages"][-3:] if context["messages"] else []
    
    all_messages = system_messages.copy()
    
    # Geçmiş mesajları ekle
    for msg in recent_messages:
        all_messages.append({"role": "user", "content": msg["user"]})
        all_messages.append({"role": "assistant", "content": msg["ai"]})
    
    # Mevcut mesajı ekle
    all_messages.append({"role": "user", "content": current_message})
    
    return all_messages

def process_whatsapp_message_with_media(user_message, phone_number, media_urls, media_types):
    """Medya içeriği olan WhatsApp mesajı işleme - GPT-5 Vision ile"""
    try:
        logger.info(f"🖼️ Medya analizi başlıyor: {len(media_urls)} medya")
        
        # Pasif profil analizi
        profile_analysis = analyze_user_message(phone_number, user_message)
        logger.info(f"📊 Profil analizi: {phone_number} -> {profile_analysis}")
        
        # Sohbet geçmişi ile sistem mesajlarını oluştur
        messages = build_context_messages(phone_number, user_message if user_message else "Gönderilen görseli analiz et")
        
        # GPT-5 Vision için mesaj hazırla
        vision_message = {
            "role": "user",
            "content": []
        }
        
        # Metin mesajı varsa ekle
        if user_message and user_message.strip():
            vision_message["content"].append({
                "type": "text",
                "text": user_message
            })
        else:
            vision_message["content"].append({
                "type": "text",
                "text": "Bu görselde ne var? Detaylı açıkla."
            })
        
        # Medya URL'lerini ekle (Twilio medya URL'leri için proxy kullan)
        for i, media_url in enumerate(media_urls):
            media_type = media_types[i] if i < len(media_types) else "image/jpeg"
            
            # Sadece görsel medyaları işle
            if media_type and media_type.startswith('image/'):
                # Twilio medya URL'sini proxy üzerinden çevir
                if 'api.twilio.com' in media_url:
                    # URL'den message SID ve media SID'yi çıkar
                    import re
                    match = re.search(r'/Messages/([^/]+)/Media/([^/]+)', media_url)
                    if match:
                        message_sid = match.group(1)
                        media_sid = match.group(2)
                        # Proxy URL'sini oluştur
                        proxy_url = f"https://video.trek-turkey.com/twilio-media-proxy.php?action=media&message={message_sid}&media={media_sid}"
                        logger.info(f"🔄 Proxy URL: {proxy_url}")
                        
                        vision_message["content"].append({
                            "type": "image_url",
                            "image_url": {
                                "url": proxy_url
                            }
                        })
                else:
                    # Diğer URL'leri doğrudan kullan
                    vision_message["content"].append({
                        "type": "image_url",
                        "image_url": {
                            "url": media_url
                        }
                    })
        
        # Son user mesajını vision mesajıyla değiştir
        messages = [msg for msg in messages if msg.get("role") != "user" or msg != messages[-1]]
        messages.append(vision_message)
        
        # Sistem mesajına bisiklet tanıma talimatı ekle
        messages.insert(0, {
            "role": "system",
            "content": "Gönderilen görsellerde bisiklet veya bisiklet parçaları varsa, bunları detaylıca tanımla. Marka, model, renk, özellikler gibi detayları belirt. Eğer Trek bisiklet ise modeli tahmin etmeye çalış. Stok durumu sorulursa, görseldeki bisikletin özelliklerini belirterek stok kontrolü yapılması gerektiğini söyle."
        })
        
        if not OPENAI_API_KEY:
            return "OpenAI API anahtarı eksik. Lütfen environment variables'ları kontrol edin."
        
        logger.info(f"📤 GPT-5 Vision'a gönderiliyor: {len(messages)} mesaj")
        
        payload = {
            "model": "gpt-5-chat-latest",
            "messages": messages,
            "temperature": 0,  # Deterministik cevaplar için
            "max_tokens": 800,
            "stream": False,
            "top_p": 0.1,  # Daha tutarlı cevaplar için düşük değer
            "frequency_penalty": 0.1,  # Tekrarları azaltmak için
            "presence_penalty": 0  # Yeni konulara açık olması için
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }
        
        response = requests.post(API_URL, headers=headers, json=payload)
        if response.status_code == 200:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']
            
            # WhatsApp için formatla
            formatted_response = extract_product_info_whatsapp(ai_response)
            
            # Sohbet geçmişine ekle
            add_to_conversation(phone_number, f"[Görsel gönderildi] {user_message if user_message else ''}", formatted_response)
            
            return formatted_response
        else:
            logger.error(f"OpenAI API Error: {response.status_code} - {response.text}")
            return f"Görsel analizi başarısız oldu. Lütfen tekrar deneyin."
            
    except Exception as e:
        logger.error(f"❌ Medya işleme hatası: {e}")
        import traceback
        traceback.print_exc()
        return "Görsel işlenirken bir hata oluştu. Lütfen tekrar deneyin."

def process_whatsapp_message_with_memory(user_message, phone_number):
    """Hafızalı WhatsApp mesaj işleme"""
    try:
        # 🔔 Yeni Mağaza Bildirim Sistemi - Mehmet Bey'e otomatik bildirim
        if USE_STORE_NOTIFICATION:
            # Önce basit keyword kontrolü yap
            should_notify_mehmet, notification_reason, urgency = should_notify_mehmet_bey(user_message)
            
            # Eğer keyword'le yakalanmadıysa ve Intent Analyzer varsa, onu da kontrol et
            if not should_notify_mehmet and USE_INTENT_ANALYZER:
                context = get_conversation_context(phone_number)
                intent_analysis = analyze_customer_intent(user_message, context)
                should_notify_mehmet, notification_reason, urgency = should_notify_mehmet_bey(user_message, intent_analysis)
            else:
                intent_analysis = None
            
            if should_notify_mehmet:
                # Ürün bilgisini belirle
                if intent_analysis:
                    product = intent_analysis.get("product") or "Belirtilmemiş"
                else:
                    # Basit keyword'den ürün çıkar
                    context = get_conversation_context(phone_number)
                    product = context.get("current_category") or "Ürün belirtilmemiş"
                
                # Bildirim tipini belirle
                if "rezervasyon" in notification_reason.lower() or urgency == "high":
                    action = "reserve"
                elif "mağaza" in notification_reason.lower() or "lokasyon" in notification_reason.lower():
                    action = "info"
                elif "fiyat" in notification_reason.lower() or "ödeme" in notification_reason.lower():
                    action = "price"
                else:
                    action = "info"
                
                # Detaylı bilgi mesajı
                additional_info = f"{notification_reason}\n\nMüşteri Mesajı: '{user_message}'"
                if urgency == "high":
                    additional_info = "⚠️ YÜKSEK ÖNCELİK ⚠️\n" + additional_info
                
                # Bildirim gönder
                result = send_store_notification(
                    customer_phone=phone_number,
                    customer_name=None,
                    product_name=product,
                    action=action,
                    store_name=None,
                    additional_info=additional_info
                )
                
                if result:
                    logger.info(f"✅ Mehmet Bey'e bildirim gönderildi!")
                    logger.info(f"   📍 Sebep: {notification_reason}")
                    logger.info(f"   ⚡ Öncelik: {urgency}")
                    logger.info(f"   📦 Ürün: {product}")
                else:
                    logger.error("❌ Mehmet Bey'e bildirim gönderilemedi")
        
        
        # 🧠 Pasif profil analizi - kullanıcı mesajını analiz et
        profile_analysis = analyze_user_message(phone_number, user_message)
        logger.info(f"📊 Profil analizi: {phone_number} -> {profile_analysis}")
        
        # 🎯 Kişiselleştirilmiş öneriler kontrolü
        if any(keyword in user_message.lower() for keyword in ["öneri", "öner", "tavsiye", "ne önerirsin"]):
            personalized = get_personalized_recommendations(phone_number, products)
            if personalized.get("personalized") and personalized.get("recommendations"):
                # Kullanıcı profiline göre özelleştirilmiş cevap hazırla
                profile_summary = get_user_profile_summary(phone_number)
                custom_response = create_personalized_response(personalized, profile_summary)
                return extract_product_info_whatsapp(custom_response)
        
        # Enhanced features kaldırıldı - GPT-4 doğal dil anlama kullanacak
        
        # Sohbet geçmişi ile sistem mesajlarını oluştur
        messages = build_context_messages(phone_number, user_message)
        
        # 🎯 Profil bilgilerini sistem mesajlarına ekle
        profile_summary = get_user_profile_summary(phone_number)
        if profile_summary.get("exists") and profile_summary.get("confidence", 0) > 0.3:
            profile_context = create_profile_context_message(profile_summary)
            messages.append({"role": "system", "content": profile_context})
        
        # 🔍 BF Space: Use improved product search if available
        product_found_improved = False
        if USE_IMPROVED_SEARCH and improved_whatsapp_bot:
            try:
                product_result = improved_whatsapp_bot.process_message(user_message)
                if product_result['is_product_query'] and product_result['response']:
                    # Check if user is asking about specific warehouse/store location
                    if any(keyword in user_message.lower() for keyword in ['mağaza', 'mağazada', 'nerede', 'hangi mağaza', 'şube']):
                        # First, always search for products using improved search
                        # This will find products even with partial/typo names
                        warehouse_info_parts = []
                        
                        # Use the response text from improved search to extract product names
                        if product_result['response']:
                            # Extract product names from the response
                            import re
                            # Look for product names in bold (between * markers)
                            product_names = re.findall(r'\*([^*]+)\*', product_result['response'])
                            
                            if product_names:
                                for product_name in product_names[:3]:  # Max 3 products
                                    # Clean up the product name
                                    product_name = product_name.strip()
                                    
                                    # Remove numbering like "1." "2." from the beginning
                                    import re
                                    product_name = re.sub(r'^\d+\.\s*', '', product_name)
                                    
                                    # Skip status indicators
                                    if product_name in ['Stokta mevcut', 'Stokta yok', 'Fiyat:', 'Kampanya:', 'İndirim:', 'Birden fazla ürün buldum:']:
                                        continue
                                    
                                    warehouse_stock = get_warehouse_stock(product_name)
                                    
                                    if warehouse_stock and warehouse_stock != ['Ürün bulunamadı'] and warehouse_stock != ['Hiçbir mağazada stokta bulunmuyor']:
                                        warehouse_info_parts.append(f"{product_name} mağaza stogu:")
                                        warehouse_info_parts.extend(warehouse_stock)
                                        warehouse_info_parts.append("")
                                        break  # Found warehouse info, stop searching
                        
                        # If still no warehouse info, use products_found as backup
                        if not warehouse_info_parts and product_result['products_found']:
                            for product in product_result['products_found'][:2]:
                                product_name = product[2]  # Full product name
                                warehouse_stock = get_warehouse_stock(product_name)
                                
                                if warehouse_stock and warehouse_stock != ['Ürün bulunamadı'] and warehouse_stock != ['Hiçbir mağazada stokta bulunmuyor']:
                                    warehouse_info_parts.append(f"{product_name} mağaza stogu:")
                                    warehouse_info_parts.extend(warehouse_stock)
                                    warehouse_info_parts.append("")
                                    break
                        
                        if warehouse_info_parts:
                            warehouse_response = "\n".join(warehouse_info_parts)
                            messages.append({
                                "role": "system",
                                "content": f"MAĞAZA STOK BİLGİSİ (BF Space):\n{warehouse_response}\n\nSADECE bu bilgileri kullanarak kullanıcıya yardımcı ol."
                            })
                            product_found_improved = True
                            logger.info("✅ BF Space: Warehouse stock info used")
                    
                    if not product_found_improved:
                        # Use improved search response directly
                        messages.append({
                            "role": "system",
                            "content": f"ÜRÜN BİLGİSİ (BF Space):\n{product_result['response']}\n\nSADECE bu bilgileri kullanarak kullanıcıya yardımcı ol. Bu bilgiler dışında ek bilgi ekleme."
                        })
                        product_found_improved = True
                        logger.info("✅ BF Space: Improved product search used")
            except Exception as e:
                logger.error(f"❌ BF Space: Improved search error: {e}")
        
        # Fallback to warehouse search if improved search didn't work
        if not product_found_improved:
            # Check if message seems to be asking about products
            product_keywords = ['fiyat', 'kaç', 'stok', 'var mı', 'mevcut', 'bisiklet', 'bike', 
                              'trek', 'model', 'beden', 'renk', 'mağaza', 'nerede', 'hangi']
            
            # Common non-product responses
            non_product_responses = ['süper', 'harika', 'güzel', 'teşekkür', 'tamam', 'olur',
                                    'evet', 'hayır', 'peki', 'anladım', 'tamamdır']
            
            is_product_query = False
            lower_message = user_message.lower()
            
            # Check if it's likely a product query
            if any(keyword in lower_message for keyword in product_keywords):
                is_product_query = True
            # Check if it's NOT a simple response
            elif lower_message not in non_product_responses and len(lower_message.split()) > 1:
                # Multi-word queries might be product searches
                is_product_query = True
            # Single short words are usually not products
            elif len(lower_message.split()) == 1 and len(lower_message) < 6:
                is_product_query = False
            
            if is_product_query:
                # Use GPT-5 warehouse search for product queries
                logger.info("📦 Using GPT-5 warehouse search")
                warehouse_result = get_warehouse_stock(user_message)
                if warehouse_result and warehouse_result != ['Ürün bulunamadı']:
                    warehouse_response = "\n".join(warehouse_result)
                    messages.append({
                        "role": "system",
                        "content": f"MAĞAZA STOK BİLGİSİ:\n{warehouse_response}\n\nBu bilgileri kullanarak kullanıcıya yardımcı ol. Fiyat ve stok bilgilerini AYNEN kullan."
                    })
                    logger.info(f"✅ Warehouse stock info added: {warehouse_response[:200]}...")
            else:
                logger.info(f"🚫 Skipping product search for: '{user_message}'")

        if not OPENAI_API_KEY:
            return "OpenAI API anahtarı eksik. Lütfen environment variables'ları kontrol edin."

        # Debug: Log what we're sending to GPT
        logger.info(f"📤 Sending to GPT-5: {len(messages)} messages")
        for i, msg in enumerate(messages):
            if msg.get('role') == 'system':
                content_preview = msg.get('content', '')[:500]
                if 'Fiyat:' in content_preview or 'TL' in content_preview:
                    logger.info(f"💰 System message with price info: {content_preview}")

        payload = {
            "model": "gpt-5-chat-latest",
            "messages": messages,
            "temperature": 0,  # Deterministik cevaplar için
            "max_tokens": 800,
            "stream": False,
            "top_p": 0.1,  # Daha tutarlı cevaplar için düşük değer
            "frequency_penalty": 0.1,  # Tekrarları azaltmak için
            "presence_penalty": 0  # Yeni konulara açık olması için
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }
        
        response = requests.post(API_URL, headers=headers, json=payload)
        if response.status_code == 200:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']
            
            # WhatsApp için resim URL'lerini formatla
            formatted_response = extract_product_info_whatsapp(ai_response)
            
            # Sohbet geçmişine ekle
            add_to_conversation(phone_number, user_message, formatted_response)
            
            return formatted_response
        else:
            print(f"OpenAI API Error: {response.status_code} - {response.text}")
            return f"API hatası: {response.status_code}. Lütfen daha sonra tekrar deneyin."
            
    except Exception as e:
        print(f"❌ WhatsApp mesaj işleme hatası: {e}")
        import traceback
        traceback.print_exc()
        logger.error(f"Detailed error: {str(e)}")
        logger.error(f"Error type: {type(e).__name__}")
        return "Teknik bir sorun oluştu. Lütfen daha sonra tekrar deneyin."

def create_profile_context_message(profile_summary):
    """Profil bilgilerini sistem mesajına çevir"""
    context_parts = []
    
    preferences = profile_summary.get("preferences", {})
    behavior = profile_summary.get("behavior", {})
    
    # Bütçe bilgisi
    if preferences.get("budget_min") and preferences.get("budget_max"):
        budget_min = preferences["budget_min"]
        budget_max = preferences["budget_max"]
        context_parts.append(f"Kullanıcının bütçesi: {budget_min:,}-{budget_max:,} TL")
    
    # Kategori tercihleri
    if preferences.get("categories"):
        categories = ", ".join(preferences["categories"])
        context_parts.append(f"İlgilendiği kategoriler: {categories}")
    
    # Kullanım amacı
    if preferences.get("usage_purpose"):
        purposes = ", ".join(preferences["usage_purpose"])
        context_parts.append(f"Kullanım amacı: {purposes}")
    
    # Davranış kalıpları
    if behavior.get("price_sensitive"):
        context_parts.append("Fiyata duyarlı bir kullanıcı")
    if behavior.get("tech_interested"):
        context_parts.append("Teknik detaylarla ilgilenen bir kullanıcı")
    if behavior.get("comparison_lover"):
        context_parts.append("Karşılaştırma yapmayı seven bir kullanıcı")
    
    # Etkileşim stili
    interaction_style = profile_summary.get("interaction_style", "balanced")
    style_descriptions = {
        "analytical": "Detaylı ve analitik bilgi bekleyen",
        "budget_conscious": "Bütçe odaklı ve ekonomik seçenekleri arayan",
        "technical": "Teknik özellikler ve spesifikasyonlarla ilgilenen",
        "decisive": "Hızlı karar veren ve özet bilgi isteyen",
        "balanced": "Dengeli yaklaşım sergileyen"
    }
    context_parts.append(f"{style_descriptions.get(interaction_style, 'balanced')} bir kullanıcı")
    
    if context_parts:
        return f"Kullanıcı profili: {'. '.join(context_parts)}. Bu bilgileri göz önünde bulundurarak cevap ver."
    return ""

def create_personalized_response(personalized_data, profile_summary):
    """Kişiselleştirilmiş öneri cevabı oluştur"""
    response_parts = []
    
    # Kullanıcı stiline göre selamlama
    interaction_style = profile_summary.get("interaction_style", "balanced")
    if interaction_style == "analytical":
        response_parts.append("🔍 Profilinizi analiz ederek sizin için en uygun seçenekleri belirledim:")
    elif interaction_style == "budget_conscious":
        response_parts.append("💰 Bütçenize uygun en iyi seçenekleri hazırladım:")
    elif interaction_style == "technical":
        response_parts.append("⚙️ Teknik tercihlerinize göre önerilerim:")
    else:
        response_parts.append("🎯 Size özel seçtiklerim:")
    
    # Önerileri listele
    recommendations = personalized_data.get("recommendations", [])[:3]  # İlk 3 öneri
    
    if recommendations:
        response_parts.append("\n")
        for i, product in enumerate(recommendations, 1):
            name, item_info, full_name = product
            price = item_info[1] if len(item_info) > 1 else "Fiyat yok"
            response_parts.append(f"**{i}. {full_name}**")
            response_parts.append(f"💰 Fiyat: {price} TL")
            response_parts.append("")
    
    # Profil bazlı açıklama
    preferences = profile_summary.get("preferences", {})
    if preferences.get("categories"):
        category = preferences["categories"][0]
        response_parts.append(f"Bu öneriler {category} kategorisindeki ilginizi ve tercihlerinizi dikkate alarak hazırlandı.")
    
    return "\n".join(response_parts)

def split_long_message(message, max_length=1600):
    """Uzun mesajları WhatsApp için uygun parçalara böler"""
    if len(message) <= max_length:
        return [message]
    
    parts = []
    remaining = message
    
    while len(remaining) > max_length:
        cut_point = max_length
        
        # Geriye doğru git ve uygun kesme noktası ara
        for i in range(max_length, max_length - 200, -1):
            if i < len(remaining) and remaining[i] in ['.', '!', '?', '\n']:
                cut_point = i + 1
                break
            elif i < len(remaining) and remaining[i] in [' ', ',', ';']:
                cut_point = i
        
        parts.append(remaining[:cut_point].strip())
        remaining = remaining[cut_point:].strip()
    
    if remaining:
        parts.append(remaining)
    
    return parts

# ===============================
# HAFIZA SİSTEMİ SONU
# ===============================

# WhatsApp mesajı işleme (eski fonksiyon - yedek için)
def process_whatsapp_message(user_message):
    try:
        system_messages = get_system_messages()
        
        # 🔍 BF Space: Use improved product search if available (backup function)
        product_found_improved = False
        if USE_IMPROVED_SEARCH and improved_whatsapp_bot:
            try:
                product_result = improved_whatsapp_bot.process_message(user_message)
                if product_result['is_product_query'] and product_result['response']:
                    # Check if user is asking about specific warehouse/store location
                    if any(keyword in user_message.lower() for keyword in ['mağaza', 'mağazada', 'nerede', 'hangi mağaza', 'şube']):
                        # Get warehouse stock info for the found products
                        if product_result['products_found']:
                            warehouse_info_parts = []
                            for product in product_result['products_found'][:2]:  # Max 2 products
                                product_name = product[2]  # Full product name
                                warehouse_stock = get_warehouse_stock(product_name)
                                if warehouse_stock:
                                    warehouse_info_parts.append(f"{product_name} mağaza stogu:")
                                    warehouse_info_parts.extend(warehouse_stock)
                                    warehouse_info_parts.append("")
                            
                            if warehouse_info_parts:
                                warehouse_response = "\n".join(warehouse_info_parts)
                                system_messages.append({
                                    "role": "system",
                                    "content": f"MAĞAZA STOK BİLGİSİ (BF Space Backup):\n{warehouse_response}\n\nSADECE bu bilgileri kullanarak kullanıcıya yardımcı ol."
                                })
                                product_found_improved = True
                    
                    if not product_found_improved:
                        system_messages.append({
                            "role": "system",
                            "content": f"ÜRÜN BİLGİSİ (BF Space Backup):\n{product_result['response']}\n\nSADECE bu bilgileri kullanarak kullanıcıya yardımcı ol. Bu bilgiler dışında ek bilgi ekleme."
                        })
                        product_found_improved = True
            except Exception as e:
                logger.error(f"BF Space backup: Improved search error: {e}")
        
        # Fallback to basic search
        if not product_found_improved:
            # Ürün bilgilerini kontrol et (basic search)
            input_words = user_message.lower().split()
            for product_info in products:
                if product_info[0] in input_words:
                    if product_info[1][0] == "stokta":
                        normal_price = f"Fiyat: {product_info[1][1]} TL"
                        if product_info[1][3]:
                            eft_price = f"Havale: {product_info[1][3]} TL"
                            price_info = f"{normal_price}, {eft_price}"
                        else:
                            price_info = normal_price
                        
                        new_msg = f"{product_info[2]} {product_info[1][0]} - {price_info}"
                    else:
                        new_msg = f"{product_info[2]} {product_info[1][0]}"
                    system_messages.append({"role": "system", "content": new_msg})
                    break

        messages = system_messages + [{"role": "user", "content": user_message}]

        if not OPENAI_API_KEY:
            return "OpenAI API anahtarı eksik. Lütfen environment variables'ları kontrol edin."

        payload = {
            "model": "gpt-5-chat-latest",
            "messages": messages,
            "temperature": 0,  # Deterministik cevaplar için
            "max_tokens": 800,
            "stream": False,
            "top_p": 0.1,  # Daha tutarlı cevaplar için düşük değer
            "frequency_penalty": 0.1,  # Tekrarları azaltmak için
            "presence_penalty": 0  # Yeni konulara açık olması için
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }
        
        response = requests.post(API_URL, headers=headers, json=payload)
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content']
        else:
            print(f"OpenAI API Error: {response.status_code} - {response.text}")
            return f"API hatası: {response.status_code}. Lütfen daha sonra tekrar deneyin."
            
    except Exception as e:
        print(f"❌ WhatsApp mesaj işleme hatası: {e}")
        import traceback
        traceback.print_exc()
        logger.error(f"Detailed error: {str(e)}")
        logger.error(f"Error type: {type(e).__name__}")
        return "Teknik bir sorun oluştu. Lütfen daha sonra tekrar deneyin."

# FastAPI uygulaması
app = FastAPI()

@app.post("/whatsapp-webhook")
async def whatsapp_webhook(request: Request):
    try:
        form_data = await request.form()
        
        from_number = form_data.get('From')
        to_number = form_data.get('To') 
        message_body = form_data.get('Body')
        message_status = form_data.get('MessageStatus')
        
        # Medya içeriği kontrolü
        num_media = form_data.get('NumMedia', '0')
        media_urls = []
        media_types = []
        
        # Medya varsa URL'leri topla
        if num_media and int(num_media) > 0:
            for i in range(int(num_media)):
                media_url = form_data.get(f'MediaUrl{i}')
                media_type = form_data.get(f'MediaContentType{i}')
                if media_url:
                    media_urls.append(media_url)
                    media_types.append(media_type)
                    logger.info(f"📸 Medya alındı: {media_type} - {media_url[:100]}...")
        
        print(f"📱 Webhook - From: {from_number}, Body: {message_body}, Status: {message_status}")
        
        # Durum güncellemelerini ignore et
        if message_status in ['sent', 'delivered', 'read', 'failed']:
            return {"status": "ignored", "message": f"Status: {message_status}"}
        
        # Giden mesajları ignore et
        if to_number != TWILIO_WHATSAPP_NUMBER:
            return {"status": "ignored", "message": "Outgoing message"}
        
        # Media Queue V2 İşleme
        if USE_MEDIA_QUEUE:
            if media_urls:
                # Medya mesajı geldi
                logger.info(f"📸 Media Queue V2: Medya alındı - {from_number}")
                
                # Media Queue'ya ekle ve bekleme mesajı al
                wait_message = media_queue.handle_media(
                    from_number,
                    media_urls,
                    media_types,
                    message_body or ""
                )
                
                # Bekleme mesajını gönder
                if twilio_client:
                    twilio_client.messages.create(
                        messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
                        body=wait_message,
                        to=from_number
                    )
                    logger.info(f"📤 Bekleme mesajı gönderildi: {wait_message}")
                
                return {"status": "media_queued", "message": wait_message}
                
            else:
                # Metin mesajı geldi - cache'de medya var mı kontrol et
                combined_text, cached_media_urls, cached_media_types = media_queue.handle_text(from_number, message_body)
                
                if combined_text and cached_media_urls:
                    # Medya + metin birleştirildi
                    logger.info(f"✅ Media Queue V2: Birleştirildi - {from_number}")
                    logger.info(f"   Birleşik mesaj: {combined_text[:100]}...")
                    logger.info(f"   Medya sayısı: {len(cached_media_urls)}")
                    
                    # Birleştirilmiş mesajı işle
                    message_body = combined_text
                    media_urls = cached_media_urls
                    media_types = cached_media_types
                    # Aşağıdaki normal akışa devam et
                else:
                    # Normal metin mesajı, cache'de medya yok
                    logger.info(f"💬 Media Queue V2: Normal metin - {from_number}")
                    # Normal akışa devam et
        
        # Boş mesaj kontrolü
        if not message_body or message_body.strip() == "":
            if not media_urls:  # Medya da yoksa ignore et
                return {"status": "ignored", "message": "Empty message"}
        
        print(f"✅ MESAJ ALINDI: {from_number} -> {message_body}")
        
        if not twilio_client:
            return {"status": "error", "message": "Twilio yapılandırması eksik"}
        
        # HAFIZALİ MESAJ İŞLEME - Medya desteği ile
        if media_urls:
            # Medya varsa, görsel analiz yap
            ai_response = process_whatsapp_message_with_media(message_body, from_number, media_urls, media_types)
        else:
            # Normal metin mesajı işle
            ai_response = process_whatsapp_message_with_memory(message_body, from_number)
        
        # Mesajı parçalara böl
        message_parts = split_long_message(ai_response, max_length=1600)
        
        sent_messages = []
        
        # Her parçayı sırayla gönder
        for i, part in enumerate(message_parts):
            if len(message_parts) > 1:
                if i == 0:
                    part = f"{part}\n\n(1/{len(message_parts)})"
                elif i == len(message_parts) - 1:
                    part = f"({i+1}/{len(message_parts)})\n\n{part}"
                else:
                    part = f"({i+1}/{len(message_parts)})\n\n{part}"
            
            # WhatsApp'a gönder
            message = twilio_client.messages.create(
                messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
                body=part,
                to=from_number
            )
            
            sent_messages.append(message.sid)
            
            if i < len(message_parts) - 1:
                import time
                time.sleep(0.5)
        
        print(f"✅ {len(message_parts)} PARÇA GÖNDERİLDİ")
        
        # Debug için mevcut kategoriyi logla
        context = get_conversation_context(from_number)
        if context.get("current_category"):
            print(f"💭 Aktif kategori: {context['current_category']}")
        
        return {
            "status": "success", 
            "message_parts": len(message_parts),
            "message_sids": sent_messages,
            "current_category": context.get("current_category")
        }
        
    except Exception as e:
        print(f"❌ Webhook hatası: {str(e)}")
        return {"status": "error", "message": str(e)}

@app.get("/")
async def root():
    return {"message": "Trek WhatsApp Bot çalışıyor!", "status": "active"}

# Hafızayı temizleme endpoint'i
@app.get("/clear-memory/{phone_number}")
async def clear_memory(phone_number: str):
    """Belirli bir telefon numarasının hafızasını temizle"""
    if phone_number in conversation_memory:
        del conversation_memory[phone_number]
        return {"status": "success", "message": f"{phone_number} hafızası temizlendi"}
    return {"status": "info", "message": "Hafıza bulunamadı"}

# Tüm hafızayı görme endpoint'i
@app.get("/debug-memory")
async def debug_memory():
    """Tüm hafızayı görüntüle (debug için)"""
    memory_info = {}
    for phone, context in conversation_memory.items():
        memory_info[phone] = {
            "current_category": context.get("current_category"),
            "message_count": len(context.get("messages", [])),
            "last_activity": str(context.get("last_activity"))
        }
    return {"conversation_memory": memory_info}

# Profil bilgilerini görme endpoint'i
@app.get("/debug-profile/{phone_number}")
async def debug_profile(phone_number: str):
    """Belirli kullanıcının profil bilgilerini görüntüle"""
    profile_summary = get_user_profile_summary(phone_number)
    return {"phone_number": phone_number, "profile": profile_summary}

# Tüm profilleri görme endpoint'i
@app.get("/debug-profiles")
async def debug_profiles():
    """Tüm kullanıcı profillerini görüntüle"""
    from whatsapp_passive_profiler import passive_profiler
    all_profiles = {}
    for phone_number in passive_profiler.profiles.keys():
        all_profiles[phone_number] = get_user_profile_summary(phone_number)
    return {"profiles": all_profiles}

@app.get("/health")
async def health():
    return {
        "status": "healthy",
        "twilio_configured": twilio_client is not None,
        "openai_configured": OPENAI_API_KEY is not None,
        "products_loaded": len(products),
        "webhook_endpoint": "/whatsapp-webhook"
    }

@app.get("/test-madone")
async def test_madone():
    """Test MADONE search directly"""
    from smart_warehouse_with_price import get_warehouse_stock_smart_with_price
    
    # Set a test API key if needed
    import os
    if not os.getenv("OPENAI_API_KEY"):
        return {"error": "No OPENAI_API_KEY set"}
    
    try:
        result = get_warehouse_stock_smart_with_price("madone sl 6")
        return {
            "query": "madone sl 6",
            "result": result if result else "No result",
            "api_key_set": bool(os.getenv("OPENAI_API_KEY"))
        }
    except Exception as e:
        return {"error": str(e), "type": type(e).__name__}

@app.post("/test-vision")
async def test_vision(request: Request):
    """Test vision capabilities with a sample image URL"""
    try:
        data = await request.json()
        image_url = data.get("image_url")
        text = data.get("text", "Bu görselde ne var?")
        
        if not image_url:
            return {"error": "image_url is required"}
        
        # Test vision API
        messages = [
            {
                "role": "system",
                "content": "Sen bir bisiklet uzmanısın. Görselleri analiz et ve detaylı bilgi ver."
            },
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": text},
                    {"type": "image_url", "image_url": {"url": image_url}}
                ]
            }
        ]
        
        payload = {
            "model": "gpt-5-chat-latest",
            "messages": messages,
            "temperature": 0,  # Deterministik cevaplar için
            "max_tokens": 500,
            "stream": False,
            "top_p": 0.1,  # Daha tutarlı cevaplar için düşük değer
            "frequency_penalty": 0.1,  # Tekrarları azaltmak için
            "presence_penalty": 0  # Yeni konulara açık olması için
        }
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }
        
        response = requests.post(API_URL, headers=headers, json=payload)
        
        if response.status_code == 200:
            result = response.json()
            return {
                "success": True,
                "response": result['choices'][0]['message']['content'],
                "model": result.get('model', 'unknown')
            }
        else:
            return {
                "success": False,
                "error": response.text,
                "status_code": response.status_code
            }
            
    except Exception as e:
        return {"error": str(e), "type": type(e).__name__}

if __name__ == "__main__":
    import uvicorn
    print("🚀 Trek WhatsApp Bot başlatılıyor...")
    uvicorn.run(app, host="0.0.0.0", port=7860)