File size: 78,233 Bytes
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944ac8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944ac8b
 
 
 
6ea7409
 
 
 
 
944ac8b
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944ac8b
6ea7409
 
 
 
 
 
 
 
944ac8b
6ea7409
944ac8b
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944ac8b
6ea7409
 
 
 
 
 
944ac8b
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944ac8b
 
 
 
 
 
 
 
6ea7409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
# -*- coding: utf-8 -*-
"""
Trek WhatsApp AI Asistani - Hybrid Model Version
Gorsel varsa: GPT-4o (vision)
Metin varsa: GPT-5.2 (daha akilli)
"""

import os
import json
import re
import requests
import xml.etree.ElementTree as ET
import warnings
import time
import threading
import datetime
import unicodedata
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 moduller - Basit sistem
from prompts import get_active_prompts
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 BASA EKLENDI
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

warnings.simplefilter('ignore')

# ===============================
# BLOCKLIST & RATE LIMITER
# ===============================
# Engellenen numaralar - mesajlari sessizce ignore edilir (0 token)
BLOCKED_NUMBERS = {
    "whatsapp:+905376627860",  # Spam - sonsuz sacma soru
}

# Rate limiter - dakikada max mesaj sayisi (tum numaralar icin)
RATE_LIMIT_PER_MINUTE = 10
rate_limit_tracker = {}  # {phone_number: [timestamp1, timestamp2, ...]}

def is_blocked(phone_number):
    """Numara blocklist'te mi kontrol et"""
    if phone_number in BLOCKED_NUMBERS:
        logger.warning(f"🚫 ENGELLENEN NUMARA: {phone_number} - mesaj ignore edildi")
        return True
    return False

def is_rate_limited(phone_number):
    """Dakikada cok fazla mesaj atan numarayi gecici engelle"""
    now = time.time()
    if phone_number not in rate_limit_tracker:
        rate_limit_tracker[phone_number] = []

    # Son 60 saniyedeki mesajlari filtrele
    rate_limit_tracker[phone_number] = [
        t for t in rate_limit_tracker[phone_number] if now - t < 60
    ]

    if len(rate_limit_tracker[phone_number]) >= RATE_LIMIT_PER_MINUTE:
        logger.warning(f"⏱️ RATE LIMIT: {phone_number} - dakikada {RATE_LIMIT_PER_MINUTE}+ mesaj")
        return True

    rate_limit_tracker[phone_number].append(now)
    return False

# ===============================
# MODEL KONFIGURASYONU
# ===============================
MODEL_CONFIG = {
    "vision": "gpt-4o",              # Gorsel analizi icin (Vision destekli)
    "text": "gpt-5.2-chat-latest",   # Metin icin (en akilli model)
    "fallback": "gpt-4o"             # Yedek model (GPT-5.2 hata verirse)
}

# Model secimi icin yardimci fonksiyon
def get_model_for_request(has_media=False):
    """
    Istek tipine gore uygun modeli sec
    has_media=True -> GPT-4o (vision destekli)
    has_media=False -> GPT-5.2 (daha akilli metin isleme)
    """
    if has_media:
        logger.info(f"🖼️ Gorsel tespit edildi -> Model: {MODEL_CONFIG['vision']}")
        return MODEL_CONFIG["vision"]
    else:
        logger.info(f"📝 Metin mesaji -> Model: {MODEL_CONFIG['text']}")
        return MODEL_CONFIG["text"]

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

# Twilio WhatsApp ayarlari
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", "MG11c1dfac28ad5f81908ec9ede0f7247f")
TWILIO_WHATSAPP_NUMBER = "whatsapp:+905332047254"  # Bizim WhatsApp Business numaramiz

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

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 basariyla olusturuldu!")
    except Exception as e:
        logger.error(f"❌ Twilio client hatasi: {e}")
        twilio_client = None

# ===============================
# GPT-5 SMART WAREHOUSE
# ===============================
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")

# 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 Follow-Up System
try:
    from follow_up_system import (
        FollowUpManager,
        analyze_message_for_follow_up,
        FollowUpType
    )
    USE_FOLLOW_UP = True
    follow_up_manager = FollowUpManager()
    logger.info("✅ Follow-Up System loaded")
except ImportError:
    USE_FOLLOW_UP = False
    follow_up_manager = None
    logger.info("❌ Follow-Up 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")

# ===============================
# STOK API ENTEGRASYONU
# ===============================
STOCK_API_BASE = "https://video.trek-turkey.com/bizimhesap-proxy.php"

# Stock cache (5 dakikalik cache)
stock_cache = {}
CACHE_DURATION = 300  # 5 dakika (saniye cinsinden)

# Turkish character normalization
turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}

def normalize_turkish(text):
    """Turkce karakterleri normalize et"""
    if not text:
        return ""
    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.lower()

def fetch_warehouse_inventory(warehouse, product_name, search_terms):
    """Tek bir magazanin stok bilgisini al"""
    try:
        warehouse_id = warehouse['id']
        warehouse_name = warehouse['title']

        # DSW'yi ayri tut (gelecek stok icin)
        is_dsw = 'DSW' in warehouse_name or 'ÖN SİPARİŞ' in warehouse_name.upper()

        # Magaza stoklarini 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 yanitini kontrol et
        if 'data' not in inventory_data or 'inventory' not in inventory_data['data']:
            return None

        products_list = inventory_data['data']['inventory']

        # Beden terimleri kontrolu
        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 mi 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

        # Eger sadece beden sorgusu varsa (or: "m", "xl")
        is_only_size_query = len(search_terms) == 1 and has_size_query

        # Urunu ara
        warehouse_variants = []
        dsw_stock_count = 0

        for product in products_list:
            product_title = normalize_turkish(product.get('title', '')).lower()
            original_title = product.get('title', '')

            # Eger sadece beden sorgusu ise
            if is_only_size_query:
                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 urun aramasi
                if has_size_query:
                    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)
                    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

                            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:
                    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")

        # Sonuc dondur
        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 gercek zamanli stok bilgisini cek - Paralel versiyon with cache"""
    try:
        # Cache kontrolu
        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]
            if current_time - cached_time < CACHE_DURATION:
                logger.info(f"Cache'den donduruluyor: {product_name}")
                return cached_data

        # Once magaza 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"Magaza listesi alinamadi: {warehouses_response.status_code}")
            return None

        warehouses_data = warehouses_response.json()

        if 'data' not in warehouses_data or 'warehouses' not in warehouses_data['data']:
            logger.error("Magaza verisi bulunamadi")
            return None

        warehouses = warehouses_data['data']['warehouses']

        # Urun adini normalize et
        search_terms = normalize_turkish(product_name).lower().split()
        logger.info(f"Aranan urun: {product_name} -> {search_terms}")

        stock_info = {}
        total_dsw_stock = 0
        total_stock = 0

        # Paralel olarak tum magazalari sorgula
        with ThreadPoolExecutor(max_workers=10) as executor:
            futures = {
                executor.submit(fetch_warehouse_inventory, warehouse, product_name, search_terms): warehouse
                for warehouse in warehouses
            }

            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

        # Sonucu olustur
        if not stock_info:
            if total_dsw_stock > 0:
                result = f"{product_name}: Su anda magazalarda stokta yok, ancak yakinda gelecek. On siparis verebilirsiniz."
            else:
                result = f"{product_name}: Su anda hicbir magazada stokta bulunmuyor."
        else:
            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}")

            if total_stock > 0:
                prompt_lines.append(f"✓ Urun 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 hatasi: {e}")
        return None

def is_stock_query(message):
    """Mesajin stok sorgusu olup olmadigini kontrol et - Basit yedek kontrol"""
    # Bu fonksiyon artik sadece yedek olarak kullaniliyor
    # Ana tespit Intent Analyzer tarafindan yapiliyor
    basic_keywords = ['stok', 'stock', 'var mı', 'mevcut']
    message_lower = message.lower()
    return any(keyword in message_lower for keyword in basic_keywords)

# ===============================
# MAGAZA STOK BILGISI CEKME
# ===============================
def get_warehouse_stock(product_name):
    """B2B API'den magaza stok bilgilerini cek - 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):
                if all(isinstance(item, str) for item in gpt5_result):
                    return gpt5_result
                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}")

    # 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)

        # 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 = []

        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]

        is_size_color_query = len(variant_words) > 0 and len(search_words) <= 4

        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())

                    product_name_matches = True
                    if product_words:
                        product_name_matches = all(word in normalized_product_name for word in product_words)

                    if product_name_matches:
                        if variant_elem is not None and variant_elem.text:
                            variant_text = normalize_turkish(variant_elem.text.lower().replace('-', ' '))

                            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:
                is_size_color_query = False

        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()

                    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))

            if not candidates:
                candidates = exact_matches if exact_matches else []

        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()

                    common_words = set(search_words) & set(xml_words)

                    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)))

            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]

        warehouse_stock_map = {}

        for product, xml_name, _ in candidates:
            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:
                            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:
            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 ["Hicbir magazada stokta bulunmuyor"]

    except Exception as e:
        logger.error(f"Magaza stok bilgisi cekme hatasi: {e}")
        return None

# ===============================
# TREK BISIKLET URUNLERINI CEKME
# ===============================
try:
    url = 'https://www.trekbisiklet.com.tr/output/8582384479'
    response = requests.get(url, verify=False, timeout=10)
    root = ET.fromstring(response.content)
    all_items = root.findall('item')

    products = []

    for item in all_items:
        stock_number = 0
        stock_amount = "stokta degil"
        price = ""
        price_eft = ""
        product_link = ""
        picture_url = ""
        category_tree = ""
        category_label = ""
        stock_code = ""
        root_product_stock_code = ""
        is_option_of_product = "0"
        is_optioned_product = "0"

        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 KONTROLU - SAYISAL KARSILASTIRMA
        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 degil"
            except (ValueError, TypeError):
                stock_number = 0
                stock_amount = "stokta degil"

        # Urun linki - HER URUN ICIN AL
        link_element = item.find('productLink')
        product_link = link_element.text if link_element is not None and link_element.text else ""

        # Urun resmi - HER URUN ICIN AL
        picture_element = item.find('picture1Path')
        picture_url = picture_element.text if picture_element is not None and picture_element.text else ""

        # Kategori bilgileri - HER URUN ICIN AL
        category_tree_element = item.find('categoryTree')
        category_tree = category_tree_element.text if category_tree_element is not None and category_tree_element.text else ""

        category_label_element = item.find('productCategoryLabel')
        category_label = category_label_element.text if category_label_element is not None and category_label_element.text else ""

        # Stock Code (SKU) - HER URUN ICIN AL
        stock_code_element = item.find('stockCode')
        stock_code = stock_code_element.text if stock_code_element is not None and stock_code_element.text else ""

        # Variant/main product iliski alanlari
        root_product_stock_code_element = item.find('rootProductStockCode')
        root_product_stock_code = root_product_stock_code_element.text if root_product_stock_code_element is not None and root_product_stock_code_element.text else ""

        is_option_of_product_element = item.find('isOptionOfAProduct')
        is_option_of_product = is_option_of_product_element.text if is_option_of_product_element is not None and is_option_of_product_element.text else "0"

        is_optioned_product_element = item.find('isOptionedProduct')
        is_optioned_product = is_optioned_product_element.text if is_optioned_product_element is not None and is_optioned_product_element.text else "0"

        # Stokta olan urunler icin 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 fiyati
            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 ""

            final_price_str = price_str
            if price_rebate_str:
                try:
                    normal_price = float(price_str)
                    rebate_price = float(price_rebate_str)
                    if rebate_price < normal_price:
                        final_price_str = price_rebate_str
                except (ValueError, TypeError):
                    final_price_str = price_str

            # EFT fiyati
            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 ""

            # Fiyat formatting
            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 = ""

        # Urun bilgilerini tuple olarak olustur
        item_info = (stock_amount, price, product_link, price_eft, str(stock_number),
                     picture_url, category_tree, category_label, stock_code,
                     root_product_stock_code, is_option_of_product, is_optioned_product)
        products.append((name, item_info, full_name))

    logger.info(f"✅ {len(products)} urun yuklendi")

except Exception as e:
    logger.error(f"❌ Urun yukleme hatasi: {e}")
    import traceback
    traceback.print_exc()
    products = []

# ===============================
# SISTEM MESAJLARI
# ===============================
def get_system_messages():
    """Sistem mesajlarini yukle - Moduler prompts'tan"""
    try:
        return get_active_prompts()
    except:
        # Fallback sistem mesajlari
        return [
            {"role": "system", "content": "Sen Trek bisiklet uzmani AI asistanisin. Trek ve Electra bisikletler konusunda uzmansin. Stokta bulunan urunlerin fiyat bilgilerini verebilirsin."}
        ]

# ===============================
# SOHBET HAFIZASI SISTEMI
# ===============================
conversation_memory = {}

def get_conversation_context(phone_number):
    """Kullanicinin sohbet gecmisini getir"""
    if phone_number not in conversation_memory:
        conversation_memory[phone_number] = {
            "messages": [],
            "current_category": None,
            "current_product": None,
            "current_product_link": None,
            "current_product_price": None,
            "last_activity": None
        }
    return conversation_memory[phone_number]

def add_to_conversation(phone_number, user_message, ai_response):
    """Sohbet gecmisine ekle"""
    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 mesaji 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):
    """Konusulan kategoriyi ve tam urun adini 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

                # TAM URUN ADINI CIKAR - ornegin "Marlin 5", "Madone SLR 9"
                # Model numarasini da yakala
                import re
                # Keyword + sayi pattern'i ara (ornegin "marlin 5", "madone slr 9")
                pattern = rf'{keyword}\s*\+?\s*(?:slr\s*)?(\d+)?'
                match = re.search(pattern, user_lower)
                if match:
                    model_num = match.group(1)
                    if model_num:
                        # Tam urun adi: "marlin 5" veya "madone slr 9"
                        full_product = match.group(0).strip()
                        context["current_product"] = full_product
                    else:
                        # Sadece kategori adi
                        context["current_product"] = keyword
                else:
                    context["current_product"] = keyword

                return category

    return context.get("current_category")

def build_context_messages(phone_number, current_message):
    """Sohbet gecmisi ile sistem mesajlarini olustur"""
    context = get_conversation_context(phone_number)
    system_messages = get_system_messages()

    # Mevcut kategori varsa, sistem mesajina ekle - GUCLENDIRILMIS BAGLAIM
    if context.get("current_category"):
        cat = context['current_category'].upper()
        category_msg = f"""KRITIK BAGLAIM BILGISI:
Musteri su anda {cat} modelleri hakkinda konusuyor.
Butun sorulari bu baglamda cevapla.
"Hangi model var", "stok var mi", "fiyat ne" gibi sorular {cat} icin sorulmus demektir.
DS, FX, Verve gibi BASKA kategorilerden bahsetme - sadece {cat} hakkinda konusuyoruz!"""
        system_messages.append({"role": "system", "content": category_msg})

    # Son konusulan urun bilgilerini ekle (link, fiyat sorulari icin)
    if context.get("current_product"):
        product_context = f"Son konusulan urun: {context['current_product']}"
        if context.get("current_product_link"):
            product_context += f"\nUrun linki: {context['current_product_link']}"
        if context.get("current_product_price"):
            product_context += f"\nUrun fiyati: {context['current_product_price']}"
        system_messages.append({"role": "system", "content": product_context})

    # Son 3 mesaj alisverisini ekle
    recent_messages = context["messages"][-3:] if context["messages"] else []

    all_messages = system_messages.copy()

    # Gecmis mesajlari ekle
    for msg in recent_messages:
        all_messages.append({"role": "user", "content": msg["user"]})
        all_messages.append({"role": "assistant", "content": msg["ai"]})

    # Mevcut mesaji ekle
    all_messages.append({"role": "user", "content": current_message})

    return all_messages

# ===============================
# HYBRID MODEL MESAJ ISLEME
# ===============================


def extract_product_from_vision_response(response):
    """
    GPT Vision yanitindan urun adini cikarir
    Ornek: "Trek Domane+ SLR 7 AXS" -> "Domane+ SLR 7 AXS"
    """
    import re
    
    # Bilinen Trek model pattern'leri
    patterns = [
        # Trek Domane+ SLR 7 AXS gibi tam isimler
        r'Trek\s+((?:Domane|Madone|Emonda|Marlin|Fuel|Rail|Powerfly|Checkpoint|FX|Verve|Dual\s*Sport|Procaliber|Supercaliber|Roscoe|Top\s*Fuel|Slash|Remedy|X-?Caliber|Allant)[+]?\s*(?:SLR|SL|Gen|EX|EXe)?\s*\d*\s*(?:AXS|Di2|eTap|Frameset)?)',
        # Sadece model adi + numara
        r'((?:Domane|Madone|Emonda|Marlin|Fuel|Rail|Powerfly|Checkpoint|FX|Verve|Dual\s*Sport|Procaliber|Supercaliber|Roscoe|Top\s*Fuel|Slash|Remedy|X-?Caliber|Allant)[+]?\s*(?:SLR|SL|Gen|EX|EXe)?\s*\d+\s*(?:AXS|Di2|eTap|Frameset)?)',
        # Model + SLR/SL + numara
        r'((?:Domane|Madone|Emonda)[+]?\s+(?:SLR|SL)\s*\d+)',
        # Marlin + numara
        r'(Marlin\s*\d+)',
        # FX + numara
        r'(FX\s*(?:Sport)?\s*\d+)',
    ]
    
    response_lower = response.lower()
    
    for pattern in patterns:
        match = re.search(pattern, response, re.IGNORECASE)
        if match:
            product = match.group(1).strip()
            # "Trek " prefix varsa kaldir
            product = re.sub(r'^Trek\s+', '', product, flags=re.IGNORECASE)
            return product
    
    return None


def process_whatsapp_message_with_media(user_message, phone_number, media_urls, media_types):
    """
    GORSEL MESAJ ISLEME - GPT-4o Vision kullanir
    """
    try:
        logger.info(f"🖼️ Gorsel analizi basliyor: {len(media_urls)} medya")
        logger.info(f"📎 Medya URL'leri: {media_urls}")
        logger.info(f"📎 Medya tipleri: {media_types}")

        # Pasif profil analizi
        try:
            profile_analysis = analyze_user_message(phone_number, user_message)
            logger.info(f"📊 Profil analizi: {phone_number} -> {profile_analysis}")
        except:
            pass

        # Gorsel icin GPT-4o kullan
        model = get_model_for_request(has_media=True)

        # Sohbet gecmisi ile sistem mesajlarini olustur
        messages = build_context_messages(phone_number, user_message if user_message else "Gonderilen gorseli analiz et")

        # GPT-4o Vision icin mesaj hazirla
        vision_message = {
            "role": "user",
            "content": []
        }

        # Metin mesaji 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 gorselde ne var? Eger bisiklet veya bisiklet parcasi ise detayli acikla."
            })

        # Medya URL'lerini isle
        valid_images = 0
        for i, media_url in enumerate(media_urls):
            media_type = media_types[i] if i < len(media_types) else "image/jpeg"

            # Sadece gorsel medyalari isle
            if media_type and media_type.startswith('image/'):
                try:
                    # Twilio medya URL'sini proxy uzerinden cevir
                    if 'api.twilio.com' in media_url:
                        import re
                        match = re.search(r'/Messages/([^/]+)/Media/([^/]+)', media_url)
                        if match:
                            message_sid = match.group(1)
                            media_sid = match.group(2)
                            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 olusturuldu: {proxy_url}")

                            # Proxy URL'sinin calisip calismadigini kontrol et
                            try:
                                test_response = requests.head(proxy_url, timeout=5, verify=False)
                                if test_response.status_code == 200:
                                    vision_message["content"].append({
                                        "type": "image_url",
                                        "image_url": {"url": proxy_url}
                                    })
                                    valid_images += 1
                                    logger.info(f"✅ Proxy URL gecerli: {proxy_url}")
                                else:
                                    logger.error(f"❌ Proxy URL calismiyor: {test_response.status_code}")
                                    vision_message["content"].append({
                                        "type": "image_url",
                                        "image_url": {"url": media_url}
                                    })
                                    valid_images += 1
                            except Exception as proxy_error:
                                logger.error(f"❌ Proxy test hatasi: {proxy_error}")
                                vision_message["content"].append({
                                    "type": "image_url",
                                    "image_url": {"url": media_url}
                                })
                                valid_images += 1
                        else:
                            logger.error(f"❌ Twilio URL parse edilemedi: {media_url}")
                    else:
                        vision_message["content"].append({
                            "type": "image_url",
                            "image_url": {"url": media_url}
                        })
                        valid_images += 1
                        logger.info(f"✅ Dogrudan URL eklendi: {media_url}")
                except Exception as url_error:
                    logger.error(f"❌ URL isleme hatasi: {url_error}")
            else:
                logger.warning(f"⚠️ Gorsel olmayan medya atlandi: {media_type}")

        # Hic gecerli gorsel yoksa
        if valid_images == 0:
            logger.error("❌ Hic gecerli gorsel bulunamadi")
            return "Gonderdiginiz gorsel islenemedi. Lutfen farkli bir gorsel gonderin veya sorunuzu yazili olarak iletin."

        logger.info(f"✅ {valid_images} gorsel islenecek")

        # Son user mesajini vision mesajiyla degistir
        messages = [msg for msg in messages if not (msg.get("role") == "user" and msg == messages[-1])]
        messages.append(vision_message)

        # Sistem mesajina bisiklet tanima talimati ekle
        bike_recognition_prompt = {
            "role": "system",
            "content": """Gonderilen gorselleri dikkatle analiz et:
1. Eger bisiklet veya bisiklet parcasi goruyorsan, detaylica tanimla (marka, model, renk, beden, ozellikler)
2. Trek bisiklet ise modeli tahmin etmeye calis
3. Stok veya fiyat sorulursa, gorseldeki bisikletin ozelliklerini belirterek bilgi ver
4. Gorsel net degilse veya tanimlanamiyorsa, kullanicidan daha net bir gorsel istemek yerine, gorselde gorduklerini acikla
5. Eger gorsel bisikletle ilgili degilse, ne gordugunu kisaca acikla"""
        }
        messages.insert(0, bike_recognition_prompt)

        if not OPENAI_API_KEY:
            logger.error("❌ OpenAI API anahtari eksik")
            return "Sistem hatasi olustu. Lutfen daha sonra tekrar deneyin."

        logger.info(f"📤 GPT Vision API'ye gonderiliyor: {len(messages)} mesaj, {valid_images} gorsel")

        payload = {
            "model": model,  # GPT-4o
            "messages": messages,
            "max_tokens": 800,
            "temperature": 0.3
        }

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }

        response = requests.post(API_URL, headers=headers, json=payload, timeout=30)

        logger.info(f"📥 API yaniti: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']
            logger.info(f"✅ Gorsel analizi basarili: {ai_response[:100]}...")

            # KRITIK: Gorselden urun adini cikar ve GERCEK stok kontrolu yap
            try:
                from smart_warehouse_with_price import get_warehouse_stock
                
                # GPT yanitindan urun adini cikar
                product_name = extract_product_from_vision_response(ai_response)
                
                if product_name:
                    logger.info(f"🔍 Gorselden tespit edilen urun: {product_name}")
                    
                    # GERCEK stok kontrolu yap
                    stock_info = get_warehouse_stock(product_name)
                    
                    if stock_info:
                        logger.info(f"✅ Stok bilgisi bulundu: {stock_info[:100]}...")
                        
                        # GPT yanlis "stokta yok" dediyse duzelt
                        if "stokta bulunmuyor" in ai_response.lower() or "stokta yok" in ai_response.lower():
                            if "stokta bulunmuyor" not in stock_info.lower():
                                # Yanlis bilgiyi kaldir ve dogru stok bilgisini ekle
                                ai_response = re.sub(
                                    r'[^.]*stok[^.]*bulunmuyor[^.]*[.]?',
                                    '',
                                    ai_response,
                                    flags=re.IGNORECASE
                                )
                                ai_response = ai_response.strip()
                        
                        # Stok bilgisini ekle (eger zaten yoksa)
                        if "Stok:" not in ai_response and "stokta" not in stock_info.lower():
                            ai_response = ai_response + "\n\n" + stock_info

                        elif "Stok:" not in ai_response:
                            ai_response = ai_response + "\n\n" + stock_info

                    else:
                        logger.info(f"⚠️ Urun icin stok bilgisi bulunamadi: {product_name}")
                else:
                    logger.info("⚠️ Gorselden urun adi cikarilamadi")
            except Exception as stock_error:
                logger.error(f"❌ Vision stok kontrolu hatasi: {stock_error}")

            # WhatsApp icin formatla
            try:
                formatted_response = extract_product_info_whatsapp(ai_response)
            except:
                formatted_response = ai_response

            # Sohbet gecmisine ekle
            add_to_conversation(phone_number, f"[Gorsel gonderildi] {user_message if user_message else ''}", formatted_response)

            return formatted_response
        else:
            error_detail = response.text[:500] if response.text else "Detay yok"
            logger.error(f"❌ OpenAI API Error: {response.status_code} - {error_detail}")

            if response.status_code == 400:
                return "Gorsel formati desteklenmiyor. Lutfen JPG veya PNG formatinda bir gorsel gonderin."
            elif response.status_code == 413:
                return "Gorsel boyutu cok buyuk. Lutfen daha kucuk bir gorsel gonderin."
            elif response.status_code == 429:
                return "Sistem su anda yogun. Lutfen birkac saniye sonra tekrar deneyin."
            else:
                return "Gorsel su anda analiz edilemiyor. Sorunuzu yazili olarak iletebilir misiniz?"

    except requests.exceptions.Timeout:
        logger.error("❌ API timeout hatasi")
        return "Islem zaman asimina ugradi. Lutfen tekrar deneyin."
    except Exception as e:
        logger.error(f"❌ Medya isleme hatasi: {e}")
        import traceback
        traceback.print_exc()
        return "Gorsel islenirken bir sorun olustu. Lutfen sorunuzu yazili olarak iletin veya farkli bir gorsel deneyin."


def process_whatsapp_message_with_memory(user_message, phone_number):
    """
    METIN MESAJ ISLEME - GPT-5.2 kullanir (daha akilli)
    """
    try:
        # Metin icin GPT-5.2 kullan
        model = get_model_for_request(has_media=False)

        # Pasif profil analizi
        try:
            profile_analysis = analyze_user_message(phone_number, user_message)
            logger.info(f"📊 Profil analizi: {phone_number}")
        except:
            pass

        # 🔔 Yeni Magaza Bildirim Sistemi - Mehmet Bey'e otomatik bildirim
        if USE_STORE_NOTIFICATION:
            try:
                should_notify_mehmet, notification_reason, urgency = should_notify_mehmet_bey(user_message)

                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:
                    if intent_analysis:
                        product = intent_analysis.get("product") or "Belirtilmemis"
                    else:
                        context = get_conversation_context(phone_number)
                        product = context.get("current_category") or "Urun belirtilmemis"

                    if "rezervasyon" in notification_reason.lower() or urgency == "high":
                        action = "reserve"
                    elif "magaza" in notification_reason.lower() or "lokasyon" in notification_reason.lower():
                        action = "info"
                    elif "fiyat" in notification_reason.lower() or "odeme" in notification_reason.lower():
                        action = "price"
                    else:
                        action = "info"

                    additional_info = f"{notification_reason}\n\nMusteri Mesaji: '{user_message}'"
                    if urgency == "high":
                        additional_info = "⚠️ YUKSEK ONCELIK ⚠️\n" + additional_info

                    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 gonderildi!")
                        logger.info(f"   📍 Sebep: {notification_reason}")
                        logger.info(f"   ⚡ Oncelik: {urgency}")
                        logger.info(f"   📦 Urun: {product}")

                        # TAKIP SISTEMINI KONTROL ET
                        if USE_FOLLOW_UP and follow_up_manager:
                            try:
                                follow_up_analysis = analyze_message_for_follow_up(user_message)
                                if follow_up_analysis and follow_up_analysis.get("needs_follow_up"):
                                    follow_up = follow_up_manager.create_follow_up(
                                        customer_phone=phone_number,
                                        product_name=product,
                                        follow_up_type=follow_up_analysis["follow_up_type"],
                                        original_message=user_message,
                                        follow_up_hours=follow_up_analysis.get("follow_up_hours", 24),
                                        notes=follow_up_analysis.get("reason", "")
                                    )
                                    logger.info(f"📌 Takip olusturuldu: {follow_up_analysis.get('reason', '')}")
                            except Exception as follow_up_error:
                                logger.error(f"Takip sistemi hatasi: {follow_up_error}")
            except Exception as notify_error:
                logger.error(f"Bildirim hatasi: {notify_error}")

        # Sohbet gecmisi ile mesajlari olustur
        messages = build_context_messages(phone_number, user_message)

        # Intent Analyzer veya context'ten urun bilgisini al
        detected_product = None
        intent_analysis = None  # Scope disinda da kullanilacak
        if USE_INTENT_ANALYZER:
            try:
                context = get_conversation_context(phone_number)
                intent_analysis = analyze_customer_intent(user_message, context)
                if intent_analysis and intent_analysis.get("product"):
                    detected_product = intent_analysis.get("product")
                    logger.info(f"🎯 Intent'ten tespit edilen urun: {detected_product}")
            except Exception as e:
                logger.error(f"Intent analiz hatasi: {e}")
                intent_analysis = None

        # Eger Intent'ten urun bulunamadiysa, context'ten al
        # ONEMLI: current_product TAM URUN ADINI icerir (ornegin "marlin 5")
        # current_category ise sadece kategori adidir (ornegin "marlin")
        if not detected_product:
            context = get_conversation_context(phone_number)
            # Oncelikle tam urun adini dene
            if context.get("current_product"):
                detected_product = context.get("current_product")
                logger.info(f"🎯 Context'ten tespit edilen TAM URUN: {detected_product}")
            elif context.get("current_category"):
                detected_product = context.get("current_category")
                logger.info(f"🎯 Context'ten tespit edilen kategori: {detected_product}")

        # Stok sorgusu icin kullanilacak urun adi
        stock_query_product = detected_product if detected_product else user_message

        # Urun bilgilerini ekle
        input_words = user_message.lower().split()
        # Detected product'i da input_words'e ekle
        if detected_product:
            input_words.extend(detected_product.lower().split())

        # Bulunan urunun link ve gorsel bilgilerini sakla
        found_product_link = None
        found_product_image = None
        found_product_name = None
        best_match_score = 0

        # Kullanici mesaji veya detected_product'i normalize et
        search_text = (detected_product or user_message).lower()
        search_words = search_text.split()

        # AKILLI URUN ESLESTIRME
        # 1. Kategori bazli filtreleme - Bisiklet aramasinda aksesuar gosterme
        # 2. Urun tipi benzerligi - Ayni tip urunler oncelikli
        # 3. Kelime eslesmesi - En cok eslesen urun

        def is_bicycle_search(text):
            """Arama bisiklet mi yoksa aksesuar mi?"""
            bike_indicators = ['madone', 'domane', 'emonda', 'checkpoint', 'fuel', 'slash',
                              'marlin', 'procaliber', 'supercaliber', 'fx', 'verve', 'dual sport',
                              'powerfly', 'rail', 'allant', 'bisiklet', 'bike']
            text_lower = text.lower()
            return any(ind in text_lower for ind in bike_indicators)

        def get_product_type(category_tree, product_name):
            """Urun tipini belirle"""
            cat_lower = (category_tree or "").lower()
            name_lower = (product_name or "").lower()

            # Kategori agacindan tip belirle
            if 'bisiklet' in cat_lower or 'bike' in cat_lower:
                if 'yol' in cat_lower or 'road' in cat_lower:
                    return 'road_bike'
                elif 'dag' in cat_lower or 'mountain' in cat_lower or 'mtb' in cat_lower:
                    return 'mtb'
                elif 'elektrik' in cat_lower or 'e-bike' in cat_lower:
                    return 'ebike'
                elif 'sehir' in cat_lower or 'hybrid' in cat_lower:
                    return 'hybrid'
                return 'bicycle'
            elif 'aksesuar' in cat_lower or 'parça' in cat_lower or 'parca' in cat_lower or 'accessory' in cat_lower or 'yedek' in cat_lower:
                return 'accessory'

            # Isimden tip belirle (fallback)
            # ONEMLI: Aksesuar kontrolu ONCE yapilmali cunku "Domane Kadro Kulagi" gibi
            # urunlerde model adi gecebilir ama aksesuar kelimeleri varsa aksesuar'dir
            accessory_keywords = ['sele', 'gidon', 'pedal', 'zincir', 'lastik', 'jant', 'fren', 'vites',
                                 'kadro kulağı', 'kadro kulagi', 'kulak', 'kablo', 'kasnak', 'dişli',
                                 'zil', 'far', 'lamba', 'pompa', 'kilit', 'çanta', 'canta', 'suluk',
                                 'gözlük', 'gozluk', 'kask', 'eldiven', 'ayakkabı', 'ayakkabi',
                                 'forma', 'tayt', 'şort', 'sort', 'mont', 'yağmurluk', 'yagmurluk']
            if any(x in name_lower for x in accessory_keywords):
                return 'accessory'
            if any(x in name_lower for x in ['madone', 'domane', 'emonda', 'checkpoint', 'fuel', 'marlin', 'fx']):
                return 'bicycle'

            return 'unknown'

        def calculate_smart_match_score(search_words, product_name, product_category, is_bike_search):
            """Akilli eslesme skoru hesapla"""
            product_name_lower = product_name.lower()
            product_words = product_name_lower.split()
            product_type = get_product_type(product_category, product_name)

            # Temel kelime eslesmesi
            base_score = sum(1 for word in search_words if word in product_name_lower)

            # Kategori uyumu bonusu/cezasi
            if is_bike_search:
                if product_type == 'bicycle':
                    base_score += 2  # Bisiklet aramasinda bisiklet bulunca bonus
                elif product_type == 'accessory':
                    base_score -= 100  # Bisiklet aramasinda aksesuar KESINLIKLE gosterilmemeli

            # KRITIK VARYANT KONTROLU
            # AXS, Di2, eTap gibi varyantlar FARKLI URUNLERDIR
            # Kullanici "Madone SLR 9" diyorsa "Madone SLR 9 AXS" GOSTERILMEMELI
            critical_variants = ['axs', 'etap', 'di2', 'frameset']

            # Urunde olan kritik varyantlar
            product_critical_variants = [v for v in critical_variants if v in product_name_lower]
            # Kullanicinin soyledigi kritik varyantlar
            user_critical_variants = [v for v in critical_variants if v in ' '.join(search_words)]

            # Urunde kritik varyant var AMA kullanici soylemedi -> BUYUK CEZA
            for variant in product_critical_variants:
                if variant not in user_critical_variants:
                    base_score -= 50  # Bu urun gosterilmemeli

            # Kullanici kritik varyant soyledi AMA urunde yok -> CEZA
            for variant in user_critical_variants:
                if variant not in product_critical_variants:
                    base_score -= 50  # Bu urun gosterilmemeli

            # Tam esleme bonusu - Tum arama kelimeleri urunde varsa
            all_words_match = all(word in product_name_lower for word in search_words if len(word) > 2)
            if all_words_match and len(search_words) > 1:
                base_score += 3

            # Model numarasi eslesmesi - "9" araniyorsa "9" olmali, "7" olmamali
            for word in search_words:
                if word.isdigit():
                    if word in product_words:
                        base_score += 2  # Tam numara eslesmesi
                    else:
                        # Farkli numara varsa ceza
                        for pword in product_words:
                            if pword.isdigit() and pword != word:
                                base_score -= 20  # Farkli model numarasi

            return base_score

        # Arama bisiklet mi?
        is_bike_search = is_bicycle_search(search_text)

        for product_info in products:
            product_full_name = product_info[2]  # Tam urun adi
            product_category = product_info[1][6] if len(product_info[1]) > 6 else ""  # category_tree

            # Akilli skor hesapla
            match_score = calculate_smart_match_score(
                search_words,
                product_full_name,
                product_category,
                is_bike_search
            )

            # Daha iyi eslesme bulduysa guncelle
            if match_score > best_match_score and product_info[1][0] == "stokta":
                best_match_score = match_score

                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

                # Urun linki ve gorseli al - EN IYI ESLESEN URUN
                if product_info[1][2]:  # product_link
                    found_product_link = product_info[1][2]
                if product_info[1][5]:  # picture_url
                    found_product_image = product_info[1][5]
                found_product_name = product_info[2]

                # System message'a LINK EKLEME - cunku GPT linki yanitina dahil ediyor
                # ve sonra biz de ekledigimizde 2 kere gorunuyor
                new_msg = f"{product_info[2]} {product_info[1][0]} - {price_info}"
                messages.append({"role": "system", "content": new_msg})

        # Eger match bulunamadiysa, basit eslesme dene
        if best_match_score == 0:
            for product_info in products:
                if product_info[0] in input_words and 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

                    if product_info[1][2]:
                        found_product_link = product_info[1][2]
                    if product_info[1][5]:
                        found_product_image = product_info[1][5]
                    found_product_name = product_info[2]

                    new_msg = f"{product_info[2]} {product_info[1][0]} - {price_info}"
                    messages.append({"role": "system", "content": new_msg})
                    break  # Ilk eslesen yeterli

        # Stok bilgisi ekle - detected_product kullan
        # ONCELIK: XML sonucu (smart_warehouse_with_price.py) daha guvenilir
        warehouse_info = get_warehouse_stock(stock_query_product)
        xml_has_valid_stock = False

        if warehouse_info:
            stock_msg = "Magaza Stok Durumu:\n" + "\n".join(warehouse_info) if isinstance(warehouse_info, list) else str(warehouse_info)
            messages.append({"role": "system", "content": stock_msg})

            # XML sonucunda gercek stok bilgisi var mi kontrol et
            # "mevcut degil", "bulunamadi", "tukendi" gibi ifadeler yoksa stok var demektir
            stock_msg_lower = stock_msg.lower()
            negative_indicators = ["mevcut değil", "mevcut degil", "bulunamadi", "bulunmuyor", "tükendi", "tukendi", "stokta yok"]
            xml_has_valid_stock = not any(indicator in stock_msg_lower for indicator in negative_indicators)

            if xml_has_valid_stock:
                logger.info(f"✅ XML'den stok bilgisi bulundu: {stock_query_product}")

            # Link ve fiyat bilgisini context'e kaydet (follow-up sorular icin)
            context = get_conversation_context(phone_number)
            link_match = re.search(r'Link: (https?://[^\s]+)', stock_msg)
            if link_match:
                context["current_product_link"] = link_match.group(1)
                logger.info(f"🔗 Link context'e kaydedildi: {link_match.group(1)}")
            price_match = re.search(r'Fiyat: ([^\n]+)', stock_msg)
            if price_match:
                context["current_product_price"] = price_match.group(1)
            # Urun adini da kaydet
            if stock_query_product:
                context["current_product"] = stock_query_product

        # Gercek zamanli stok sorgusu - SADECE XML sonucu bos veya olumsuzsa calistir
        # Bu sayede XML'de bulunan urunler icin yanlis "stokta yok" mesaji onlenir
        should_query_stock = False

        if not xml_has_valid_stock:
            if intent_analysis:
                # Intent Analyzer'dan gelen intent'lere bak
                intents = intent_analysis.get("intents", [])
                # stock, info, price gibi intent'ler stok sorgusu gerektirir
                stock_related_intents = ["stock", "info", "price", "availability"]
                should_query_stock = any(intent in intents for intent in stock_related_intents)

            # Urun tespit edildiyse de stok sorgula (kullanici urun hakkinda konusuyor demektir)
            if detected_product:
                should_query_stock = True

            # Yedek: Intent Analyzer calismazsa basit keyword kontrolu
            if not intent_analysis and is_stock_query(user_message):
                should_query_stock = True

        if should_query_stock and stock_query_product and not xml_has_valid_stock:
            realtime_stock = get_realtime_stock_parallel(stock_query_product)
            if realtime_stock:
                messages.append({"role": "system", "content": f"Gercek Zamanli Stok:\n{realtime_stock}"})
                logger.info(f"📦 API'den stok bilgisi eklendi: {stock_query_product}")

        if not OPENAI_API_KEY:
            return "Sistem hatasi olustu."

        # SON HATIRLATMA: Turkce dil kurallari - GPT'ye her yanit oncesi hatirlatma
        # Bu mesaj en sona ekleniyor ki GPT son gordukleri kurallari uygulasın
        turkish_reminder = """KRITIK KURALLAR (HER YANIT ICIN GECERLI):
1. ASLA 'sen' kullanma, HER ZAMAN 'siz' kullan (istersen -> isterseniz, sana -> size)
2. ASLA soru ile bitirme (ayirtayim mi?, ister misiniz?, bakar misiniz? YASAK)
3. Bilgiyi ver ve sus, musteri karar versin
4. ONEMLI: Onceki mesajlarda bahsedilen urunleri UNUTMA! "Hangi model var" gibi sorular onceki konudan devam eder.
YANLIS: "Istersen beden ve magaza bazli stok bilgisini de netlestirebilirim."
DOGRU: "Beden ve magaza bazli stok bilgisi icin yazabilirsiniz." """
        messages.append({"role": "system", "content": turkish_reminder})

        # Model tipine gore payload olustur
        # GPT-5.2 ve o1/o3 modelleri: temperature ve max_tokens desteklemiyor
        if "gpt-5" in model or "o1" in model or "o3" in model:
            payload = {
                "model": model,
                "messages": messages,
                "max_completion_tokens": 1000
            }
        else:
            payload = {
                "model": model,
                "messages": messages,
                "temperature": 0.3,
                "max_tokens": 1000
            }

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }

        logger.info(f"📤 API istegi gonderiliyor - Model: {model}")

        response = requests.post(API_URL, headers=headers, json=payload, timeout=30)

        if response.status_code == 200:
            result = response.json()
            ai_response = result['choices'][0]['message']['content']

            # Kullanilan modeli logla
            used_model = result.get('model', model)
            logger.info(f"✅ Yanit alindi - Kullanilan model: {used_model}")

            try:
                formatted_response = extract_product_info_whatsapp(ai_response)
            except:
                formatted_response = ai_response

            # Urun linki ve gorseli varsa ekle
            # NOT: Stok/magaza sorularinda yanlis gorsel gostermemek icin
            # sadece TEK URUN soruldugundan eminsen gorsel gonder
            is_specific_product_query = best_match_score >= 3  # En az 3 kelime eslesmeli

            if found_product_link and is_specific_product_query:
                formatted_response += f"\n\n🔗 {found_product_link}"

            add_to_conversation(phone_number, user_message, formatted_response)

            # Gorsel sadece spesifik urun sorgusu ise gonder
            # "Sariyer'de hangi renk var" gibi genel sorularda gorsel gonderme
            if found_product_image and is_specific_product_query:
                return (formatted_response, found_product_image)

            return formatted_response
        else:
            error_msg = response.text[:200] if response.text else "Bilinmeyen hata"
            logger.error(f"❌ API hatasi {response.status_code}: {error_msg}")

            # Fallback modele gec
            if model != MODEL_CONFIG["fallback"]:
                logger.info(f"🔄 Fallback modele geciliyor: {MODEL_CONFIG['fallback']}")
                fallback_model = MODEL_CONFIG["fallback"]

                # Fallback icin payload'i yeniden olustur (max_tokens kullan)
                fallback_payload = {
                    "model": fallback_model,
                    "messages": messages,
                    "temperature": 0.3,
                    "max_tokens": 1000
                }

                response = requests.post(API_URL, headers=headers, json=fallback_payload, timeout=30)

                if response.status_code == 200:
                    result = response.json()
                    ai_response = result['choices'][0]['message']['content']
                    add_to_conversation(phone_number, user_message, ai_response)
                    return ai_response

            return "Su anda bir sorun yasiyorum. Lutfen tekrar deneyin."

    except requests.exceptions.Timeout:
        logger.error("❌ API timeout hatasi")
        return "Islem zaman asimina ugradi. Lutfen tekrar deneyin."
    except Exception as e:
        logger.error(f"❌ Mesaj isleme hatasi: {e}")
        import traceback
        traceback.print_exc()
        return "Teknik bir sorun olustu. Lutfen tekrar deneyin."


# ===============================
# FASTAPI UYGULAMASI
# ===============================
app = FastAPI(title="Trek WhatsApp Bot - Hybrid Model")

@app.post("/whatsapp-webhook")
async def whatsapp_webhook(request: Request):
    """WhatsApp webhook - Hybrid model ile"""
    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 kontrolu
        num_media = int(form_data.get('NumMedia', 0))
        media_urls = []
        media_types = []

        for i in range(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"📱 Webhook - From: {from_number}, Body: {message_body[:50] if message_body else 'N/A'}, Media: {num_media}")

        # BLOCKLIST KONTROLU - engellenen numaralar sessizce ignore edilir (0 token)
        if from_number and is_blocked(from_number):
            return {"status": "blocked", "message": "Blocked number"}

        # RATE LIMIT KONTROLU - dakikada cok fazla mesaj atanlari engelle
        if from_number and is_rate_limited(from_number):
            return {"status": "rate_limited", "message": "Too many messages"}

        # Durum guncellemelerini ignore et
        if message_status in ['sent', 'delivered', 'read', 'failed']:
            return {"status": "ignored", "message": f"Status: {message_status}"}

        # Giden mesajlari ignore et
        if to_number != TWILIO_WHATSAPP_NUMBER:
            return {"status": "ignored", "message": "Outgoing message"}

        # Bos mesaj ve medya yoksa ignore et
        if not message_body and num_media == 0:
            return {"status": "ignored", "message": "Empty message"}

        logger.info(f"✅ MESAJ ALINDI: {from_number} -> Metin: {bool(message_body)}, Medya: {num_media}")

        if not twilio_client:
            return {"status": "error", "message": "Twilio yapilandirmasi eksik"}

        # ========================================
        # HYBRID MODEL SECIMI
        # ========================================
        product_image_url = None

        if num_media > 0 and media_urls:
            # GORSEL VAR -> GPT-4o kullan
            logger.info("🖼️ GORSEL TESPIT EDILDI -> GPT-4o Vision kullanilacak")
            ai_response = process_whatsapp_message_with_media(
                message_body,
                from_number,
                media_urls,
                media_types
            )
        else:
            # SADECE METIN -> GPT-5.2 kullan
            logger.info("📝 METIN MESAJI -> GPT-5.2 kullanilacak")
            result = process_whatsapp_message_with_memory(
                message_body,
                from_number
            )

            # Tuple donerse (metin, gorsel_url) seklinde
            if isinstance(result, tuple):
                ai_response, product_image_url = result
                logger.info(f"🖼️ Urun gorseli bulundu: {product_image_url}")
            else:
                ai_response = result

        # Yanit kisalt
        if len(ai_response) > 1500:
            ai_response = ai_response[:1500] + "...\n\nDetayli bilgi: trekbisiklet.com.tr"

        # WhatsApp'a gonder
        # Once metin mesaji gonder
        message = twilio_client.messages.create(
            messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
            body=ai_response,
            to=from_number
        )

        logger.info(f"✅ YANIT GONDERILDI: {ai_response[:100]}...")

        # Urun gorseli varsa ayrica gonder
        if product_image_url:
            try:
                image_message = twilio_client.messages.create(
                    messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
                    media_url=[product_image_url],
                    to=from_number
                )
                logger.info(f"🖼️ URUN GORSELI GONDERILDI: {product_image_url}")
            except Exception as img_error:
                logger.error(f"❌ Gorsel gonderme hatasi: {img_error}")

        return {"status": "success", "message_sid": message.sid}

    except Exception as e:
        logger.error(f"❌ Webhook hatasi: {str(e)}")
        import traceback
        traceback.print_exc()
        return {"status": "error", "message": str(e)}


@app.get("/")
async def root():
    return {
        "message": "Trek WhatsApp Bot - Hybrid Model calisiyor!",
        "status": "active",
        "models": {
            "vision": MODEL_CONFIG["vision"],
            "text": MODEL_CONFIG["text"],
            "fallback": MODEL_CONFIG["fallback"]
        }
    }


@app.get("/health")
async def health():
    return {
        "status": "healthy",
        "twilio_configured": twilio_client is not None,
        "openai_configured": OPENAI_API_KEY is not None,
        "models": MODEL_CONFIG,
        "products_loaded": len(products),
        "modules": {
            "gpt5_search": USE_GPT5_SEARCH,
            "media_queue": USE_MEDIA_QUEUE,
            "store_notification": USE_STORE_NOTIFICATION,
            "follow_up": USE_FOLLOW_UP,
            "intent_analyzer": USE_INTENT_ANALYZER
        }
    }


@app.get("/test-models")
async def test_models():
    """Model durumlarini test et"""
    results = {}

    for model_type, model_name in MODEL_CONFIG.items():
        try:
            payload = {
                "model": model_name,
                "messages": [{"role": "user", "content": "Merhaba, test mesaji."}],
                "max_tokens": 10
            }
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {OPENAI_API_KEY}"
            }
            response = requests.post(API_URL, headers=headers, json=payload, timeout=10)
            results[model_type] = {
                "model": model_name,
                "status": "OK" if response.status_code == 200 else f"Error: {response.status_code}",
                "available": response.status_code == 200
            }
        except Exception as e:
            results[model_type] = {
                "model": model_name,
                "status": f"Error: {str(e)}",
                "available": False
            }

    return results


@app.get("/cache-status")
async def cache_status():
    """Cache durumunu goster"""
    return {
        "cache_size": len(stock_cache),
        "cache_duration_seconds": CACHE_DURATION,
        "cached_products": list(stock_cache.keys())[:10]  # Ilk 10
    }


@app.post("/clear-cache")
async def clear_cache():
    """Cache'i temizle"""
    global stock_cache
    old_size = len(stock_cache)
    stock_cache = {}
    return {"message": f"Cache temizlendi. {old_size} kayit silindi."}


if __name__ == "__main__":
    import uvicorn
    print("=" * 60)
    print("   Trek WhatsApp Bot - HYBRID MODEL")
    print("=" * 60)
    print(f"   🖼️  Gorsel mesajlar -> {MODEL_CONFIG['vision']}")
    print(f"   📝  Metin mesajlar  -> {MODEL_CONFIG['text']}")
    print(f"   🔄  Fallback        -> {MODEL_CONFIG['fallback']}")
    print("=" * 60)
    print(f"   📦 Yuklenen urun sayisi: {len(products)}")
    print(f"   🔍 GPT-5 Search: {'Aktif' if USE_GPT5_SEARCH else 'Pasif'}")
    print(f"   🔔 Store Notification: {'Aktif' if USE_STORE_NOTIFICATION else 'Pasif'}")
    print(f"   📌 Follow-Up System: {'Aktif' if USE_FOLLOW_UP else 'Pasif'}")
    print(f"   🧠 Intent Analyzer: {'Aktif' if USE_INTENT_ANALYZER else 'Pasif'}")
    print("=" * 60)
    uvicorn.run(app, host="0.0.0.0", port=7860)