import os
from datetime import timedelta

class Config:
    """Base configuration with sensible defaults"""
    
    # Database
    DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql://admin:adminpass@localhost:5432/v2')
    
    # Redis
    REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379')
    
    # RabbitMQ
    RABBITMQ_URL = os.getenv('RABBITMQ_URL', 'amqp://guest:guest@localhost:5672')
    
    # JWT
    JWT_SECRET = os.getenv('JWT_SECRET', 'change-this-in-production')
    JWT_ALGORITHM = 'HS256'
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(hours=1)
    JWT_REFRESH_TOKEN_EXPIRES = timedelta(days=30)
    
    # API Rate Limiting
    DEFAULT_RATE_LIMIT_PER_MINUTE = 60
    DEFAULT_RATE_LIMIT_PER_HOUR = 1000
    DEFAULT_RATE_LIMIT_PER_DAY = 10000
    
    # Offline tokens
    MAX_OFFLINE_TOKEN_DURATION_HOURS = 72
    DEFAULT_OFFLINE_TOKEN_DURATION_HOURS = 24
    
    # Heartbeat settings
    HEARTBEAT_INTERVAL_SECONDS = 300  # 5 minutes
    HEARTBEAT_TIMEOUT_SECONDS = 900   # 15 minutes
    
    # Session settings
    MAX_CONCURRENT_SESSIONS = 1
    SESSION_TIMEOUT_MINUTES = 30
    
    # Cache TTL
    CACHE_TTL_VALIDATION = 300  # 5 minutes
    CACHE_TTL_LICENSE_STATUS = 60  # 1 minute
    CACHE_TTL_DEVICE_LIST = 300  # 5 minutes
    
    # Anomaly detection thresholds
    ANOMALY_RAPID_HARDWARE_CHANGE_MINUTES = 10
    ANOMALY_MULTIPLE_IPS_THRESHOLD = 5
    ANOMALY_GEO_DISTANCE_KM = 1000
    
    # Logging
    LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
    LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    
    # Service ports
    AUTH_SERVICE_PORT = int(os.getenv('PORT', 5001))
    LICENSE_API_PORT = int(os.getenv('PORT', 5002))
    ANALYTICS_SERVICE_PORT = int(os.getenv('PORT', 5003))
    ADMIN_API_PORT = int(os.getenv('PORT', 5004))

class DevelopmentConfig(Config):
    """Development configuration"""
    DEBUG = True
    TESTING = False

class ProductionConfig(Config):
    """Production configuration"""
    DEBUG = False
    TESTING = False
    
    # Override with production values
    JWT_SECRET = os.environ['JWT_SECRET']  # Required in production

class TestingConfig(Config):
    """Testing configuration"""
    DEBUG = True
    TESTING = True
    DATABASE_URL = 'postgresql://admin:adminpass@localhost:5432/v2_test'

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

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