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
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
# =========================================================
# ULTRA ADVANCED HYBRID NLP TO SQL ENGINE
# RULE BASED + LLM BASED + SQL SAFETY
# MISTRAL / SQLCODER READY
# =========================================================

import re
import traceback
import os

from huggingface_hub import InferenceClient
from dotenv import load_dotenv
from sqlalchemy import create_engine, text

# =========================================================
# ENVIRONMENT SETUP
# =========================================================

load_dotenv()

HF_TOKEN = os.getenv("HF_TOKEN")
DATABASE_URL = os.getenv("DATABASE_URL")

# Initialize Mistral client
client = None
try:
    if HF_TOKEN:
        client = InferenceClient(
            model="mistralai/Mistral-7B-Instruct-v0.2",
            token=HF_TOKEN
        )
        print("βœ… Mistral client initialized")
    else:
        print("⚠️ HF_TOKEN not set - LLM features disabled")
except Exception as e:
    print(f"⚠️ Mistral client error: {e}")
    client = None

# Initialize database engine
engine = None
try:
    if DATABASE_URL:
        engine = create_engine(DATABASE_URL)
        print("βœ… Database connection initialized")
    else:
        print("⚠️ DATABASE_URL not set - Database features disabled")
except Exception as e:
    print(f"⚠️ Database connection warning: {e}")
    engine = None

# =========================================================
# CONFIG
# =========================================================

USE_LLM = True

# =========================================================
# DATABASE KNOWLEDGE
# =========================================================

SCHEMA = {
    "table": "vehicle_logs",
    "columns": [
        "timestamp",
        "plate",
        "state",
        "vehicle_type",
        "vehicle_conf",
        "camera_id",
        "location",
        "date",
        "hour",
        "day"
    ]
}

VALID_STATES = {
    "tn": "TN",
    "tamil nadu": "TN",

    "ka": "KA",
    "karnataka": "KA",

    "kl": "KL",
    "kerala": "KL",

    "ap": "AP",
    "andhra": "AP",

    "ts": "TS",
    "telangana": "TS",

    "mh": "MH",
    "maharashtra": "MH",

    "dl": "DL",
    "delhi": "DL",

    "gj": "GJ",
    "gujarat": "GJ",

    "rj": "RJ",
    "rajasthan": "RJ",

    "up": "UP",
    "uttar pradesh": "UP",

    "wb": "WB",
    "west bengal": "WB",

    "hr": "HR",
    "haryana": "HR",

    "pb": "PB",
    "punjab": "PB"
}

KNOWN_LOCATIONS = [
    "adyar",
    "guindy",
    "velachery",
    "besantnagar",
    "besant nagar",
    "thiruvanmiyur",
    "tnagar",
    "t nagar",
    "mylapore",
    "annanagar",
    "anna nagar",
    "koyambedu",
    "nungambakkam",
    "kotturpuram"
]

VEHICLE_TYPES = [
    "suv",
    "bus",
    "truck",
    "bike",
    "auto",
    "taxi",
    "car",
    "jeep",
    "sedan"
]

# =========================================================
# SQL CLEANER
# =========================================================

def clean_sql(sql):

    sql = sql.replace("```sql", "")
    sql = sql.replace("```", "")
    sql = sql.strip()

    if not sql.endswith(";"):
        sql += ";"

    return sql


# =========================================================
# SQL VALIDATOR
# =========================================================

def validate_sql(sql):

    blocked = [
        "DROP",
        "DELETE",
        "UPDATE",
        "INSERT",
        "ALTER",
        "CREATE",
        "TRUNCATE",
        "JOIN",
        "UNION"
    ]

    upper = sql.upper()

    for word in blocked:

        if word in upper:
            return False

    if not upper.startswith("SELECT"):
        return False

    if "VEHICLE_LOGS" not in upper:
        return False

    return True


# =========================================================
# MAIN NLP TO SQL ENGINE
# =========================================================

def ask_llm(user_query):

    q = user_query.lower().strip()

    # =====================================================
    # ENTITY EXTRACTION
    # =====================================================

    plate_match = re.search(
        r'([A-Z]{2}\d{1,2}[A-Z]{1,3}\d{3,4})',
        user_query.upper()
    )

    date_match = re.search(
        r'(\d{4}-\d{2}-\d{2})',
        q
    )

    # =====================================================
    # INTENT DETECTION
    # =====================================================

    intents = {

        "tracking":
            any(k in q for k in [
                "track",
                "history",
                "movement",
                "travel",
                "route",
                "visited",
                "where"
            ]),

        "count":
            any(k in q for k in [
                "count",
                "how many",
                "total"
            ]),

        "analytics":
            any(k in q for k in [
                "top",
                "most",
                "distribution",
                "analysis",
                "statistics",
                "peak"
            ]),

        "latest":
            any(k in q for k in [
                "latest",
                "recent",
                "last"
            ])
    }

    # =====================================================
    # RULE BASED ENGINE
    # =====================================================

    # =====================================================
    # PLATE TRACKING
    # =====================================================

    if plate_match:

        plate = plate_match.group(1)

        # TRACKING

        if intents["tracking"]:

            return clean_sql(f"""
            SELECT
                timestamp,
                plate,
                state,
                vehicle_type,
                location,
                camera_id,
                date,
                hour,
                day
            FROM vehicle_logs
            WHERE plate = '{plate}'
            ORDER BY timestamp DESC
            LIMIT 100
            """)

        # COUNT

        if intents["count"]:

            return clean_sql(f"""
            SELECT
                plate,
                COUNT(*) as detections,
                COUNT(DISTINCT location) as unique_locations,
                COUNT(DISTINCT date) as active_days
            FROM vehicle_logs
            WHERE plate = '{plate}'
            GROUP BY plate
            """)

        # DEFAULT

        return clean_sql(f"""
        SELECT *
        FROM vehicle_logs
        WHERE plate = '{plate}'
        ORDER BY timestamp DESC
        LIMIT 50
        """)

    # =====================================================
    # STATE QUERIES
    # =====================================================

    for key, state in VALID_STATES.items():

        if key in q:

            if intents["count"]:

                return clean_sql(f"""
                SELECT
                    state,
                    COUNT(*) as total_detections,
                    COUNT(DISTINCT plate) as unique_vehicles
                FROM vehicle_logs
                WHERE state = '{state}'
                GROUP BY state
                """)

            return clean_sql(f"""
            SELECT *
            FROM vehicle_logs
            WHERE state = '{state}'
            ORDER BY timestamp DESC
            LIMIT 100
            """)

    # =====================================================
    # LOCATION QUERIES
    # =====================================================

    for loc in KNOWN_LOCATIONS:

        if loc in q:

            # COUNT

            if intents["count"]:

                return clean_sql(f"""
                SELECT
                    location,
                    COUNT(*) as detections,
                    COUNT(DISTINCT plate) as unique_vehicles
                FROM vehicle_logs
                WHERE LOWER(location) LIKE '%{loc}%'
                GROUP BY location
                ORDER BY detections DESC
                """)

            # DEFAULT

            return clean_sql(f"""
            SELECT
                timestamp,
                plate,
                state,
                vehicle_type,
                location,
                camera_id
            FROM vehicle_logs
            WHERE LOWER(location) LIKE '%{loc}%'
            ORDER BY timestamp DESC
            LIMIT 100
            """)

    # =====================================================
    # VEHICLE TYPE
    # =====================================================

    for vtype in VEHICLE_TYPES:

        if vtype in q:

            if intents["count"]:

                return clean_sql(f"""
                SELECT
                    vehicle_type,
                    COUNT(*) as count
                FROM vehicle_logs
                WHERE LOWER(vehicle_type) LIKE '%{vtype}%'
                GROUP BY vehicle_type
                """)

            return clean_sql(f"""
            SELECT *
            FROM vehicle_logs
            WHERE LOWER(vehicle_type) LIKE '%{vtype}%'
            ORDER BY timestamp DESC
            LIMIT 50
            """)

    # =====================================================
    # DATE QUERY
    # =====================================================

    if date_match:

        d = date_match.group(1)

        return clean_sql(f"""
        SELECT *
        FROM vehicle_logs
        WHERE date = '{d}'
        ORDER BY timestamp DESC
        LIMIT 100
        """)

    # =====================================================
    # ANALYTICS
    # =====================================================

    if "hourly traffic" in q or "traffic by hour" in q:

        return clean_sql("""
        SELECT
            hour,
            COUNT(*) as traffic
        FROM vehicle_logs
        GROUP BY hour
        ORDER BY hour
        """)

    if "top vehicles" in q or "most detected" in q:

        return clean_sql("""
        SELECT
            plate,
            COUNT(*) as detections
        FROM vehicle_logs
        GROUP BY plate
        ORDER BY detections DESC
        LIMIT 20
        """)

    if "state distribution" in q:

        return clean_sql("""
        SELECT
            state,
            COUNT(*) as count
        FROM vehicle_logs
        GROUP BY state
        ORDER BY count DESC
        """)

    if "vehicle type distribution" in q:

        return clean_sql("""
        SELECT
            vehicle_type,
            COUNT(*) as count
        FROM vehicle_logs
        GROUP BY vehicle_type
        ORDER BY count DESC
        """)

    if "latest" in q or "recent" in q:

        return clean_sql("""
        SELECT *
        FROM vehicle_logs
        ORDER BY timestamp DESC
        LIMIT 50
        """)

    # =====================================================
    # LLM FALLBACK
    # =====================================================

    if not USE_LLM:

        return clean_sql("""
        SELECT *
        FROM vehicle_logs
        ORDER BY timestamp DESC
        LIMIT 10
        """)

    # =====================================================
    # SYSTEM PROMPT
    # =====================================================

    system_prompt = f"""
You are an elite PostgreSQL SQL generator.

Your job:
Convert natural language into VALID PostgreSQL SQL.

==================================================
DATABASE
==================================================

TABLE:
vehicle_logs

AVAILABLE COLUMNS:

timestamp
plate
state
vehicle_type
vehicle_conf
camera_id
location
date
hour
day

==================================================
COLUMN MEANINGS
==================================================

timestamp:
vehicle detection timestamp

plate:
vehicle number plate

state:
vehicle state code

vehicle_type:
type of vehicle

vehicle_conf:
AI detection confidence

camera_id:
CCTV camera ID

location:
detected location

date:
YYYY-MM-DD

hour:
0-23

day:
Monday-Sunday

==================================================
KNOWN STATES
==================================================

TN
KA
KL
AP
TS
MH
DL
GJ
RJ
UP
WB
HR
PB

==================================================
KNOWN LOCATIONS
==================================================

{KNOWN_LOCATIONS}

==================================================
STRICT RULES
==================================================

1. ONLY use vehicle_logs
2. NEVER use JOIN
3. NEVER invent tables
4. NEVER invent columns
5. ONLY SELECT queries
6. NEVER use UPDATE
7. NEVER use DELETE
8. NEVER use DROP
9. NEVER use ALTER
10. PostgreSQL syntax only
11. Always use LIMIT 50 or LIMIT 100
12. Return SQL ONLY
13. No markdown
14. No explanation

==================================================
QUERY UNDERSTANDING
==================================================

track vehicle
β†’ WHERE plate=''

show TN vehicles
β†’ WHERE state='TN'

show vehicles from adyar
β†’ WHERE LOWER(location) LIKE '%adyar%'

top vehicles
β†’ GROUP BY plate

hourly traffic
β†’ GROUP BY hour

vehicle type distribution
β†’ GROUP BY vehicle_type

latest detections
β†’ ORDER BY timestamp DESC

==================================================
GOOD EXAMPLES
==================================================

SELECT *
FROM vehicle_logs
WHERE state='TN'
ORDER BY timestamp DESC
LIMIT 50;

SELECT *
FROM vehicle_logs
WHERE LOWER(location) LIKE '%adyar%'
ORDER BY timestamp DESC
LIMIT 50;

SELECT
plate,
COUNT(*) as detections
FROM vehicle_logs
GROUP BY plate
ORDER BY detections DESC
LIMIT 20;

SELECT *
FROM vehicle_logs
WHERE plate='TN63MB3157'
ORDER BY timestamp DESC
LIMIT 100;
"""

    user_prompt = f"""
Generate PostgreSQL SQL query for:

{user_query}
"""

    # =====================================================
    # MISTRAL / SQLCODER CALL
    # =====================================================

    try:

        if client is None:
            print("❌ Mistral client not initialized - HF_TOKEN missing")
            raise Exception("LLM service unavailable - HF_TOKEN not configured")

        try:
            response = client.chat_completion(
                messages=[
                    {
                        "role": "system",
                        "content": system_prompt
                    },
                    {
                        "role": "user",
                        "content": user_prompt
                    }
                ],
                max_tokens=250,
                temperature=0.05
            )
            sql = response.choices[0].message.content.strip()
        except Exception as api_error:
            print(f"⚠️ API timeout or error: {api_error}")
            # Fallback to rule-based query if LLM times out
            print("⚠️ Using fallback query due to API timeout")
            return clean_sql("""
            SELECT *
            FROM vehicle_logs
            ORDER BY timestamp DESC
            LIMIT 10
            """)

        sql = clean_sql(sql)

        # =================================================
        # SAFETY
        # =================================================

        if not validate_sql(sql):
            print("❌ SQL validation failed - using safe query")
            return clean_sql("""
            SELECT *
            FROM vehicle_logs
            ORDER BY timestamp DESC
            LIMIT 10
            """)

        # AUTO LIMIT

        if "LIMIT" not in sql.upper():

            sql = sql.replace(";", " LIMIT 50;")

        return sql

    except Exception as e:

        print(f"❌ LLM ERROR: {e}")
        traceback.print_exc()

        return clean_sql("""
        SELECT *
        FROM vehicle_logs
        ORDER BY timestamp DESC
        LIMIT 10
        """)

# =========================================================
# QUERY EXECUTION
# =========================================================

def run_query(user_query):
    """Execute NLP-to-SQL query with timeout protection"""

    sql = ""
    try:

        sql = ask_llm(user_query)

        print("\n" + "="*40)
        print("USER QUERY:")
        print(user_query)

        print("\nGENERATED SQL:")
        print(sql)
        print("="*40)

        if engine is None:
            return {
                "query": user_query,
                "error": "❌ Database not configured - DATABASE_URL missing",
                "sql": sql,
                "result": [],
                "count": 0
            }

        try:
            # Execute with timeout protection
            with engine.connect() as conn:
                # Set statement timeout to 30 seconds
                conn.execute(text("SET statement_timeout = 30000"))  # 30 seconds
                
                result = conn.execute(text(sql))

                rows = [
                    dict(r._mapping)
                    for r in result
                ]

            return {
                "query": user_query,
                "sql": sql,
                "count": len(rows),
                "result": rows
            }
            
        except Exception as query_error:
            print(f"❌ Query Execution Error (possible timeout): {query_error}")
            return {
                "query": user_query,
                "error": f"Query timeout or error: {str(query_error)}",
                "sql": sql,
                "result": [],
                "count": 0
            }

    except Exception as e:

        print(f"❌ Run Query Error: {e}")
        traceback.print_exc()

        return {
            "query": user_query,
            "error": str(e),
            "sql": sql if sql else "",
            "result": [],
            "count": 0
        }

# =========================================================
# DATABASE OPERATIONS
# =========================================================

def save_detection(plate, state, vehicle_type, vehicle_conf, date, time):
    """Save a vehicle detection to the database
    
    Note: The table schema uses timestamp, date, hour, day columns.
    The 'time' parameter is extracted to hour for the hour column.
    """
    
    try:
        
        if engine is None:
            print("⚠️ Engine not initialized - save_detection skipped")
            return False
        
        # Extract hour from time string (HH:MM:SS)
        try:
            hour = int(time.split(":")[0]) if time else 0
        except:
            hour = 0
        
        # Extract day of week from date (simplified)
        from datetime import datetime
        try:
            dt = datetime.strptime(date, "%Y-%m-%d")
            day = dt.strftime("%A")
        except:
            day = "Unknown"
        
        # Use timestamp for current time, date for the date field, hour for hourly grouping
        query = f"""
        INSERT INTO vehicle_logs 
        (plate, state, vehicle_type, vehicle_conf, date, hour, day, timestamp, camera_id, location)
        VALUES ('{plate}', '{state}', '{vehicle_type}', {vehicle_conf}, '{date}', {hour}, '{day}', NOW(), 'CAM-01', 'default')
        """
        
        with engine.connect() as conn:
            conn.execute(text(query))
            conn.commit()
            
        print(f"βœ… Saved: {plate} from {state} at {time}")
        return True
        
    except Exception as e:
        print(f"❌ Save Error: {e}")
        traceback.print_exc()
        return False


def health_check():
    """Check database health with timeout protection"""
    
    try:
        
        if engine is None:
            return False, "❌ Database not configured"
        
        with engine.connect() as conn:
            conn.execute(text("SET statement_timeout = 10000"))  # 10 second timeout
            result = conn.execute(text("SELECT COUNT(*) FROM vehicle_logs"))
            count = result.scalar()
            
        return True, f"βœ… Database OK - {count} records"
        
    except Exception as e:
        print(f"❌ Health Check Error (timeout?): {e}")
        return False, f"❌ Database Error: {str(e)}"


def get_vehicles_by_state():
    """Get vehicle count by state with timeout protection"""
    
    try:
        
        sql = """
        SELECT state, COUNT(*) as count
        FROM vehicle_logs
        GROUP BY state
        ORDER BY count DESC
        """
        
        with engine.connect() as conn:
            conn.execute(text("SET statement_timeout = 15000"))  # 15 second timeout
            result = conn.execute(text(sql))
            rows = [dict(r._mapping) for r in result]
            
        return rows
        
    except Exception as e:
        print(f"❌ State Query Error (timeout?): {e}")
        return []


def get_hourly_traffic():
    """Get traffic by hour with timeout protection"""
    
    try:
        
        sql = """
        SELECT hour, COUNT(*) as traffic
        FROM vehicle_logs
        GROUP BY hour
        ORDER BY hour
        """
        
        with engine.connect() as conn:
            conn.execute(text("SET statement_timeout = 15000"))  # 15 second timeout
            result = conn.execute(text(sql))
            rows = [dict(r._mapping) for r in result]
            
        return rows
        
    except Exception as e:
        print(f"❌ Hourly Traffic Error (timeout?): {e}")
        return []


def get_top_plates():
    """Get top detected plates with timeout protection"""
    
    try:
        
        sql = """
        SELECT plate, COUNT(*) as detections
        FROM vehicle_logs
        GROUP BY plate
        ORDER BY detections DESC
        LIMIT 20
        """
        
        with engine.connect() as conn:
            conn.execute(text("SET statement_timeout = 15000"))  # 15 second timeout
            result = conn.execute(text(sql))
            rows = [dict(r._mapping) for r in result]
            
        return rows
        
    except Exception as e:
        print(f"❌ Top Plates Error (timeout?): {e}")
        return []


def get_suspicious_vehicles():
    """Get vehicles detected multiple times (potentially suspicious) with timeout protection"""
    
    try:
        
        sql = """
        SELECT plate, state, COUNT(*) as detections, 
               COUNT(DISTINCT location) as locations,
               COUNT(DISTINCT date) as days
        FROM vehicle_logs
        GROUP BY plate, state
        HAVING COUNT(*) > 5
        ORDER BY detections DESC
        LIMIT 20
        """
        
        with engine.connect() as conn:
            conn.execute(text("SET statement_timeout = 15000"))  # 15 second timeout
            result = conn.execute(text(sql))
            rows = [dict(r._mapping) for r in result]
            
        return rows
        
    except Exception as e:
        print(f"❌ Suspicious Vehicles Error (timeout?): {e}")
        return []