"""
Flask Configuration
===================

Configuration classes for different environments.
"""

import os
from datetime import timedelta


class Config:
    """Base configuration with common settings."""

    # Security: Require strong SECRET_KEY
    SECRET_KEY = os.getenv('SECRET_KEY')

    # Session configuration
    PERMANENT_SESSION_LIFETIME = timedelta(days=7)

    # CSRF configuration
    WTF_CSRF_ENABLED = True
    WTF_CSRF_TIME_LIMIT = None  # No time limit for CSRF tokens

    # Cookie security
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = 'Lax'

    # Rate limiting
    RATELIMIT_STORAGE_URI = "memory://"
    RATELIMIT_DEFAULT = ["200 per day", "50 per hour"]

    @staticmethod
    def init_app(app):
        """Initialize application-specific configuration."""
        pass


class DevelopmentConfig(Config):
    """Development environment configuration."""

    DEBUG = True
    SESSION_COOKIE_SECURE = False  # Allow HTTP in development

    # Try Redis for rate limiting, fallback to memory
    @staticmethod
    def init_app(app):
        try:
            import redis
            redis_client = redis.Redis(host='localhost', port=6379, db=0)
            redis_client.ping()
            app.config['RATELIMIT_STORAGE_URI'] = "redis://localhost:6379/0"
        except Exception:
            app.config['RATELIMIT_STORAGE_URI'] = "memory://"


class ProductionConfig(Config):
    """Production environment configuration."""

    DEBUG = False
    SESSION_COOKIE_SECURE = True  # HTTPS only

    @staticmethod
    def init_app(app):
        # Use Redis for persistent rate limiting across restarts
        try:
            import redis
            redis_client = redis.Redis(host='localhost', port=6379, db=0)
            redis_client.ping()
            app.config['RATELIMIT_STORAGE_URI'] = "redis://localhost:6379/0"
        except Exception:
            import logging
            logging.warning("Redis unavailable, rate limiter using memory storage")
            app.config['RATELIMIT_STORAGE_URI'] = "memory://"


class TestingConfig(Config):
    """Testing environment configuration."""

    TESTING = True
    WTF_CSRF_ENABLED = False
    SESSION_COOKIE_SECURE = False


config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}


def get_config():
    """Get configuration class based on FLASK_ENV environment variable."""
    env = os.getenv('FLASK_ENV', 'development')
    return config.get(env, config['default'])
