import os
import multiprocessing
from dotenv import load_dotenv

# Filepath (e.g.: /home/user/AKSARA-Ent/app/core/config.py)
current_dir = os.path.abspath(os.path.dirname(__file__))

# Find file .env in the ROOT project (/home/user/AKSARA-Ent/.env)
# We assume the 'app' folder is in the root.
# If this config file is in app/core/, we need to go up 2 levels.
root_path = os.path.abspath(os.path.join(current_dir, "../../"))
env_path = os.path.join(root_path, '.env')

# DEBUG: Add this temporarily to see the path in stderr/logs cPanel
# print(f"--- DEBUG: Looking for .env at {env_path} ---")

if os.path.exists(env_path):
    load_dotenv(env_path)
else:
    # If still fails, try to load from the current folder (fallback)
    load_dotenv()

class Config:
    """
    Configuration for the Flask application.
    """
    basedir = os.path.dirname(os.path.abspath(__file__))
    filedir = os.path.abspath(os.path.dirname(__file__))

    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-this'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') or 'mysql+pymysql://user:password@localhost/aksara_db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False # Disable track modifications to reduce overhead
    SQLALCHEMY_ECHO = False # Set to True to see SQL queries in the console (useful during development)

    # Dynamic Pool Sizing — scales with server hardware
    # pool_size: baseline concurrent connections (min 5, scales with CPU cores)
    # max_overflow: burst capacity above pool_size for traffic spikes
    # pool_timeout: seconds to wait for a free connection before raising error
    _cpu_count = multiprocessing.cpu_count()
    _pool_size = max(5, _cpu_count * 2)
    _max_overflow = max(10, _cpu_count * 4)

    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_recycle': 280,        # Recycle connections before MariaDB timeout (~300s)
        'pool_pre_ping': True,      # Validate connections before use (handles stale)
        'pool_size': _pool_size,    # Dynamic baseline connections
        'max_overflow': _max_overflow,  # Burst capacity for spikes
        'pool_timeout': 30,         # Fail-fast when pool exhausted
    }

    # Session Configuration
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SECURE = os.environ.get('FLASK_ENV') == 'production'
    SESSION_COOKIE_SAMESITE = 'Lax'  # CSRF protection for cross-site requests

    # CORS — comma-separated origins, default wildcard for dev only
    # WARNING: Set CORS_ALLOWED_ORIGINS in production to specific domains!
    CORS_ALLOWED_ORIGINS = os.getenv('CORS_ALLOWED_ORIGINS', '*')

    APP_TITLE = os.getenv('APP_TITLE', 'Default Website Title')
    APP_TAGLINE = os.getenv('APP_TAGLINE', 'Default Tagline')
    APP_VERSION = f"v{os.getenv('APP_VERSION', '1.0.0')}"
    POWERED_BY = os.getenv('POWERED_BY', 'Default Powered By')
    DEV_URL = os.getenv('DEV_URL', 'https://indrafer.com/')

    SERVER_TIMEZONE = os.getenv('SERVER_TIMEZONE', 'UTC')

    # Upload Folder
    UPLOAD_FOLDER = os.path.join(basedir, os.getenv('UPLOAD_FOLDER', 'uploads'))
    ALLOWED_EXTENSIONS = set(os.getenv('ALLOWED_EXTENSIONS', 'png,jpg,jpeg,gif,webp,pdf,docx,xlsx,txt').lower().split(','))
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16 MB max upload

    # Logging
    LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')

    # Dev Tools — Dummy Data Generator (set False in production!)
    ALLOW_DUMMY_DATA = os.getenv('ALLOW_DUMMY_DATA', 'False').lower() == 'true'

    # Enterprise Module Toggles
    # Default is False, must be explicitly enabled in .env
    ENABLE_MODULE_CRM = os.getenv('ENABLE_MODULE_CRM', 'False').lower() == 'true'
    ENABLE_MODULE_ERP = os.getenv('ENABLE_MODULE_ERP', 'False').lower() == 'true'
    ENABLE_MODULE_HRIS = os.getenv('ENABLE_MODULE_HRIS', 'False').lower() == 'true'
    ENABLE_MODULE_COLLAB = os.getenv('ENABLE_MODULE_COLLAB', 'False').lower() == 'true'
