"""
VYNDR Environment Variable Checker
Runs at startup. Exits if required vars missing. Warns on recommended.
Never logs secret values.
"""

import os
import sys
import logging

logger = logging.getLogger('vyndr')

REQUIRED_VARS = {
    'SUPABASE_URL': 'Supabase project URL',
    'SUPABASE_SERVICE_ROLE_KEY': 'Supabase service role key',
    'SUPABASE_JWT_SECRET': 'Supabase JWT signing secret',
}

RECOMMENDED_VARS = {
    'ODDS_API_KEY': 'The Odds API key (required for odds scanning)',
    'REDIS_URL': 'Upstash Redis URL (required for caching)',
    'VYNDR_INTERNAL_KEY': 'Internal API key for cron jobs (legacy: BETONBLK_INTERNAL_KEY)',
    'ALLOWED_ORIGINS': 'CORS allowed origins (defaults to localhost)',
    'SHADOW_MODE': 'Shadow mode flag (defaults to true)',
    'ALT_LINE_MODE': 'Alt line mode (defaults to manual)',
}

# Env vars whose values must never be logged. Both internal-key names listed
# so the legacy var stays redacted during the rename window.
NEVER_LOG = [
    'SUPABASE_SERVICE_ROLE_KEY', 'SUPABASE_JWT_SECRET', 'ODDS_API_KEY',
    'REDIS_URL', 'VYNDR_INTERNAL_KEY', 'BETONBLK_INTERNAL_KEY', 'STRIPE_SECRET_KEY'
]

# Vars where presence under EITHER name satisfies the recommended check.
# Tuple: (canonical, [legacy aliases]).
_ALIASED_VARS = [('VYNDR_INTERNAL_KEY', ['BETONBLK_INTERNAL_KEY'])]


def _has_any(name, aliases):
    if os.environ.get(name):
        return True
    return any(os.environ.get(a) for a in aliases)


def check_environment(exit_on_missing=True):
    """
    Verify all required environment variables are present.
    Exit if critical vars missing (unless exit_on_missing=False for testing).

    Args:
        exit_on_missing: If True, sys.exit(1) when required vars missing.

    Returns:
        Dict with 'missing_required' and 'missing_recommended' lists.
    """
    missing_required = []
    missing_recommended = []

    for var, description in REQUIRED_VARS.items():
        if not os.environ.get(var):
            missing_required.append(f'{var} — {description}')

    alias_lookup = {canonical: aliases for canonical, aliases in _ALIASED_VARS}
    for var, description in RECOMMENDED_VARS.items():
        aliases = alias_lookup.get(var, [])
        if not _has_any(var, aliases):
            missing_recommended.append(f'{var} — {description}')

    if missing_required:
        logger.critical('[SECURITY] Missing REQUIRED environment variables:')
        for m in missing_required:
            logger.critical(f'  - {m}')
        if exit_on_missing:
            logger.critical('[SECURITY] Cannot start without required variables. Exiting.')
            sys.exit(1)

    if missing_recommended:
        logger.warning('[SECURITY] Missing recommended environment variables:')
        for m in missing_recommended:
            logger.warning(f'  - {m}')

    logger.info('[SECURITY] Environment check passed')
    return {
        'missing_required': missing_required,
        'missing_recommended': missing_recommended
    }
