#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
数据库配置模块
仅包含数据库连接的配置信息
"""

from urllib.parse import quote_plus
from sqlalchemy.ext.declarative import declarative_base
from config.settings import settings

# 创建Model基类
Base = declarative_base()

# 数据库连接配置
class DBConfig:
    """数据库配置类"""
    # 数据库连接URL
    DATABASE_URL = settings.DATABASE_URL
    
    # 数据库连接参数（强制关闭echo）
    DATABASE_ARGS = {**settings.DATABASE_ARGS, "echo": False}
    
    # 异步数据库连接参数
    ASYNC_DATABASE_ARGS = {
        "pool_size": settings.DB_POOL_SIZE,
        "max_overflow": settings.DB_MAX_OVERFLOW,
        "pool_recycle": settings.DB_POOL_RECYCLE,
        "pool_timeout": settings.DB_POOL_TIMEOUT,
        "echo": False,  # 强制关闭SQL日志输出
        "pool_pre_ping": settings.DB_POOL_PRE_PING
    }
    
    @classmethod
    def create_db_url(cls, include_db_name=True):
        """
        创建数据库连接URL
        
        Args:
            include_db_name: 是否包含数据库名称
        
        Returns:
            str: 数据库连接URL
        """
        if include_db_name:
            return settings.DATABASE_URL
        else:
            # 根据数据库类型创建不同的连接URL
            if settings.DB_DIALECT == 'sqlite':
                return "sqlite:///:memory:"
            # 对用户名和密码进行URL编码，避免特殊字符（如@符号）造成解析错误
            encoded_user = quote_plus(settings.DB_USER)
            encoded_password = quote_plus(settings.DB_PASSWORD)
            return f"{settings.DB_DIALECT}+{settings.DB_DRIVER}://{encoded_user}:{encoded_password}@{settings.DB_HOST}:{settings.DB_PORT}/mysql"


# 缓存配置
class CacheConfig:
    """缓存配置类，定义Redis缓存配置"""
    # Redis连接配置
    REDIS_URL = settings.REDIS_URL
    REDIS_HOST = settings.REDIS_HOST
    REDIS_PORT = settings.REDIS_PORT
    REDIS_DB = settings.REDIS_DB
    REDIS_PASSWORD = settings.REDIS_PASSWORD
    REDIS_PREFIX = settings.REDIS_PREFIX
    REDIS_SOCKET_TIMEOUT = settings.REDIS_SOCKET_TIMEOUT
    REDIS_SOCKET_CONNECT_TIMEOUT = settings.REDIS_SOCKET_CONNECT_TIMEOUT
    REDIS_DECODE_RESPONSES = settings.REDIS_DECODE_RESPONSES
    
    @classmethod
    def get_redis_connection_args(cls):
        """
        获取Redis连接参数
        
        Returns:
            dict: Redis连接参数字典
        """
        return {
            "host": cls.REDIS_HOST,
            "port": cls.REDIS_PORT,
            "db": cls.REDIS_DB,
            "password": cls.REDIS_PASSWORD,
            "socket_timeout": cls.REDIS_SOCKET_TIMEOUT,
            "socket_connect_timeout": cls.REDIS_SOCKET_CONNECT_TIMEOUT,
            "decode_responses": cls.REDIS_DECODE_RESPONSES
        }
