import os

def env(key, default=None, type_=str, required=True):
    """Generic function to get environment variables with type conversion and validation."""
    value = os.environ.get(key, default)

    print(f'{key}={value}')
    
    if required and value is None:
        raise EnvironmentError(f"{key} is not set in the environment.")
    
    # Strip whitespace for string values
    if value is not None and type_ == str:
        value = value.strip()
    
    if value is not None and type_ != str:
        try:
            return type_(value)
        except (ValueError, TypeError) as e:
            raise EnvironmentError(f"Cannot convert {key}='{value}' to {type_.__name__}: {e}")
    
    return value

# Bot configuration
BOT_TOKEN = env('BOT_TOKEN')
LightningProxiesAPI_KEY = env('LIGHTNINGPROXIESAPI_KEY')

# Admin IDs - can be single ID or comma-separated list
ADMIN_ID_RAW = env('ADMIN_ID')
if ',' in ADMIN_ID_RAW:
    ADMIN_IDS = [int(id.strip()) for id in ADMIN_ID_RAW.split(',') if id.strip()]
else:
    ADMIN_IDS = [int(ADMIN_ID_RAW)]

# For backward compatibility
ADMIN_ID = ADMIN_IDS[0]

# Helper function to send messages to all admins
async def send_to_admins(bot, message):
    """Send message to all admin users"""
    for admin_id in ADMIN_IDS:
        try:
            await bot.send_message(admin_id, message)
        except Exception as e:
            print(f"Failed to send message to admin {admin_id}: {e}")

# Backup settings
BACKUP_PATH = env('BACKUP_PATH', default="./backups-db/", required=False)
DATABASE_PATH = env('DATABASE_PATH', default="database.sqlite", required=False)
INTERVAL_HOURS = env('INTERVAL_HOURS', default=24, type_=int, required=False)

# Payment settings
CRYSTALPAY_LOGIN = env('CRYSTALPAY_LOGIN')
CRYSTALPAY_SECRET = env('CRYSTALPAY_SECRET')
CRYSTALPAY_SALT = env('CRYSTALPAY_SALT')

HELEKET_MERCHANT = env('HELEKET_MERCHANT')
HELEKET_SIGN = env('HELEKET_SIGN')

LOCALES_PATH = env('LOCALES_PATH')

print(f'DATABASE_PATH: {DATABASE_PATH}')