import os
from flask import current_app
import pymysql
# 1. Use the NEW Google GenAI library
from google import genai

# 2. Mask PyMySQL as MySQLdb for compatibility
pymysql.install_as_MySQLdb()

# 2. Change the import to a PyMySQL-friendly approach
# We will use a custom wrapper or raw PyMySQL since flask_mysqldb 
# often looks for the system C-libraries that cause your error.
import pymysql.cursors
from apscheduler.schedulers.background import BackgroundScheduler
from dotenv import load_dotenv

load_dotenv()

# We replace the old mysql = MySQL() with a configuration-based approach
# because cPanel handles raw PyMySQL connections much better.
scheduler = BackgroundScheduler()

# Initialize Gemini Client
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
if not GEMINI_API_KEY:
    client = None
else:
    try:
        client = genai.Client(api_key=GEMINI_API_KEY)
    except Exception as e:
        print(f"Error initializing Gemini client: {e}")
        client = None

# Database helper function for your app to use
def get_db_connection():
    return pymysql.connect(
            host=current_app.config.get('MYSQL_HOST', 'localhost'),
            user=current_app.config.get('MYSQL_USER'),
            password=current_app.config.get('MYSQL_PASSWORD'),
            database=current_app.config.get('MYSQL_DB'),
            cursorclass=pymysql.cursors.DictCursor
        )