import os

from dotenv import load_dotenv

base_dir = os.path.dirname(os.path.abspath(__file__))

load_dotenv(os.path.join(base_dir, ".env"))


class Config:
    APP_NAME = os.getenv("APP_NAME")
    POSTS_PER_PAGE = 5
    # EMAIL SETTINGS
    MAIL_SERVER = os.getenv("MAIL_SERVER")
    MAIL_PORT = os.getenv("MAIL_PORT")
    MAIL_USE_TLS = os.getenv("MAIL_USE_TLS")
    MAIL_USERNAME = os.getenv("MAIL_USER")
    MAIL_PASSWORD = os.getenv("MAIL_PASS")

    # Secret key - CHANGE THIS to a random string
    SECRET_KEY = (
        os.environ.get("SECRET_KEY") or "your-secret-key-change-this-in-production"
    )

    # Database Configuration
    # IMPORTANT: Replace these values with your actual database credentials
    SQLALCHEMY_DATABASE_URI = (
        os.environ.get("DATABASE_URL")
        or f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}@{os.getenv('MYSQL_HOST')}/{os.getenv('MYSQL_NAME')}"
    )

    # Disable modification tracking (improves performance)
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # CRITICAL: Database Engine Options for Connection Pooling
    SQLALCHEMY_ENGINE_OPTIONS = {
        # Test connections before using (prevents "MySQL server has gone away")
        "pool_pre_ping": True,
        # Connection pool size
        "pool_size": 10,
        # Maximum overflow connections
        "max_overflow": 20,
        # Recycle connections after 1 hour (3600 seconds)
        # MySQL default timeout is 8 hours, but we recycle earlier
        "pool_recycle": 3600,
        # Timeout for getting connection from pool (30 seconds)
        "pool_timeout": 30,
        # MySQL-specific connection arguments
        "connect_args": {
            "connect_timeout": 10,  # Connection timeout
            "read_timeout": 300,  # Read timeout
            "write_timeout": 300,  # Write timeout
            "charset": "utf8mb4",  # Character set
            "use_unicode": True,
        },
        # Logging (set to False in production for better performance)
        "echo": False,
        "echo_pool": False,
    }

    # CKEditor Configuration
    CKEDITOR_PKG_TYPE = "standard"

    # Session Configuration
    SESSION_COOKIE_SECURE = False  # Set to True if using HTTPS
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"
    PERMANENT_SESSION_LIFETIME = 3600  # 1 hour

    # Upload Configuration (if you have file uploads)
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB max file size


class DevelopmentConfig(Config):
    """Development configuration"""

    DEBUG = True
    TESTING = False

    # Enable SQL query logging in development
    SQLALCHEMY_ENGINE_OPTIONS = {
        **Config.SQLALCHEMY_ENGINE_OPTIONS,
        "echo": True,  # Log all SQL queries
        "echo_pool": True,  # Log pool events
    }


class ProductionConfig(Config):
    """Production configuration"""

    DEBUG = False
    TESTING = False

    # Ensure these are set from environment variables in production
    SECRET_KEY = os.environ.get("SECRET_KEY")
    SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")

    # Stricter session settings for production
    SESSION_COOKIE_SECURE = True  # Requires HTTPS
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Strict"


class TestingConfig(Config):
    """Testing configuration"""

    TESTING = True
    DEBUG = True

    # Use separate test database
    SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}@{os.getenv('MYSQL_HOST')}/{os.getenv('MYSQL_NAME')}"


# Configuration dictionary
config = {
    "development": DevelopmentConfig,
    "production": ProductionConfig,
    "testing": TestingConfig,
    "default": DevelopmentConfig,
}
