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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
# %%
import os
import uuid
import sqlite3
import datetime
import json
import re
import time
from typing import Dict, Any, List, Tuple, Optional
import hashlib

import pandas as pd
from groq import Groq
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings

# %%
# 0. Global config
DB_PATH = "olist.db"
DATA_DIR = "data"

# Groq Model
GROQ_MODEL_NAME = "llama-3.3-70b-versatile"

GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY not found.")

groq_client = Groq(api_key=GROQ_API_KEY)

# Embedding model
EMBED_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"

# Logging paths
PROMPT_LOG_PATH = "prompt_logs.txt"
RUN_LOG_PATH = "run_logs.txt"

# %%
# SINGLE, CORRECT, PERSISTENT CHROMA CLIENT

import os
import chromadb
from chromadb.config import Settings

CHROMA_PERSIST_DIR = os.path.abspath("./chroma_data")
os.makedirs(CHROMA_PERSIST_DIR, exist_ok=True)

_CHROMA_CLIENT = None

def get_chroma_client():
    global _CHROMA_CLIENT
    if _CHROMA_CLIENT is None:
        _CHROMA_CLIENT = chromadb.PersistentClient(
            path=CHROMA_PERSIST_DIR,
            settings=Settings(
                anonymized_telemetry=False,
            ),
        )
    return _CHROMA_CLIENT


# %%


# %%
# 1. Logging helpers


def log_prompt(tag: str, prompt: str) -> None:
    """

    Append the full prompt to a log file, with a tag and timestamp.

    """
    timestamp = datetime.datetime.now().isoformat(timespec="seconds")
    header = f"\n\n================ {tag} @ {timestamp} ================\n"
    with open(PROMPT_LOG_PATH, "a", encoding="utf-8") as f:
        f.write(header)
        f.write(prompt)
        f.write("\n================ END PROMPT ================\n")


def log_run_event(tag: str, content: str) -> None:
    """

    Append model response, final SQL, and error info into a run log.

    """
    timestamp = datetime.datetime.now().isoformat(timespec="seconds")
    header = f"\n\n================ {tag} @ {timestamp} ================\n"
    with open(RUN_LOG_PATH, "a", encoding="utf-8") as f:
        f.write(header)
        f.write(content)
        f.write("\n================ END EVENT ================\n")



# %%
# 2. Feedback table + helpers

def init_feedback_table(conn: sqlite3.Connection) -> None:
    """

    Create (or upgrade) a table to capture user feedback on model answers.

    """
    conn.execute("""

    CREATE TABLE IF NOT EXISTS user_feedback (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        created_at TEXT NOT NULL,

        question TEXT NOT NULL,

        generated_sql TEXT,

        model_answer TEXT,

        rating TEXT CHECK(rating IN ('good','bad')) NOT NULL,

        comment TEXT,

        corrected_sql TEXT

    )

    """)
    conn.commit()


def record_feedback(

    conn: sqlite3.Connection,

    question: str,

    generated_sql: str,

    model_answer: str,

    rating: str,                     # "good" or "bad"

    comment: Optional[str] = None,

    corrected_sql: Optional[str] = None,

) -> None:
    """

    Store user feedback about a particular model answer / SQL query.

    If corrected_sql is provided, it is treated as an external correction.

    """
    rating = rating.lower()
    if rating not in ("good", "bad"):
        raise ValueError("rating must be 'good' or 'bad'")

    ts = datetime.datetime.now().isoformat(timespec="seconds")
    conn.execute(
        """

        INSERT INTO user_feedback (

            created_at, question, generated_sql, model_answer,

            rating, comment, corrected_sql

        )

        VALUES (?, ?, ?, ?, ?, ?, ?)

        """,
        (ts, question, generated_sql, model_answer, rating, comment, corrected_sql),
    )
    conn.commit()


def get_last_feedback_for_question(

    conn: sqlite3.Connection,

    question: str,

) -> Optional[Dict[str, Any]]:
    """

    Return the most recent feedback row for this question (if any).

    """
    cur = conn.cursor()
    cur.execute(
        """

        SELECT created_at, generated_sql, model_answer,

               rating, comment, corrected_sql

        FROM user_feedback

        WHERE question = ?

        ORDER BY created_at DESC

        LIMIT 1

        """,
        (question,),
    )
    row = cur.fetchone()
    if not row:
        return None

    return {
        "created_at": row[0],
        "generated_sql": row[1],
        "model_answer": row[2],
        "rating": row[3],
        "comment": row[4],
        "corrected_sql": row[5],
    }



# %%
# 3. Database setup (from CSVs)   

def init_db() -> sqlite3.Connection:
    """

    Load all CSVs from the data/ folder into a local SQLite DB.

    Table names are derived from file names (without .csv).

    """
    conn = sqlite3.connect(DB_PATH, check_same_thread=False)

    csv_files = [
        "olist_customers_dataset.csv",
        "olist_orders_dataset.csv",
        "olist_order_items_dataset.csv",
        "olist_products_dataset.csv",
        "olist_order_reviews_dataset.csv",
        "olist_order_payments_dataset.csv",
        "product_category_name_translation.csv",
        "olist_sellers_dataset.csv",
        "olist_geolocation_dataset.csv",
    ]

    for fname in csv_files:
        path = os.path.join(DATA_DIR, fname)
        print(path)
        if not os.path.exists(path):
            print(f"CSV not found: {path} - skipping")
            continue

        table_name = os.path.splitext(fname)[0]
        print(f"Loading {path} into table {table_name}...")
        df = pd.read_csv(path)
        df.to_sql(table_name, conn, if_exists="replace", index=False)

    
    init_feedback_table(conn)

    return conn


conn = init_db()



# %%
# 4. Manual docs for Olist tables

OLIST_DOCS: Dict[str, Dict[str, Any]] = {
    "olist_customers_dataset": {
        "description": "Customer master data, one row per customer_id (which can change over time for the same end-user).",
        "columns": {
            "customer_id": "Primary key for this table. Unique technical identifier for a customer at a point in time. Used to join with olist_orders_dataset.customer_id.",
            "customer_unique_id": "Stable unique identifier for the end-user. A single customer_unique_id can map to multiple customer_id records over time.",
            "customer_zip_code_prefix": "Customer ZIP/postal code prefix. Used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
            "customer_city": "Customer's city as captured at the time of the order or registration.",
            "customer_state": "Customer's state (two-letter Brazilian state code, e.g. SP, RJ)."
        }
    },
    "olist_orders_dataset": {
        "description": "Customer orders placed on the Olist marketplace, one row per order.",
        "columns": {
            "order_id": "Primary key. Unique identifier for each order. Used to join with items, payments, and reviews.",
            "customer_id": "Foreign key to olist_customers_dataset.customer_id indicating who placed the order.",
            "order_status": "Current lifecycle status of the order (e.g. created, shipped, delivered, canceled, unavailable).",
            "order_purchase_timestamp": "Timestamp when the customer completed the purchase (event time for order placement).",
            "order_approved_at": "Timestamp when the payment was approved by the system or financial gateway.",
            "order_delivered_carrier_date": "Timestamp when the order was handed over by the seller to the carrier/logistics provider.",
            "order_delivered_customer_date": "Timestamp when the carrier reported the order as delivered to the final customer.",
            "order_estimated_delivery_date": "Estimated delivery date promised to the customer at checkout."
        }
    },
    "olist_order_items_dataset": {
        "description": "Order line items, one row per product per order.",
        "columns": {
            "order_id": "Foreign key to olist_orders_dataset.order_id. Multiple order_items can belong to the same order.",
            "order_item_id": "Sequential item number within an order (1, 2, 3, ...). Uniquely identifies a line inside an order.",
            "product_id": "Foreign key to olist_products_dataset.product_id representing the purchased product.",
            "seller_id": "Foreign key to olist_sellers_dataset.seller_id representing the seller that fulfilled this item.",
            "shipping_limit_date": "Deadline for the seller to hand the item over to the carrier for shipping.",
            "price": "Item price paid by the customer for this line (in BRL, not including freight).",
            "freight_value": "Freight (shipping) cost attributed to this line item (in BRL)."
        }
    },
    "olist_products_dataset": {
        "description": "Product catalog with physical and category attributes, one row per product.",
        "columns": {
            "product_id": "Primary key. Unique identifier for each product. Used to join with olist_order_items_dataset.product_id.",
            "product_category_name": "Product category name in Portuguese. Join to product_category_name_translation.product_category_name for English.",
            "product_name_lenght": "Number of characters in the product name (field name misspelled as 'lenght' in the original dataset).",
            "product_description_lenght": "Number of characters in the product description (also misspelled as 'lenght').",
            "product_photos_qty": "Number of product images associated with the listing.",
            "product_weight_g": "Product weight in grams.",
            "product_length_cm": "Product length in centimeters (package dimension).",
            "product_height_cm": "Product height in centimeters (package dimension).",
            "product_width_cm": "Product width in centimeters (package dimension)."
        }
    },
    "olist_order_reviews_dataset": {
        "description": "Post-purchase customer reviews and satisfaction scores, one row per review.",
        "columns": {
            "review_id": "Primary key. Unique identifier for each review record.",
            "order_id": "Foreign key to olist_orders_dataset.order_id for the reviewed order.",
            "review_score": "Star rating given by the customer on a 1–5 scale (5 = very satisfied, 1 = very dissatisfied).",
            "review_comment_title": "Optional short text title or summary of the review.",
            "review_comment_message": "Optional detailed free-text comment describing the customer experience.",
            "review_creation_date": "Date when the customer created the review.",
            "review_answer_timestamp": "Timestamp when Olist or the seller responded to the review (if applicable)."
        }
    },
    "olist_order_payments_dataset": {
        "description": "Payments associated with orders, one row per payment record (order can have multiple payments).",
        "columns": {
            "order_id": "Foreign key to olist_orders_dataset.order_id.",
            "payment_sequential": "Sequence number for multiple payments of the same order (1 for first payment, 2 for second, etc.).",
            "payment_type": "Payment method used (e.g. credit_card, boleto, voucher, debit_card).",
            "payment_installments": "Number of installments chosen by the customer for this payment.",
            "payment_value": "Monetary amount paid in this payment record (in BRL)."
        }
    },
    "product_category_name_translation": {
        "description": "Lookup table mapping Portuguese product category names to English equivalents.",
        "columns": {
            "product_category_name": "Product category name in Portuguese as used in olist_products_dataset.",
            "product_category_name_english": "Translated product category name in English."
        }
    },
    "olist_sellers_dataset": {
        "description": "Seller master data, one row per seller operating on the Olist marketplace.",
        "columns": {
            "seller_id": "Primary key. Unique identifier for each seller. Used to join with olist_order_items_dataset.seller_id.",
            "seller_zip_code_prefix": "Seller ZIP/postal code prefix, used to join with olist_geolocation_dataset.geolocation_zip_code_prefix.",
            "seller_city": "City where the seller is located.",
            "seller_state": "State where the seller is located (two-letter Brazilian state code)."
        }
    },
    "olist_geolocation_dataset": {
        "description": "Geolocation reference data for ZIP code prefixes in Brazil, not unique per prefix.",
        "columns": {
            "geolocation_zip_code_prefix": "ZIP/postal code prefix, used to link customers and sellers via zip code.",
            "geolocation_lat": "Latitude coordinate of the location.",
            "geolocation_lng": "Longitude coordinate of the location.",
            "geolocation_city": "City name for the location.",
            "geolocation_state": "State code for the location (two-letter Brazilian state code)."
        }
    }
}



# %%
# 5. Schema extractor + metadata YAML 

def extract_schema_metadata(connection: sqlite3.Connection) -> Dict[str, Any]:
    """

    Introspect SQLite tables, columns and foreign key relationships.

    """
    cursor = connection.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = [row[0] for row in cursor.fetchall()]

    metadata: Dict[str, Any] = {"tables": {}}

    for table in tables:
        cursor.execute(f"PRAGMA table_info('{table}')")
        cols = cursor.fetchall()

        # Manual docs for the table
        table_docs = OLIST_DOCS.get(table, {})
        table_desc: str = table_docs.get(
            "description",
            f"Table '{table}' from Olist dataset."
        )
        column_docs: Dict[str, str] = table_docs.get("columns", {})

        columns_meta: Dict[str, str] = {}
        for c in cols:
            col_name = c[1]
            col_type = c[2] or "TEXT"

            if col_name in column_docs:
                columns_meta[col_name] = column_docs[col_name]
            else:
                columns_meta[col_name] = f"Column '{col_name}' of type {col_type}"

        cursor.execute(f"PRAGMA foreign_key_list('{table}')")
        fk_rows = cursor.fetchall()
        relationships: List[str] = []
        for fk in fk_rows:
            ref_table = fk[2]
            from_col = fk[3]
            to_col = fk[4]
            relationships.append(
                f"{table}.{from_col}{ref_table}.{to_col} (foreign key)"
            )

        metadata["tables"][table] = {
            "description": table_desc,
            "columns": columns_meta,
            "relationships": relationships,
        }

    return metadata


schema_metadata = extract_schema_metadata(conn)


def build_schema_yaml(metadata: Dict[str, Any]) -> str:
    """

    Render metadata dict into a YAML-style string.

    """
    lines: List[str] = ["tables:"]
    for tname, tinfo in metadata["tables"].items():
        lines.append(f"  {tname}:")
        desc = tinfo.get("description", "").replace('"', "'")
        lines.append(f'    description: "{desc}"')
        lines.append("    columns:")
        for col_name, col_desc in tinfo.get("columns", {}).items():
            col_desc_clean = col_desc.replace('"', "'")
            lines.append(f'      {col_name}: "{col_desc_clean}"')
        rels = tinfo.get("relationships", [])
        if rels:
            lines.append("    relationships:")
            for rel in rels:
                rel_clean = rel.replace('"', "'")
                lines.append(f'      - "{rel_clean}"')
    return "\n".join(lines)


schema_yaml = build_schema_yaml(schema_metadata)



# %%
# 6. Build schema documents for RAG (taking samples from the table)

def build_schema_documents(

    connection: sqlite3.Connection,

    schema_metadata: Dict[str, Any],

    sample_rows: int = 5,

) -> Tuple[List[str], List[Dict[str, Any]]]:
    """

    Build one rich RAG document per table, using schema_metadata.



    Each document includes:

    - Table name

    - Table description

    - Columns with type + description

    - Relationships (FKs)

    - A few sample rows

    """
    cursor = connection.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = [row[0] for row in cursor.fetchall()]

    docs: List[str] = []
    metadatas: List[Dict[str, Any]] = []

    for table in tables:
        tmeta = schema_metadata["tables"][table]
        table_desc = tmeta.get("description", "")
        columns_meta = tmeta.get("columns", {})
        relationships = tmeta.get("relationships", [])

        # Use PRAGMA to get types, then enrich with descriptions
        cursor.execute(f"PRAGMA table_info('{table}')")
        cols = cursor.fetchall()

        col_lines = []
        for c in cols:
            col_name = c[1]
            col_type = c[2] or "TEXT"
            col_desc = columns_meta.get(col_name, f"Column '{col_name}' of type {col_type}")
            col_lines.append(f"- {col_name} ({col_type}): {col_desc}")

        # Sample rows
        try:
            sample_df = pd.read_sql_query(
                f"SELECT * FROM '{table}' LIMIT {sample_rows}",
                connection,
            )
            sample_text = sample_df.to_markdown(index=False)
        except Exception:
            sample_text = "(could not fetch sample rows)"

        # Relationships block
        rel_block = ""
        if relationships:
            rel_block = "Relationships:\n" + "\n".join(
                f"- {rel}" for rel in relationships
            ) + "\n"

        doc_text = (
            f"Table: {table}\n"
            f"Description: {table_desc}\n\n"
            f"Columns:\n" + "\n".join(col_lines) + "\n\n"
            f"{rel_block}\n"
            f"Example rows:\n{sample_text}\n"
        )

        docs.append(doc_text)
        metadatas.append({
            "doc_type": "table_schema",
            "table_name": table,
        })

    return docs, metadatas


# Build RAG texts + metadata
schema_docs, schema_doc_metas = build_schema_documents(conn, schema_metadata)

RAG_TEXTS: List[str] = []
RAG_METADATAS: List[Dict[str, Any]] = []

# 1) Per-table docs
RAG_TEXTS.extend(schema_docs)
RAG_METADATAS.extend(schema_doc_metas)

# 2) Global YAML as a separate doc
RAG_TEXTS.append("SCHEMA_METADATA_YAML:\n" + schema_yaml)
RAG_METADATAS.append({"doc_type": "global_schema"})


# %%
def build_store_final():
    embedding_model = HuggingFaceEmbeddings(
        model_name=EMBED_MODEL_NAME,
        encode_kwargs={"normalize_embeddings": True},
    )

    rag_store = Chroma(
        client=get_chroma_client(),
        collection_name="rag_schema_store",
        embedding_function=embedding_model,
    )

    if rag_store._collection.count() == 0:
        rag_store.add_texts(
            texts=RAG_TEXTS,
            metadatas=RAG_METADATAS,
        )

    rag_retriever = rag_store.as_retriever(
        search_kwargs={"k": 3, "filter": {"doc_type": "table_schema"}}
    )

    return rag_store, rag_retriever

# Initialize once
rag_store, rag_retriever = build_store_final()


# %%
from langchain.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings

_sql_cache_store = None
_sql_embedding_fn = None

SQL_CACHE_COLLECTION = "sql_cache_mpnet"

def get_sql_cache_store():
    global _sql_cache_store, _sql_embedding_fn

    if _sql_cache_store is not None:
        return _sql_cache_store

    if _sql_embedding_fn is None:
        _sql_embedding_fn = HuggingFaceEmbeddings(
            model_name=EMBED_MODEL_NAME,
            encode_kwargs={"normalize_embeddings": True},
        )

    _sql_cache_store = Chroma(
        client=get_chroma_client(),
        collection_name=SQL_CACHE_COLLECTION,
        embedding_function=_sql_embedding_fn,
    )

    return _sql_cache_store


# %%
def sanitize_metadata_for_chroma(metadata: dict) -> dict:
    safe = {}
    for k, v in (metadata or {}).items():
        if v is None:
            continue
        if isinstance(v, (int, float, bool)):
            safe[k] = v
        elif isinstance(v, str):
            safe[k] = v
        else:
            safe[k] = str(v)
    return safe


# %%
def normalize_question_strict(q: str) -> str:
    """

    Deterministic normalization for exact cache hits.

    """
    if not q:
        return ""
    q = q.lower().strip()
    q = re.sub(r"[^\w\s]", "", q)
    q = re.sub(r"\s+", " ", q)
    return q


# %%
# Helper: normalize question

def normalize_question_text(q: str) -> str:
    if not q:
        return ""
    q = q.strip().lower()
    q = re.sub(r"[^\w\s]", " ", q)
    q = re.sub(r"\s+", " ", q).strip()
    return q

# Helper: compute success rate
def compute_success_rate(md: dict) -> float:
    sc = md.get("success_count", 0) or 0
    tf = md.get("total_feedbacks", 0) or 0
    if tf <= 0:
        return 0.0
    return float(sc) / float(tf)

# Insert initial cache entry (no feedback yet)
def cache_sql_answer_initial(question: str, sql: str, answer_md: str, store=None, extra_metadata: dict = None):
    """

    Insert a cached entry when you run a query and want to cache it regardless of feedback.

    initial metrics: views=1, success_count=0, total_feedbacks=0, success_rate=1.0

    """
    if store is None:
        store = get_sql_cache_store()

    ident = uuid.uuid4().hex
    norm = normalize_question_text(question)
    md = {
        "id": ident,
        "normalized_question": norm,
        "sql": sql,
        "answer_md": answer_md,
        "saved_at": time.time(),
        "views": 1,
        "success_count": 0,
        "total_feedbacks": 0,
        "success_rate": 1.0,
    }
    if extra_metadata:
        md.update(extra_metadata)

    # Use store's API; 
    store.add_texts([question], metadatas=[md])
    return ident



# %%
import time
import logging
from typing import Optional, List, Dict, Any
from difflib import SequenceMatcher

_logger = logging.getLogger(__name__)

# -------------------------------------------------------------------------
# Utility helpers
# -------------------------------------------------------------------------

def _now_ts() -> float:
    return time.time()

def similarity_score(a: str, b: str) -> float:
    return SequenceMatcher(None, (a or ""), (b or "")).ratio()

# -------------------------------------------------------------------------
# Persist helper 
# -------------------------------------------------------------------------
def langchain_upsert(

    store,

    text: str,

    metadata: dict,

    cache_id: str,

):
    safe_md = sanitize_metadata_for_chroma(metadata)

    try:
        store.add_texts(
            texts=[text],
            metadatas=[safe_md],
            ids=[cache_id],
        )
    except TypeError:
        store.add_texts(
            texts=[text],
            metadatas=[safe_md],
        )


# -------------------------------------------------------------------------
# Cache insert / update
# -------------------------------------------------------------------------
def cache_sql_answer_dedup(

    question: str,

    sql: str,

    answer_md: str,

    metadata: dict,

    store,

):
    norm_q_semantic = normalize_text(question)
    norm_q_exact = normalize_question_strict(question)

    cache_id = generate_cache_id(question, sql)
    now = _now_ts()

    md = {
        # identity
        "cache_id": cache_id,
        "sql": sql,
        "answer_md": answer_md,

        # exact match key
        "normalized_question": norm_q_exact,

        # timestamps
        "saved_at": metadata.get("saved_at", now),
        "last_updated_at": now,
        "last_viewed_at": metadata.get("last_viewed_at", 0),

        # metrics
        "good_count": metadata.get("good_count", 0),
        "bad_count": metadata.get("bad_count", 0),
        "total_feedbacks": metadata.get("total_feedbacks", 0),
        "success_rate": metadata.get("success_rate", 0.5),
        "views": metadata.get("views", 0),
    }

    langchain_upsert(
        store=store,
        text=norm_q_semantic,   # semantic vector
        metadata=md,
        cache_id=cache_id,
    )

    return {
        "question": question,
        "sql": sql,
        "answer_md": answer_md,
        "metadata": md,
    }

# -------------------------------------------------------------------------
# Find exact cached entry (question + SQL)
# -------------------------------------------------------------------------

def find_cached_doc_by_sql(question: str, sql: str, store):
    cache_id = generate_cache_id(question, sql)
    coll = getattr(store, "_collection", None)

    if coll and hasattr(coll, "get"):
        try:
            res = coll.get(ids=[cache_id])
            if res and res.get("metadatas"):
                md = res["metadatas"][0]
                return {
                    "id": cache_id,
                    "question": question,
                    "sql": md.get("sql"),
                    "answer_md": md.get("answer_md"),
                    "metadata": md,
                }
        except Exception:
            pass

    return None

# -------------------------------------------------------------------------
# Retrieve cached answers ranked primarily by success rate
# -------------------------------------------------------------------------

import re
import unicodedata


def normalize_text(text: str) -> str:
    if not text:
        return ""
    text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
    text = text.lower()
    text = re.sub(r"[^\w\s]", " ", text)
    text = re.sub(r"\s+", " ", text).strip()
    return text

import hashlib

def generate_cache_id(question: str, sql: str) -> str:
    q = normalize_text(question)
    s = (sql or "").strip()
    key = f"{q}||{s}".encode("utf-8")
    return hashlib.sha1(key).hexdigest()


def rank_cached_candidates(candidates: list[dict]) -> dict:
    """

    Deterministic quality-first ranking.

    """
    candidates.sort(
        key=lambda c: (
            -float(c["metadata"].get("success_rate", 0.5)),
            -int(c["metadata"].get("good_count", 0)),
            int(c["metadata"].get("bad_count", 0)),
            -float(c["metadata"].get("last_updated_at", 0)),
        )
    )
    return candidates[0]



def retrieve_exact_cached_sql(question: str, store):
    """

    Exact question match, but still quality-ranked.

    """
    norm_q = normalize_question_strict(question)
    coll = store._collection

    try:
        res = coll.get(where={"normalized_question": norm_q})
        if not res or not res.get("metadatas"):
            return None

        candidates = []
        for md in res["metadatas"]:
            candidates.append({
                "matched_question": question,
                "sql": md["sql"],
                "answer_md": md.get("answer_md", ""),
                "distance": 0.0,
                "metadata": md,
            })

        return rank_cached_candidates(candidates)

    except Exception:
        return None


def retrieve_best_cached_sql(

    question: str,

    store,

    max_distance: float = 0.25,

):
    norm_q = normalize_text(question)
    results = store.similarity_search_with_score(norm_q, k=20)

    candidates = []

    for doc, score in results:
        distance = float(score)
        if distance > max_distance:
            continue

        md = doc.metadata or {}
        if "sql" not in md:
            continue

        candidates.append({
            "matched_question": doc.page_content,
            "sql": md["sql"],
            "answer_md": md.get("answer_md", ""),
            "distance": distance,
            "metadata": md,

            # ranking signals (FORCED numeric)
            "success_rate": float(md.get("success_rate", 0.5)),
            "good": int(md.get("good_count", 0)),
            "bad": int(md.get("bad_count", 0)),
            "views": int(md.get("views", 0)),
            "last_updated": float(md.get("last_updated_at", 0)),
        })

    if not candidates:
        return None

    # QUALITY-FIRST RANKING
    candidates.sort(
    key=lambda c: (
        -c["success_rate"],
        -c["good"],
        c["bad"],
        c["distance"],
        -c["last_updated"],
    )
)


    return candidates[0]

# -------------------------------------------------------------------------
# Increment views
# -------------------------------------------------------------------------

def increment_cache_views(metadata: dict, store):
    if not metadata:
        return False

    cache_id = metadata.get("cache_id")
    if not cache_id:
        return False

    md = dict(metadata)
    md["views"] = int(md.get("views", 0)) + 1
    md["last_viewed_at"] = _now_ts()
    md["last_updated_at"] = _now_ts()
    md["saved_at"] = md.get("saved_at", _now_ts())

    try:
        langchain_upsert(
            store=store,
            text=normalize_text(md.get("normalized_question", "")),
            metadata=md,
            cache_id=cache_id,
        )
        return True
    except Exception:
        _logger.exception("increment_cache_views failed")
        return False


# Update metrics on feedback
def update_cache_on_feedback(

    question: str,

    original_doc_md: dict,

    user_marked_good: bool,

    llm_corrected_sql: str | None,

    llm_corrected_answer_md: str | None,

    store,

):
    if not original_doc_md:
        return

    md = dict(original_doc_md["metadata"])
    cache_id = md["cache_id"]

    # ---- feedback counts ----
    if user_marked_good:
        md["good_count"] = md.get("good_count", 0) + 1
    else:
        md["bad_count"] = md.get("bad_count", 0) + 1

    md["total_feedbacks"] = md.get("total_feedbacks", 0) + 1
    md["success_rate"] = (
        md["good_count"] / md["total_feedbacks"]
        if md["total_feedbacks"] > 0 else 0.5
    )

    # ---- timestamps ----
    md["saved_at"] = md.get("saved_at", _now_ts())   # preserve
    md["last_updated_at"] = _now_ts()

    langchain_upsert(
        store=store,
        text=normalize_text(question),
        metadata=md,
        cache_id=cache_id,
    )

    # -------------------------
    # Corrected SQL --> NEW ENTRY
    # -------------------------
    if llm_corrected_sql and llm_corrected_answer_md:
        cache_sql_answer_dedup(
            question=question,
            sql=llm_corrected_sql,
            answer_md=llm_corrected_answer_md,
            metadata={
                "good_count": 1,
                "bad_count": 0,
                "total_feedbacks": 1,
                "success_rate": 1.0,
                "views": 0,
                "saved_at": _now_ts(),
            },
            store=store,
        )


# %%
# ### 8. Groq LLM via LangChain

from langchain_groq import ChatGroq
import re
import gradio as gr

llm = ChatGroq(model=GROQ_MODEL_NAME, groq_api_key=GROQ_API_KEY)

# %%
def get_rag_context(question: str) -> str:
    """

    Retrieve the most relevant schema documents for the question.

    """
    docs = rag_retriever.invoke(question)
    return "\n\n---\n\n".join(d.page_content for d in docs)

def clean_sql(sql: str) -> str:
    sql = sql.strip()
    if "```" in sql:
        sql = sql.replace("```sql", "").replace("```", "").strip()
    return sql

def extract_sql_from_markdown(text: str) -> str:
    """

    Extract the first ```sql ... ``` block from LLM output.

    If not found, return the whole text.

    """
    match = re.search(r"```sql(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
    if match:
        return match.group(1).strip()
    return text.strip()

def extract_explanation_after_marker(text: str, marker: str = "EXPLANATION:") -> str:
    """

    After the given marker, return the rest of the text as explanation.

    """
    idx = text.upper().find(marker.upper())
    if idx == -1:
        return text.strip()
    return text[idx + len(marker):].strip()

# 6b. General / descriptive questions

GENERAL_DESC_KEYWORDS = [
    "what is this dataset about",
    "what is this data about",
    "describe this dataset",
    "describe the dataset",
    "dataset overview",
    "data overview",
    "summary of the dataset",
    "explain this dataset",
]


def is_general_question(question: str) -> bool:
    """

    Detect high-level descriptive questions where we should answer

    directly from schema context instead of generating SQL.

    """
    q = question.lower().strip()
    return any(key in q for key in GENERAL_DESC_KEYWORDS)


def answer_general_question(question: str) -> str:
    """

    Use the RAG schema docs to generate a rich, high-level description

    of the Olist dataset for conceptual questions.

    """
    rag_context = get_rag_context(question)

    system_instructions = """

You are a data documentation expert.



You will be given:

- Schema documentation for the Olist dataset (tables, descriptions, columns, relationships).

- A high-level user question like "what is this dataset about?".



Your job:

- Write a clear, structured overview of the dataset.

- Explain the main entities (customers, orders, items, products, sellers, payments, reviews, geolocation).

- Mention typical analysis use-cases (delivery performance, customer behavior, seller performance, product/category analysis, etc.).

- Target a non-technical person.



Do NOT write SQL. Answer in Markdown.

"""

    prompt = (
        system_instructions
        + "\n\n=== SCHEMA CONTEXT ===\n"
        + rag_context
        + "\n\n=== USER QUESTION ===\n"
        + question
        + "\n\nDetailed dataset overview:"
    )

    log_prompt("GENERAL_DATASET_QUESTION", prompt)

    response = llm.invoke(prompt)
    log_run_event("RAW_MODEL_RESPONSE_GENERAL_DATASET", response.content)

    return response.content.strip()

# %%
# ### 9. SQL execution / validation

def execute_sql(sql: str, connection: sqlite3.Connection) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
    """

    Execute SQL on SQLite and return a DataFrame, else return an error.

    """
    try:
        df = pd.read_sql_query(sql, connection)
        return df, None
    except Exception as e:
        return None, str(e)

def validate_sql(sql: str, connection: sqlite3.Connection) -> Tuple[bool, Optional[str]]:
    """

    Basic SQL validator:

    - Uses EXPLAIN QUERY PLAN to detect syntax or schema issues.

    """
    try:
        cursor = connection.cursor()
        cursor.execute(f"EXPLAIN QUERY PLAN {sql}")
        return True, None
    except Exception as e:
        return False, str(e)

# %%
# ### 10. SQL Generation + Repair with LLM (feedback-aware)

def build_sql_review_prompt(

    question: str,

    generated_sql: str,

    user_feedback_comment: str,

    rag_context: str,

) -> str:
    """

    Prompt to let the LLM compare its SQL with the user's feedback,

    decide if the join/logic is wrong, and produce a corrected SQL + explanation.



    We explicitly allow the model to say:

    - "query was already correct, user mistaken" OR

    - "query was wrong, here is the fix".

    """
    prompt = f"""

You previously generated the following SQL for a SQLite database:



```sql

{generated_sql}



The user now says this query is WRONG and provided this feedback:

"{user_feedback_comment}"



TASKS:



    Compare the SQL with the database schema (given in the context) and the user's feedback.



    Decide whether the query is actually correct or incorrect.

    Make sure that the user clearly specifies why they think it is incorrect. 

    It can be if they are unsatisfied with the numbers, or the logic is incorrect, or SQL is invalid etc.

    If any reason is not clearly specified, return the previous result as it is.



        If it is already correct, keep it unchanged and explain why the user might be mistaken.



        If it is incorrect (e.g., wrong joins, missing filters, wrong aggregation), fix it.



        Produce a corrected SQL query that better answers the question.



        If the original query is already correct, just repeat the same SQL.



        Explain in a few sentences WHO is correct (you or the user) and WHY.



DATABASE SCHEMA (partial, from RAG):

{rag_context}



User question:

{question}



Return your answer in this format:



CORRECTED_SQL:



-- your (possibly unchanged) SQL here

SELECT ...



EXPLANATION:

Your explanation here, clearly stating whether:



    the original query was correct or not, and



    how your corrected SQL addresses the issue (or why it didn't need changes).

    """
    return prompt.strip()


# %%
# Review and Correct SQL based on Feedback

def review_and_correct_sql_with_llm(

    question: str,

    generated_sql: str,

    user_feedback_comment: str,

    rag_context: str,

) -> Tuple[str, str]:
    """

    Ask the LLM to compare its SQL with user's feedback, decide what is wrong (or not),

    and propose a corrected SQL (possibly unchanged) + explanation.



    Returns:

        corrected_sql, explanation

    """
    prompt = build_sql_review_prompt(
        question=question,
        generated_sql=generated_sql,
        user_feedback_comment=user_feedback_comment,
        rag_context=rag_context,
    )

    log_prompt("SQL_REVIEW_FEEDBACK", prompt)
    response = llm.invoke(prompt)
    log_run_event("RAW_MODEL_RESPONSE_SQL_REVIEW", response.content)

    # Try to extract SQL; if none, fall back to original
    extracted_sql = extract_sql_from_markdown(response.content)
    corrected_sql = clean_sql(extracted_sql) if extracted_sql else generated_sql
    if not corrected_sql.strip():
        corrected_sql = generated_sql

    explanation = extract_explanation_after_marker(
        response.content,
        marker="EXPLANATION:",
    )
    return corrected_sql, explanation

# %%
# Generate SQL

def generate_sql(question: str, rag_context: str) -> str:
    """

    Generate SQL using LLM, but also pull in any past user feedback

    (corrected SQL) for this question as external guidance.

    """
    # External correction from past feedback, if any
    last_fb = get_last_feedback_for_question(conn, question)
    if last_fb and last_fb.get("corrected_sql"):
        previous_feedback_block = f"""

EXTERNAL USER FEEDBACK FROM PAST RUNS:



Previous generated SQL:

{last_fb['generated_sql']}



Corrected SQL (preferred reference):

{last_fb['corrected_sql']}



User comment & prior explanation:

{last_fb.get('comment') or '(none)'}



You must avoid repeating the same mistake and should follow the logic of

the corrected SQL when appropriate, while still reasoning from the schema.

"""
    else:
        previous_feedback_block = ""

    system_instructions = f"""

You are a senior data analyst writing SQL for a SQLite database.



You will be given:



- A description of available tables, columns, and relationships (schema + YAML metadata).

- A natural language question from the user.



Your job:



- Write ONE valid SQLite SQL query that answers the question.

- ONLY use tables and columns that exist in the schema_context.

- Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions.

- Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.

- Always use floating-point division for percentage calculations using 1.0 * numerator / denominator,

  and round to 2 decimals when appropriate.



{previous_feedback_block}

"""

    prompt = (
        system_instructions
        + "\n\n=== RAG CONTEXT ===\n"
        + rag_context
        + "\n\n=== USER QUESTION ===\n"
        + question
        + "\n\nSQL query:"
    )

    log_prompt("SQL_GENERATION", prompt)
    response = llm.invoke(prompt)
    log_run_event("RAW_MODEL_RESPONSE_SQL_GENERATION", response.content)

    sql = clean_sql(response.content)
    return sql


# %%
# Repair SQL

def repair_sql(

    question: str,

    rag_context: str,

    bad_sql: str,

    error_message: str,

) -> str:
    """

    Ask the LLM to correct a failing SQL query.

    """
    system_instructions = """

You are a senior data analyst fixing an existing SQL query for a SQLite database.



You will be given:



- Schema context (tables, columns, relationships).

- The user's question.

- A previously generated SQL query that failed.

- The SQLite error message.



Your job:



- Diagnose why the query failed.

- Rewrite ONE valid SQLite SQL query that answers the question.

- ONLY use tables and columns that exist in the schema_context.

- Use correct JOINS (Left, Right, Inner, Outer, Full Outer etc.) with ON conditions.

- Do not use DROP, INSERT, UPDATE, DELETE or other destructive operations.

- Return ONLY the corrected SQL query, no explanation or markdown.

"""

    prompt = (
        system_instructions
        + "\n\n=== RAG CONTEXT ===\n"
        + rag_context
        + "\n\n=== USER QUESTION ===\n"
        + question
        + "\n\n=== PREVIOUS (FAILING) SQL ===\n"
        + bad_sql
        + "\n\n=== SQLITE ERROR ===\n"
        + error_message
        + "\n\nCorrected SQL query:"
    )

    log_prompt("SQL_REPAIR", prompt)
    response = llm.invoke(prompt)
    log_run_event("RAW_MODEL_RESPONSE_SQL_REPAIR", response.content)

    sql = clean_sql(response.content)
    return sql


# %%
### 11. Result summarization

def summarize_results(

    question: str,

    sql: str,

    df: Optional[pd.DataFrame],

    rag_context: str,

    error: Optional[str] = None,

) -> str:
    """

    Ask the LLM to produce a concise, human-readable answer.

    """
    system_instructions = """

    You are a senior data analyst.



    You will be given:



    The user's question.

    The final SQL that was executed.

    A small preview of the query result (as a Markdown table, if available).

    Optional error information if the query failed.



    Your job:



    Provide a clear, concise answer in Markdown.

    If the result is numeric / aggregated, explain what it means in business terms.

    If there was an error, explain it simply and suggest how the user could rephrase.

    Do NOT show raw SQL unless it is helpful to the user.

    """

    # Build a markdown table preview if we have data
    if df is not None and not df.empty:
        preview_rows = min(len(df), 50)
        df_preview_md = df.head(preview_rows).to_markdown(index=False)
    else:
        df_preview_md = "(no rows returned)"

    prompt = (
        system_instructions
        + "\n\n=== USER QUESTION ===\n"
        + question
        + "\n\n=== EXECUTED SQL ===\n"
        + sql
        + "\n\n=== QUERY RESULT PREVIEW ===\n"
        + df_preview_md
        + "\n\n=== RAG CONTEXT (schema) ===\n"
        + rag_context
    )

    if error:
        prompt += "\n\n=== ERROR ===\n" + error

    # Logging helpers assumed to exist
    log_prompt("RESULT_SUMMARY", prompt)

    response = llm.invoke(prompt)
    log_run_event("RAW_MODEL_RESPONSE_RESULT_SUMMARY", response.content)

    return response.content.strip()


# %%
def backend_pipeline(question: str):
    """

    STRICT cache-first backend.



    Priority:

      1. Exact question cache hit

      2. Best semantic cache hit

      3. LLM fallback

    """

    # ------------------------------------------------------------------
    # Guards
    # ------------------------------------------------------------------
    if not question or not question.strip():
        return (
            "Please type a question.",
            pd.DataFrame(),
            "",
            "",
            "",
            "",
            pd.DataFrame(),
            [],
            [],
            False,
            4,
            "**Feedback attempts remaining: 4**",
            gr.update(value="", visible=False),
        )

    attempts_left = 4
    attempts_text = f"**Feedback attempts remaining: {attempts_left}**"

    # ------------------------------------------------------------------
    # General / descriptive questions
    # ------------------------------------------------------------------
    if is_general_question(question):
        overview_md = answer_general_question(question)
        return (
            overview_md,
            pd.DataFrame(),
            "",
            "",
            question,
            overview_md,
            pd.DataFrame(),
            [],
            [],
            False,
            attempts_left,
            attempts_text,
            gr.update(value="", visible=False),
        )

    store = get_sql_cache_store()

    # ------------------------------------------------------------------
    # STEP 0A: EXACT CACHE LOOKUP (deterministic)
    # ------------------------------------------------------------------
    cached = retrieve_exact_cached_sql(question, store)

    # ------------------------------------------------------------------
    # STEP 0B: SEMANTIC CACHE LOOKUP (ranked)
    # ------------------------------------------------------------------
    if cached is None:
        cached = retrieve_best_cached_sql(
            question=question,
            store=store,
            max_distance=0.25,
        )

    # ------------------------------------------------------------------
    # CACHE HIT PATH
    # ------------------------------------------------------------------
    if cached:
        try:
            increment_cache_views(cached["metadata"], store=store)
        except Exception:
            pass

        rag_context = get_rag_context(question)

        header = (
            "### Cache Hit\n"
            f"- **Matched question:** \"{cached['matched_question']}\"\n"
            f"- **Success rate:** {cached['metadata'].get('success_rate', 0.5):.2f}\n"
            f"- **Similarity distance:** {cached['distance']:.4f}\n\n"
            "---\n\n"
        )

        answer_md = header + (cached.get("answer_md") or "")

        try:
            df, exec_error = execute_sql(cached["sql"], conn)
            if exec_error:
                df = pd.DataFrame()
                answer_md += f"\n\n Error re-running cached SQL: `{exec_error}`"
        except Exception as e:
            df = pd.DataFrame()
            answer_md += f"\n\n Exception re-running cached SQL: `{e}`"

        md = cached["metadata"]

        stats_md = (
            f"**Cached entry stats**\n\n"
            f"- **Success rate:** {md.get('success_rate', 0.5):.2f}  \n"
            f"- **Total feedbacks:** {md.get('total_feedbacks', 0)}  \n"
            f"- **Good / Bad:** {md.get('good_count', 0)} / {md.get('bad_count', 0)}  \n"
            f"- **Views:** {md.get('views', 0)}  \n"
            f"- **Saved at:** "
            f"{datetime.datetime.fromtimestamp(md.get('saved_at')).strftime('%Y-%m-%d %H:%M') if md.get('saved_at') else 'unknown'}  \n"
            f"- **Last updated:** "
            f"{datetime.datetime.fromtimestamp(md.get('last_updated_at')).strftime('%Y-%m-%d %H:%M') if md.get('last_updated_at') else 'unknown'}\n\n"
            f"**SQL preview:**\n\n```sql\n{cached['sql']}\n```\n"
        )

        return (
            answer_md,
            df,
            cached["sql"],
            rag_context,
            question,
            answer_md,
            df,
            [],
            [],
            False,
            attempts_left,
            attempts_text,
            gr.update(value=stats_md, visible=True),
        )

    # ------------------------------------------------------------------
    # STEP 1: LLM FLOW (NO CACHE HIT)
    # ------------------------------------------------------------------
    rag_context = get_rag_context(question)

    sql = generate_sql(question, rag_context)
    original_sql = sql

    is_valid, validation_error = validate_sql(sql, conn)
    repaired = False

    if not is_valid and validation_error:
        repaired_sql = repair_sql(question, rag_context, sql, validation_error)
        repaired_valid, repaired_error = validate_sql(repaired_sql, conn)
        if repaired_valid:
            sql = repaired_sql
            repaired = True
            validation_error = None
        else:
            validation_error = repaired_error or validation_error

    df, exec_error = (None, None)
    if not validation_error:
        df, exec_error = execute_sql(sql, conn)
    else:
        exec_error = validation_error

    summary_text = summarize_results(
        question=question,
        sql=sql,
        df=df,
        rag_context=rag_context,
        error=exec_error,
    )

    sql_status = []
    if exec_error:
        sql_status.append(f"**Error:** `{exec_error}`")
    else:
        sql_status.append("Query ran successfully.")
    if repaired:
        sql_status.append("_Note: SQL was auto-repaired._")

    sql_status.append("\n**Final SQL used:**\n")
    sql_status.append(f"```sql\n{sql}\n```")

    answer_md = summary_text + "\n\n---\n\n" + "\n".join(sql_status)
    df_preview = df if df is not None and exec_error is None else pd.DataFrame()

    # ------------------------------------------------------------------
    # STEP 2: CACHE LLM RESULT (ALWAYS)
    # ------------------------------------------------------------------
    try:
        cache_sql_answer_dedup(
            question=question,
            sql=sql,
            answer_md=answer_md,
            metadata={
                "good_count": 0,
                "bad_count": 0,
                "total_feedbacks": 0,
                "success_rate": 0.5,
                "views": 1,
                "saved_at": _now_ts(),
            },
            store=store,
        )
    except Exception:
        _logger.exception("backend_pipeline: failed to cache LLM result")

    return (
        answer_md,
        df_preview,
        sql,
        rag_context,
        question,
        answer_md,
        df_preview,
        [],
        [],
        False,
        attempts_left,
        attempts_text,
        gr.update(value="", visible=False),
    )


# %%
def _looks_like_sql(text: str) -> bool:
    """Quick heuristic: does text contain SQL keywords / SELECT ?"""
    if not text:
        return False
    return bool(re.search(r"\bselect\b|\bfrom\b|\bwhere\b|\bjoin\b|\bgroup by\b|\border by\b", text, flags=re.I))


def is_feedback_sufficient(feedback_text: str) -> bool:
    """

    Heuristic to decide whether the user's free-text feedback is actionable.



    Returns True if:

      - length >= 20 characters AND contains a signal word (e.g., 'filter', 'year', 'should', 'instead', 'missing', 'wrong', digits),

      OR

      - it looks like SQL (user pasted corrected SQL),

      OR

      - length >= 60 characters (long feedback).

    """
    if not feedback_text:
        return False

    text = feedback_text.strip()
    if len(text) >= 60:
        return True

    if _looks_like_sql(text):
        return True

    # look for signal words that indicate specificity
    signal_words = [
        "filter", "where", "year", "month", "should", "instead", "expected",
        "wrong", "missing", "aggregate", "sum", "avg", "count", "distinct",
        "join", "left join", "inner join", "group by", "order by", "date",
        "range", "exclude", "include", "only"
    ]
    lower = text.lower()
    signals = sum(1 for w in signal_words if w in lower)
    if signals >= 1 and len(text) >= 20:
        return True

    # short hits like "numbers look off" are insufficient
    return False


def build_followup_prompt_for_user(sample_feedback: str = "") -> str:
    """

    Deterministic follow-up question to ask the user when feedback is vague.

    Returns a friendly prompt that the UI can display to the user.

    """
    base = (
        "Thanks — I need a bit more detail to act on this feedback.\n\n"
        "Please tell me one (or more) of the following so I can check and correct the result:\n\n"
        "1. Which part looks wrong — the **numbers**, the **aggregation** (sum/count/avg),\n"
        "   the **time range** (year/month), or the **filters** applied?\n"
        "2. If you expected a different number, what was the expected number (and how was it computed)?\n"
        "3. If you have a corrected SQL snippet, paste it (I can run and compare it).\n\n"
        "Examples you can copy-paste:\n"
    )
    examples = (
        "- \"I think the query should count DISTINCT customer_unique_id, not customer_id.\"\n"
        "- \"This looks off for year 2018 — I expected the count for 2018 to be ~40k.\"\n"
        "- \"Please exclude canceled orders (order_status = 'canceled').\"\n"
        "- \"SELECT COUNT(DISTINCT customer_unique_id) FROM olist_customers_dataset;\"\n"
    )
    hint = "\nIf you prefer, just paste a corrected SQL snippet and I'll run it and compare."
    prompt = base + examples + hint
    if sample_feedback:
        prompt = f"I saw your feedback: \"{sample_feedback}\"\n\n" + prompt
    return prompt



# %%
def feedback_pipeline_interactive(

    feedback_rating: str,

    feedback_comment: str,

    last_sql: str,

    last_rag_context: str,

    last_question: str,

    last_answer_md: str,

    last_df: pd.DataFrame,

    feedback_sql: str,

    attempts_left: int,

):
    rating = (feedback_rating or "").strip().lower()
    comment = (feedback_comment or "").strip()
    attempts_left = int(attempts_left or 0)

    # ---------------- Guard ----------------
    if not last_question or not last_sql:
        return (
            last_answer_md,
            last_df,
            last_sql,
            last_rag_context,
            last_question,
            last_answer_md,
            last_df,
            False,
            "",
            attempts_left,
        )

    if rating not in ("correct", "wrong"):
        return (
            last_answer_md + "\n\n Please select **Correct** or **Wrong**.",
            last_df,
            last_sql,
            last_rag_context,
            last_question,
            last_answer_md,
            last_df,
            False,
            "",
            attempts_left,
        )

    # ============================================================
    # CORRECT -> no attempt decrement
    # ============================================================
    if rating == "correct":
        original_doc = find_cached_doc_by_sql(
            last_question, last_sql, store=get_sql_cache_store()
        )

        update_cache_on_feedback(
            question=last_question,
            original_doc_md=original_doc,
            user_marked_good=True,
            llm_corrected_sql=None,
            llm_corrected_answer_md=None,
            store=get_sql_cache_store(),
        )

        record_feedback(
            conn=conn,
            question=last_question,
            generated_sql=last_sql,
            model_answer=last_answer_md,
            rating="good",
            comment=comment or None,
            corrected_sql=None,
        )

        return (
            last_answer_md + "\n\n **Feedback recorded as GOOD.**",
            last_df,
            last_sql,
            last_rag_context,
            last_question,
            last_answer_md,
            last_df,
            False,
            "",
            attempts_left,
        )

    # ============================================================
    #  WRONG -> decrement immediately
    # ============================================================
    attempts_left = max(0, attempts_left - 1)

    # ============================================================
    #  Attempts exhausted → FORCE LLM
    # ============================================================
    if attempts_left == 0:
        comment = comment or "User marked result as wrong."

    # ============================================================
    # Insufficient feedback -> FOLLOW-UP (only if attempts remain)
    # ============================================================
    if attempts_left > 0 and not is_feedback_sufficient(comment):
        return (
            last_answer_md,
            last_df,
            last_sql,
            last_rag_context,
            last_question,
            last_answer_md,
            last_df,
            True,   # awaiting follow-up
            build_followup_prompt_for_user(comment),
            attempts_left,
        )

    # ============================================================
    # Run LLM review
    # ============================================================
    original_doc = find_cached_doc_by_sql(
        last_question, last_sql, store=get_sql_cache_store()
    )

    corrected_sql, explanation = review_and_correct_sql_with_llm(
        question=last_question,
        generated_sql=last_sql,
        user_feedback_comment=comment,
        rag_context=last_rag_context,
    )

    corrected_sql = corrected_sql or last_sql
    df_new, exec_error = execute_sql(corrected_sql, conn)

    if exec_error:
        answer_core = summarize_results(
            question=last_question,
            sql=corrected_sql,
            df=None,
            rag_context=last_rag_context,
            error=exec_error,
        )
        df_new = pd.DataFrame()
    else:
        answer_core = summarize_results(
            question=last_question,
            sql=corrected_sql,
            df=df_new,
            rag_context=last_rag_context,
            error=None,
        )

    update_cache_on_feedback(
        question=last_question,
        original_doc_md=original_doc,
        user_marked_good=False,
        llm_corrected_sql=(
            corrected_sql if corrected_sql.strip() != last_sql.strip() else None
        ),
        llm_corrected_answer_md=(
            answer_core if corrected_sql.strip() != last_sql.strip() else None
        ),
        store=get_sql_cache_store(),
    )

    record_feedback(
        conn=conn,
        question=last_question,
        generated_sql=last_sql,
        model_answer=last_answer_md,
        rating="bad",
        comment=comment + "\n\nLLM explanation:\n" + (explanation or ""),
        corrected_sql=corrected_sql,
    )

    final_md = (
        answer_core
        + "\n\n---\n\n"
        + f"**Final corrected SQL:**\n```sql\n{corrected_sql}\n```\n\n"
        + "### LLM Review Explanation\n"
        + (explanation or "")
    )

    return (
        final_md,
        df_new,
        corrected_sql,
        last_rag_context,
        last_question,
        final_md,
        df_new,
        False,
        "",
        attempts_left,
    )


# %%
import gradio as gr
import pandas as pd

with gr.Blocks() as demo:
    gr.Markdown("# Olist Analytics Assistant (RAG + SQL + Feedback)")

    # ==================== STATE ====================
    last_sql_state = gr.State("")
    last_rag_state = gr.State("")
    last_question_state = gr.State("")
    last_answer_state = gr.State("")
    last_df_state = gr.State(pd.DataFrame())

    attempts_state = gr.State(4)
    feedback_sql_state = gr.State("") 

    # ==================== MAIN UI ====================
    with gr.Row():
        with gr.Column(scale=1):
            question_in = gr.Textbox(
                label="Your question",
                placeholder="e.g. Total number of customers",
                lines=4,
            )
            submit_btn = gr.Button("Run")
        with gr.Column(scale=2):
            answer_out = gr.Markdown()
            table_out = gr.Dataframe()

    attempts_display = gr.Markdown("**Feedback attempts remaining: 4**")
    cached_stats_md = gr.Markdown(visible=False)

    # ==================== FEEDBACK ====================
    gr.Markdown("### Feedback")

    feedback_rating = gr.Radio(
        ["Correct", "Wrong"],
        label="Is the answer correct?",
        value=None,
    )
    feedback_comment = gr.Textbox(
        label="Explain (required if Wrong)",
        lines=3,
    )
    feedback_btn = gr.Button("Submit feedback")

    # ==================== FOLLOW-UP ====================
    followup_prompt_md = gr.Markdown(visible=False)
    followup_input = gr.Textbox(
        label="Please clarify",
        visible=False,
        lines=4,
    )
    followup_submit_btn = gr.Button(
        "Submit follow-up",
        visible=False,
    )

    exhausted_md = gr.Markdown(
        "**You have exhausted your feedback attempts. Please ask a new question to continue.**",
        visible=False,
    )

    # ==================== UI HELPERS ====================
    def reset_feedback_ui():
        return (
            gr.update(value=None, visible=True),   # rating
            gr.update(value="", visible=True),     # comment
            gr.update(visible=True),               # submit
            gr.update(visible=False),              # followup input
            gr.update(visible=False),              # followup btn
            gr.update(visible=False),              # followup prompt
            gr.update(visible=False),              # exhausted
        )

    def show_followup_ui(prompt: str):
        return (
            gr.update(visible=False),              # rating
            gr.update(visible=False),              # comment
            gr.update(visible=False),              # submit
            gr.update(value="", visible=True),     # followup input
            gr.update(visible=True),               # followup btn
            gr.update(value=prompt, visible=True), # followup prompt
            gr.update(visible=False),              # exhausted
        )

    def show_exhausted_ui():
        return (
            gr.update(visible=False),  # rating
            gr.update(visible=False),  # comment
            gr.update(visible=False),  # submit
            gr.update(visible=False),  # followup input
            gr.update(visible=False),  # followup btn
            gr.update(visible=False),  # followup prompt
            gr.update(visible=True),   # exhausted
        )

    # ==================== RUN PIPELINE ====================
    def run_and_render(question):
        (
            answer_md,
            df,
            sql,
            rag,
            q,
            answer_state,
            df_state,
            _cached_matches,
            _dropdown_choices,
            _dropdown_visible,
            attempts,
            attempts_text,
            cached_stats_update,
        ) = backend_pipeline(question)

        return (
            answer_md,
            df,
            sql,
            rag,
            q,
            answer_state,
            df_state,
            attempts,
            attempts_text,
            cached_stats_update,
            *reset_feedback_ui(),
        )

    submit_btn.click(
        run_and_render,
        inputs=[question_in],
        outputs=[
            answer_out,
            table_out,
            last_sql_state,
            last_rag_state,
            last_question_state,
            last_answer_state,
            last_df_state,
            attempts_state,
            attempts_display,
            cached_stats_md,
            feedback_rating,
            feedback_comment,
            feedback_btn,
            followup_input,
            followup_submit_btn,
            followup_prompt_md,
            exhausted_md,
        ],
    )

    # ==================== FEEDBACK HANDLER ====================
    def handle_feedback(

        rating,

        comment,

        last_sql,

        last_rag,

        last_question,

        last_answer,

        last_df,

        feedback_sql,

        attempts_left,

    ):
        (
            answer_md,
            df_new,
            sql_new,
            rag_new,
            q_new,
            ans_state,
            df_state,
            awaiting_followup,
            followup_prompt,
            attempts_new,
        ) = feedback_pipeline_interactive(
            rating,
            comment,
            last_sql,
            last_rag,
            last_question,
            last_answer,
            last_df,
            feedback_sql,
            attempts_left,
        )

        attempts_md = f"**Feedback attempts remaining: {attempts_new}**"

        # Exhausted
        if attempts_new <= 0:
            ui = show_exhausted_ui()
            return (
                answer_md,
                df_new,
                sql_new,
                rag_new,
                q_new,
                ans_state,
                df_state,
                attempts_new,
                attempts_md,
                cached_stats_md,
                *ui,
            )

        # Follow-up only
        if awaiting_followup:
            ui = show_followup_ui(followup_prompt)
            return (
                answer_md,
                df_new,
                sql_new,
                rag_new,
                q_new,
                ans_state,
                df_state,
                attempts_new,
                attempts_md,
                cached_stats_md,
                *ui,
            )

        # Normal reset
        ui = reset_feedback_ui()
        return (
            answer_md,
            df_new,
            sql_new,
            rag_new,
            q_new,
            ans_state,
            df_state,
            attempts_new,
            attempts_md,
            cached_stats_md,
            *ui,
        )

    feedback_btn.click(
        handle_feedback,
        inputs=[
            feedback_rating,
            feedback_comment,
            last_sql_state,
            last_rag_state,
            last_question_state,
            last_answer_state,
            last_df_state,
            feedback_sql_state,
            attempts_state,
        ],
        outputs=[
            answer_out,
            table_out,
            last_sql_state,
            last_rag_state,
            last_question_state,
            last_answer_state,
            last_df_state,
            attempts_state,
            attempts_display,
            cached_stats_md,
            feedback_rating,
            feedback_comment,
            feedback_btn,
            followup_input,
            followup_submit_btn,
            followup_prompt_md,
            exhausted_md,
        ],
    )

    followup_submit_btn.click(
        handle_feedback,
        inputs=[
            feedback_rating,
            followup_input,
            last_sql_state,
            last_rag_state,
            last_question_state,
            last_answer_state,
            last_df_state,
            feedback_sql_state,
            attempts_state,
        ],
        outputs=[
            answer_out,
            table_out,
            last_sql_state,
            last_rag_state,
            last_question_state,
            last_answer_state,
            last_df_state,
            attempts_state,
            attempts_display,
            cached_stats_md,
            feedback_rating,
            feedback_comment,
            feedback_btn,
            followup_input,
            followup_submit_btn,
            followup_prompt_md,
            exhausted_md,
        ],
    )

# %%
if __name__ == "__main__":
    demo.launch()