"""
Database connection pooling.

Uses mysql-connector-python pool for efficient connections.
"""

import mysql.connector
from mysql.connector import pooling
from config import config
import logging

# Simple print-based logging for now
def log_info(msg):
    print(f"[INFO] {msg}")

def log_error(msg):
    print(f"[ERROR] {msg}")

# Connection pool (module-level singleton)
_connection_pool = None


def get_connection_pool():
    """
    Get or create database connection pool.

    Returns:
        MySQL connection pool
    """
    global _connection_pool

    if _connection_pool is None:
        try:
            # Build connection parameters
            # NOTE: pool_timeout is NOT supported by mysql-connector-python
            # It's only supported by aiomysql. Do not add it here.
            conn_params = {
                'pool_name': "baolife_pool",
                'pool_size': min(config.MAX_CONNECTIONS, 32),  # MySQL max is 32
                'pool_reset_session': True,
                'host': config.DB_HOST,
                'port': config.DB_PORT,
                'user': config.DB_USER,
                'password': config.DB_PASSWORD,
                'database': config.DB_NAME
            }

            # Filter out any unsupported parameters (defensive programming)
            # mysql-connector-python does NOT support: pool_timeout, connect_timeout (in pool)
            unsupported_params = ['pool_timeout', 'connect_timeout']
            conn_params = {k: v for k, v in conn_params.items() if k not in unsupported_params}

            _connection_pool = pooling.MySQLConnectionPool(**conn_params)
            log_info(f"Database connection pool created (size: {config.MAX_CONNECTIONS})")
        except Exception as e:
            log_error(f"Failed to create connection pool: {e}")
            raise

    return _connection_pool


def get_database_connection():
    """
    Get database connection from pool.

    Returns:
        MySQL connection

    Usage:
        conn = get_database_connection()
        try:
            cursor = conn.cursor()
            cursor.execute("SELECT ...")
        finally:
            conn.close()  # Returns to pool
    """
    try:
        pool = get_connection_pool()
        return pool.get_connection()
    except Exception as e:
        log_error(f"Failed to get database connection: {e}")
        raise


def close_connection_pool():
    """Close all connections in pool (for cleanup)"""
    global _connection_pool

    if _connection_pool:
        # Pool doesn't have explicit close, but we can clear reference
        _connection_pool = None
        log_info("Database connection pool closed")
