"""
VYNDR Retry Logic
ALL external API calls use this wrapper. 3 attempts, exponential backoff.
Never returns an unhandled error to the user.
"""

import time
import logging

logger = logging.getLogger('vyndr')


def api_call_with_retry(func, *args, max_retries=3, base_delay=1.0, **kwargs):
    """
    Execute a function with retry logic and exponential backoff.

    Args:
        func: Callable to execute.
        *args: Positional arguments passed to func.
        max_retries: Maximum number of attempts (default 3).
        base_delay: Base delay in seconds between retries (default 1.0).
        **kwargs: Keyword arguments passed to func.

    Returns:
        The return value of func, or None if all retries fail.
    """
    for attempt in range(max_retries):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            if attempt < max_retries - 1:
                delay = base_delay * (2 ** attempt)
                logger.warning(
                    f'[VYNDR] API attempt {attempt + 1} failed: {e}. '
                    f'Retrying in {delay}s'
                )
                time.sleep(delay)
            else:
                logger.error(
                    f'[VYNDR] API failed after {max_retries} attempts: {e}'
                )
                log_api_failure(func.__name__ if hasattr(func, '__name__') else str(func), str(e))
                return None


def log_api_failure(api_name, error_message):
    """
    Log API failure to Supabase api_health_log table.
    Non-fatal — if Supabase itself is down, just log to stderr.
    """
    try:
        from utils.supabase_client import get_supabase_client
        supabase = get_supabase_client()
        if supabase:
            from datetime import datetime
            supabase.table('api_health_log').insert({
                'api_name': api_name,
                'error_message': error_message,
                'failed_at': datetime.utcnow().isoformat(),
                'games_tonight': 0
            }).execute()
    except Exception as e:
        logger.error(f'[VYNDR] Failed to log API failure: {e}')
