import mysql.connector
import re
from mysql.connector import Error

# --- MASTER DATABASE CONFIG (UNCHANGED) ---
DB_CONFIG = {
    "host": "prod-db-read.webxpay.com",
    "user": "readuser01",
    "password": "hV51KziWB3hSlc8Gu",
    "database": "webxpay_master",
    # "port": 3306,
    "connect_timeout": 5 
}


try:
    conn = mysql.connector.connect(**DB_CONFIG)
    if conn.is_connected():
        print("✅ Connection successful!")
        conn.close()
except Error as e:
    print(f"❌ Connection failed: {e}")

def db_connect():
    return mysql.connector.connect(**DB_CONFIG)

def run_sql(query):
    try:
        # Remove markdown formatting like ```sql
        query = query.replace("```sql", "").replace("```", "").strip()
        conn = db_connect()
        cursor = conn.cursor(dictionary=True)
        # Prevent non-SELECT queries for safety
        if not query.upper().startswith("SELECT"):
            return {"error": "Only SELECT queries are allowed."}
        cursor.execute(query)
        data = cursor.fetchall()
        cursor.close()
        conn.close()
        return data
    except Exception as e:
        return {"error": str(e)}

def get_columns_for_table(table_name):
    """Return list of columns for a table."""
    try:
        conn = db_connect()
        cursor = conn.cursor()
        cursor.execute(f"SHOW COLUMNS FROM `{table_name}`")
        columns = [row[0] for row in cursor.fetchall()]
        cursor.close()
        conn.close()
        return columns
    except Exception as e:
        return []

