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
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
"""
AI SQL Agent - Backend Flask API
Local:  python app.py
HF:     gunicorn app:app
"""

import os
import sqlite3
import shutil
import json
from datetime import datetime
from pathlib import Path
from werkzeug.utils import secure_filename
import pandas as pd
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS

from agent import ask_ai
from config import MODEL_NAME
import database as db_module

# ==================== APP SETUP ====================

app = Flask(__name__)
CORS(app, origins="*")

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE_FOLDER = os.path.join(BASE_DIR, "databases")
BACKUP_FOLDER   = os.path.join(BASE_DIR, "backup")
LOG_FOLDER      = os.path.join(BASE_DIR, "logs")

ALLOWED_EXTENSIONS = {"db", "sqlite", "sqlite3"}
MAX_FILE_SIZE = 50 * 1024 * 1024  # 50 MB

for folder in [DATABASE_FOLDER, BACKUP_FOLDER, LOG_FOLDER]:
    os.makedirs(folder, exist_ok=True)

app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE

# ==================== STATE ====================

query_count   = 0
message_count = 0

# ==================== HELPERS ====================

def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS


def get_db_tables(db_path):
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = [row[0] for row in cursor.fetchall()]
        conn.close()
        return tables
    except Exception:
        return []


def get_table_info(db_path, table_name):
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        cursor.execute(f"SELECT COUNT(*) FROM [{table_name}]")
        row_count = cursor.fetchone()[0]
        cursor.execute(f"PRAGMA table_info([{table_name}])")
        columns = [row[1] for row in cursor.fetchall()]
        conn.close()
        return {
            "name": table_name,
            "rows": row_count,
            "columns": columns,
            "column_count": len(columns),
        }
    except Exception:
        return None


def get_table_data(db_path, table_name, limit=100):
    try:
        conn = sqlite3.connect(db_path)
        df = pd.read_sql_query(f"SELECT * FROM [{table_name}] LIMIT {limit}", conn)
        conn.close()
        return df.to_dict("records")
    except Exception:
        return []


def log_action(action, details):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_file = os.path.join(LOG_FOLDER, "activity.log")
    with open(log_file, "a") as f:
        f.write(f"[{timestamp}] {action}: {details}\n")


def current_db():
    """Return active DB path or None."""
    path = db_module.get_db_path()
    return path if path and os.path.exists(path) else None


# ==================== ROUTES: STATUS ====================

@app.route("/api/health", methods=["GET"])
def health_check():
    return jsonify({"status": "ok", "timestamp": datetime.now().isoformat()})


@app.route("/api/status", methods=["GET"])
def get_status():
    cdb = current_db()
    tables = get_db_tables(cdb) if cdb else []
    return jsonify({
        "model": MODEL_NAME,
        "database": os.path.basename(cdb) if cdb else "Not Connected",
        "tables": len(tables),
        "queries": query_count,
        "messages": message_count,
        "timestamp": datetime.now().isoformat(),
        "version": "1.0.0",
    })


# ==================== ROUTES: DATABASE ====================

@app.route("/api/upload-database", methods=["POST"])
def upload_database():
    try:
        if "file" not in request.files:
            return jsonify({"error": "No file provided"}), 400

        file = request.files["file"]
        if not file or file.filename == "":
            return jsonify({"error": "No file selected"}), 400

        if not allowed_file(file.filename):
            return jsonify({"error": "Invalid file type. Only .db, .sqlite, .sqlite3 allowed"}), 400

        filename = secure_filename(file.filename) or "database.db"
        filepath = os.path.join(DATABASE_FOLDER, filename)
        file.save(filepath)

        # Validate it's a real SQLite file
        try:
            conn = sqlite3.connect(filepath)
            conn.execute("SELECT 1")
            conn.close()
        except Exception:
            os.remove(filepath)
            return jsonify({"error": "Invalid SQLite database file"}), 400

        db_module.set_db_path(filepath)
        tables = get_db_tables(filepath)

        log_action("DATABASE_UPLOAD", f"Uploaded {filename}")

        return jsonify({
            "success": True,
            "message": f"Database uploaded: {filename}",
            "database": filename,
            "tables": tables,
            "table_count": len(tables),
        })

    except Exception as e:
        log_action("ERROR", f"Upload failed: {e}")
        return jsonify({"error": str(e)}), 500


@app.route("/api/databases", methods=["GET"])
def list_databases():
    try:
        files = os.listdir(DATABASE_FOLDER)
        databases = []
        cdb = current_db()
        for f in files:
            fp = os.path.join(DATABASE_FOLDER, f)
            if os.path.isfile(fp):
                size = os.path.getsize(fp)
                mtime = datetime.fromtimestamp(os.path.getmtime(fp))
                databases.append({
                    "name": f,
                    "size": f"{size/1024:.2f} KB",
                    "modified": mtime.strftime("%Y-%m-%d %H:%M:%S"),
                })
        return jsonify({
            "databases": databases,
            "current": os.path.basename(cdb) if cdb else None,
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/select-database/<filename>", methods=["POST"])
def select_database(filename):
    try:
        filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
        if not os.path.exists(filepath):
            return jsonify({"error": "Database not found"}), 404

        conn = sqlite3.connect(filepath)
        conn.execute("SELECT 1")
        conn.close()

        db_module.set_db_path(filepath)
        tables = get_db_tables(filepath)

        log_action("DATABASE_SELECT", filename)

        return jsonify({
            "success": True,
            "database": filename,
            "tables": tables,
            "table_count": len(tables),
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/delete-database/<filename>", methods=["DELETE"])
def delete_database(filename):
    try:
        filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
        if not os.path.exists(filepath):
            return jsonify({"error": "Database not found"}), 404

        cdb = current_db()
        if cdb and os.path.abspath(cdb) == os.path.abspath(filepath):
            db_module.set_db_path(None)

        os.remove(filepath)
        log_action("DATABASE_DELETE", filename)
        return jsonify({"success": True, "message": f"Deleted {filename}"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/download-database", methods=["GET"])
def download_database():
    try:
        cdb = current_db()
        if not cdb:
            return jsonify({"error": "No database selected"}), 400

        log_action("DATABASE_DOWNLOAD", os.path.basename(cdb))
        return send_file(
            cdb,
            as_attachment=True,
            download_name=os.path.basename(cdb),
            mimetype="application/octet-stream",
        )
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ==================== ROUTES: TABLES ====================

@app.route("/api/tables", methods=["GET"])
def get_tables():
    cdb = current_db()
    if not cdb:
        return jsonify({"error": "No database selected"}), 400
    try:
        tables = get_db_tables(cdb)
        table_info = [get_table_info(cdb, t) for t in tables]
        table_info = [t for t in table_info if t]
        return jsonify({"tables": table_info, "total": len(table_info)})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/table/<table_name>", methods=["GET"])
def get_table(table_name):
    cdb = current_db()
    if not cdb:
        return jsonify({"error": "No database selected"}), 400
    try:
        info = get_table_info(cdb, table_name)
        data = get_table_data(cdb, table_name)
        return jsonify({"table": table_name, "info": info, "data": data, "row_count": len(data)})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ==================== ROUTES: QUERY ====================

@app.route("/api/query", methods=["POST"])
def process_query():
    global query_count, message_count
    try:
        body = request.get_json()
        question = (body.get("question") or "").strip()

        if not question:
            return jsonify({"error": "Question cannot be empty"}), 400

        cdb = current_db()
        if not cdb:
            return jsonify({"error": "No database selected. Please upload or select a database first."}), 400

        answer, sql, result_df = ask_ai(question)

        query_count  += 1
        message_count += 1

        result_data = None
        if isinstance(result_df, pd.DataFrame) and not result_df.empty:
            result_data = result_df.to_dict("records")

        sql_upper = sql.upper().strip()
        if sql_upper.startswith("SELECT"):
            operation = "SELECT"
        elif sql_upper.startswith("INSERT"):
            operation = "INSERT"
        elif sql_upper.startswith("UPDATE"):
            operation = "UPDATE"
        elif sql_upper.startswith("DELETE"):
            operation = "DELETE"
        else:
            operation = "UNKNOWN"

        log_action("QUERY", f"{operation} | Q: {question[:60]}")

        return jsonify({
            "success": True,
            "answer": answer,
            "sql": sql,
            "data": result_data,
            "operation": operation,
            "row_count": len(result_data) if result_data else 0,
            "database": os.path.basename(cdb),
            "timestamp": datetime.now().isoformat(),
        })

    except Exception as e:
        log_action("ERROR", f"Query failed: {e}")
        return jsonify({"error": str(e)}), 500


# ==================== ROUTES: BACKUP ====================

@app.route("/api/backup", methods=["POST"])
def create_backup():
    cdb = current_db()
    if not cdb:
        return jsonify({"error": "No database selected"}), 400
    try:
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        base = os.path.splitext(os.path.basename(cdb))[0]
        backup_name = f"{base}_backup_{ts}.db"
        backup_path = os.path.join(BACKUP_FOLDER, backup_name)
        shutil.copy2(cdb, backup_path)
        log_action("BACKUP_CREATED", backup_name)
        return jsonify({"success": True, "message": f"Backup created: {backup_name}", "backup": backup_name})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/backups", methods=["GET"])
def list_backups():
    try:
        files = os.listdir(BACKUP_FOLDER)
        backups = []
        for f in files:
            fp = os.path.join(BACKUP_FOLDER, f)
            if os.path.isfile(fp):
                size = os.path.getsize(fp)
                mtime = datetime.fromtimestamp(os.path.getmtime(fp))
                backups.append({
                    "name": f,
                    "size": f"{size/1024:.2f} KB",
                    "created": mtime.strftime("%Y-%m-%d %H:%M:%S"),
                })
        backups.sort(key=lambda x: x["created"], reverse=True)
        return jsonify({"backups": backups, "total": len(backups)})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/restore/<backup_name>", methods=["POST"])
def restore_backup(backup_name):
    try:
        backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
        if not os.path.exists(backup_path):
            return jsonify({"error": "Backup not found"}), 404

        restore_name = backup_name.replace("_backup", "").split("_")[0] + ".db"
        restore_path = os.path.join(DATABASE_FOLDER, restore_name)
        shutil.copy2(backup_path, restore_path)
        db_module.set_db_path(restore_path)
        tables = get_db_tables(restore_path)
        log_action("BACKUP_RESTORED", backup_name)
        return jsonify({
            "success": True,
            "message": "Backup restored successfully",
            "database": restore_name,
            "tables": tables,
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/backup/<backup_name>", methods=["DELETE"])
def delete_backup(backup_name):
    try:
        backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
        if not os.path.exists(backup_path):
            return jsonify({"error": "Backup not found"}), 404
        os.remove(backup_path)
        log_action("BACKUP_DELETED", backup_name)
        return jsonify({"success": True, "message": "Backup deleted"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ==================== ROUTES: MANAGEMENT ====================

@app.route("/api/clear-all", methods=["POST"])
def clear_all():
    try:
        for folder in [DATABASE_FOLDER]:
            for f in os.listdir(folder):
                fp = os.path.join(folder, f)
                if os.path.isfile(fp):
                    os.remove(fp)
        db_module.set_db_path(None)
        log_action("CLEAR_ALL", "Cleared all databases")
        return jsonify({"success": True, "message": "All databases cleared (backups preserved)"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route("/api/logs", methods=["GET"])
def get_logs():
    try:
        log_file = os.path.join(LOG_FOLDER, "activity.log")
        if not os.path.exists(log_file):
            return jsonify({"logs": [], "total": 0})
        with open(log_file, "r") as f:
            logs = f.readlines()
        logs = list(reversed(logs[-100:]))
        return jsonify({"logs": logs, "total": len(logs)})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# ==================== ERROR HANDLERS ====================

@app.errorhandler(404)
def not_found(e):
    return jsonify({"error": "Not found"}), 404

@app.errorhandler(413)
def too_large(e):
    return jsonify({"error": "File too large (max 50 MB)"}), 413

@app.errorhandler(500)
def server_error(e):
    return jsonify({"error": "Internal server error"}), 500


# ==================== MAIN ====================

if __name__ == "__main__":
    # Auto-load default DB if it exists
    default_db = os.path.join(BASE_DIR, "database", "company.db")
    if os.path.exists(default_db):
        db_module.set_db_path(default_db)
        print(f"✅ Default DB loaded: {default_db}")

    print("=" * 60)
    print("🚀  AI SQL Agent  –  Backend API")
    print("=" * 60)
    print(f"Model    : {MODEL_NAME}")
    print(f"API URL  : http://localhost:5000")
    print("=" * 60)

    app.run(debug=True, host="0.0.0.0", port=5000)