"""
Central helpers for reading sensitive API keys.

Source: the SiteSettings row, and nothing else.

There used to be an environment fallback on every one of these. It is gone
deliberately. .env is a file on disk: it travels into backups, into synced
folders and into every copy of the tree, and on 21 August 2026 a live Stripe
key was used from an address that was not ours. The database keeps these
encrypted at rest and is edited only through the panel.

A missing key now means the feature is off and says so, rather than quietly
using a value nobody remembers setting.
"""


def _site(tenant=None):
    """
    The Settings row to read keys from.

    Called with a tenant, that tenant's row. Called without one, from a
    management command or a helper with no request to hand, the master
    tenant's row. Never SiteSettings.load(None), which returns whatever
    orphaned null-tenant row happens to exist and twice made this look
    unconfigured when it was not.
    """
    try:
        from apps.pages.models import SiteSettings
        if tenant is None or getattr(tenant, 'pk', 0) == 0:
            from apps.tenants.models import Tenant
            tenant = Tenant.objects.filter(is_master=True).first()
            if tenant is None:
                return None
        return SiteSettings.load(tenant)
        # No cross-tenant fallback. That handed one client's OpenAI, Stripe
        # and reCAPTCHA keys to another client's site.
    except Exception:
        return None


def get_openai_api_key(tenant=None):
    site = _site(tenant)
    return (site.openai_api_key or '') if site else ''


def get_recaptcha_secret_key(tenant=None):
    site = _site(tenant)
    return (site.recaptcha_secret_key or '') if site else ''


def get_recaptcha_site_key(tenant=None):
    site = _site(tenant)
    return (site.recaptcha_site_key or '') if site else ''


def get_recaptcha_v2_site_key(tenant=None):
    site = _site(tenant)
    return (getattr(site, 'recaptcha_v2_site_key', '') or '') if site else ''


def get_recaptcha_v2_secret_key(tenant=None):
    site = _site(tenant)
    return (getattr(site, 'recaptcha_v2_secret_key', '') or '') if site else ''


def get_stripe_public_key(tenant=None):
    """Publishable, so not a secret, but it belongs with its pair."""
    site = _site(tenant)
    return (site.stripe_public_key or '') if site else ''


def get_twilio_credentials(tenant=None):
    """Returns (account_sid, auth_token, from_number)."""
    site = _site(tenant)
    if not site:
        return '', '', ''
    return (
        site.twilio_account_sid or '',
        site.twilio_auth_token or '',
        site.twilio_from_number or '',
    )
