import os
from dotenv import load_dotenv
from pydub.utils import which

# Load environment variables from .env file
load_dotenv()

class Config:
    # Flask Configuration
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard-to-guess-string'
    
    # Get the base directory of your project
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    # SQLAlchemy — honours DATABASE_URL env var (MySQL/Postgres on cPanel/cloud)
    # Falls back to local SQLite for development.
    SQLALCHEMY_DATABASE_URI = (
        os.environ.get('DATABASE_URL')
        or 'sqlite:///' + os.path.join(BASE_DIR, 'app.db')
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    
    # Mail Configuration
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT') or 587)
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS', 'true').lower() in ('1', 'true', 'yes', 'on')
    MAIL_USE_SSL = False
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    MAIL_DEFAULT_SENDER = os.environ.get('MAIL_DEFAULT_SENDER')
    
    # Admin Configuration
    ADMIN_EMAILS = os.environ.get('ADMIN_EMAILS', '').split(',')
    
    # API Keys
    MISTRAL_API_KEY = os.environ.get('MISTRAL_API_KEY') or 'your-mistral-api-key-here'
    OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')   # Optional — Whisper transcription
    
    # AI Configuration
    USE_AI_TRANSCRIPTION = True  # Enable AI-based audio transcription and assessment

    # PDF Generation
    WKHTMLTOPDF_PATH = os.environ.get('WKHTMLTOPDF_PATH')

    # FFmpeg — honour explicit env vars first, then try the bundled Windows binary,
    # then fall back to whatever is on the system PATH (Linux/cPanel).
    _is_windows = os.name == 'nt'
    _bundled_ffmpeg = os.path.join(BASE_DIR, 'ffmpeg', 'ffmpeg.exe' if _is_windows else 'ffmpeg')
    _bundled_ffprobe = os.path.join(BASE_DIR, 'ffmpeg', 'ffprobe.exe' if _is_windows else 'ffprobe')

    FFMPEG_PATH = (
        os.environ.get('FFMPEG_PATH')
        or (_bundled_ffmpeg if os.path.exists(_bundled_ffmpeg) else (which('ffmpeg') or 'ffmpeg'))
    )
    FFPROBE_PATH = (
        os.environ.get('FFPROBE_PATH')
        or (_bundled_ffprobe if os.path.exists(_bundled_ffprobe) else (which('ffprobe') or 'ffprobe'))
    )

    # Ensure pydub can find the binary
    if not which('ffmpeg') and os.path.isfile(FFMPEG_PATH):
        os.environ['PATH'] = os.path.dirname(FFMPEG_PATH) + os.pathsep + os.environ.get('PATH', '')

    @classmethod
    def validate_paths(cls):
        """Warn (don't crash) when FFmpeg is missing — audio features degrade gracefully."""
        if not os.path.isfile(cls.FFMPEG_PATH) and not which('ffmpeg'):
            import warnings
            warnings.warn(
                f"FFmpeg not found at '{cls.FFMPEG_PATH}' and not on PATH. "
                "Audio processing features will be unavailable.",
                RuntimeWarning
            )