"""Web-specific configuration"""

import os
import secrets

# JWT
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "")
JWT_ALGORITHM = "HS256"
JWT_EXPIRE_HOURS = 24

# File upload
MAX_UPLOAD_SIZE = 50 * 1024 * 1024  # 50MB
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp'}
ALLOWED_EXCEL_EXTENSIONS = {'.xlsx', '.xls'}
ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS | ALLOWED_EXCEL_EXTENSIONS

# CORS
CORS_ORIGINS = os.getenv("CORS_ORIGINS", "*").split(",")

# Auth rate limit
LOGIN_RATE_LIMIT = 5  # per minute


def get_or_generate_secret() -> str:
    """Get JWT secret from env or auto-generate on first run"""
    global JWT_SECRET_KEY
    if not JWT_SECRET_KEY:
        secret_file = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
            'data', '.jwt_secret'
        )
        if os.path.exists(secret_file):
            with open(secret_file, 'r') as f:
                JWT_SECRET_KEY = f.read().strip()
        if not JWT_SECRET_KEY:
            JWT_SECRET_KEY = secrets.token_urlsafe(48)
            os.makedirs(os.path.dirname(secret_file), exist_ok=True)
            with open(secret_file, 'w') as f:
                f.write(JWT_SECRET_KEY)
    return JWT_SECRET_KEY
