"""
Why the Twilio balance is not showing in the panel.

Run inside the install, from its backend directory:

    venv/bin/python manage.py shell --settings=config.settings.production < deploy/check_twilio.py

Reads only. Changes nothing.

The panel renders that figure from a live call to Twilio's Balance API, wrapped
in a bare `except Exception: pass`, and the template prints it only when the
value is not None. So blank credentials, a rejected token, a subaccount
mismatch and a slow network all look identical on screen: the number is simply
absent, and the card reads as a feature that was removed.

This prints the one thing the panel throws away, which is the reason.

The auth token is never printed. Only whether it is set, and its length.
"""
import time

from django.conf import settings

from apps.pages.models import SiteSettings
from apps.tenants.models import Tenant

tenant = Tenant.objects.filter(is_master=True).first()
obj = SiteSettings.load(tenant)

print()
print(f'Install : {tenant.name if tenant else "no master tenant"}')
print(f'Settings row: {obj.pk if obj else "none"}')
print()

sid = (getattr(obj, 'twilio_account_sid', '') or '').strip()
tok = (getattr(obj, 'twilio_auth_token', '') or '').strip()

print('── What is stored ──────────────────────────────────────────────────────')
print(f'  Account SID set   : {bool(sid)}   length {len(sid)}')
print(f'  Auth token set    : {bool(tok)}   length {len(tok)}')
if sid:
    # An Account SID starts AC and is 34 characters. An API Key SID starts SK
    # and will authenticate for some endpoints but not for Balance, which is
    # read against the account itself.
    print(f'  SID prefix        : {sid[:2]}')
    if not sid.startswith('AC'):
        print('    ^ not an Account SID. Balance needs the AC... one from the')
        print('      Twilio console home, not an API key or a Messaging SID.')
    if len(sid) != 34:
        print(f'    ^ expected 34 characters, found {len(sid)}')
if tok and len(tok) != 32:
    print(f'  ! auth token is {len(tok)} characters, expected 32')

if not sid or not tok:
    print()
    print('Nothing to call. The panel never even makes the request when either')
    print('field is blank, so the figure can never appear. Fill both under')
    print('Settings, SMS Twilio, and it will.')
    raise SystemExit

print()
print('── The call the panel makes ────────────────────────────────────────────')
import requests

url = f'https://api.twilio.com/2010-04-01/Accounts/{sid}/Balance.json'
print(f'  GET {url}')
started = time.time()
try:
    r = requests.get(url, auth=(sid, tok), timeout=10)
    took = time.time() - started
    print(f'  HTTP {r.status_code} in {took:.2f}s   (the panel gives up at 5s)')
    print(f'  body: {r.text[:300]}')
    print()
    if r.status_code == 200:
        d = r.json()
        print(f'  balance  {d.get("currency", "")} {d.get("balance")}')
        print()
        print('  The credentials work. If the panel still shows nothing, the')
        print(f'  cause is the timeout: this took {took:.2f}s against a 5s limit.')
    elif r.status_code == 401:
        print('  401 means the token is wrong for this SID. Rotating a token in')
        print('  the Twilio console does not update the copy saved here.')
    elif r.status_code == 404:
        print('  404 means that Account SID does not exist, or it is a')
        print('  subaccount being queried with the parent credentials.')
except requests.Timeout:
    print(f'  timed out after {time.time() - started:.1f}s')
    print('  The panel would have given up at 5s and shown nothing.')
except Exception as exc:
    print(f'  {type(exc).__name__}: {exc}')
    print('  This is the exception the panel swallows.')
print()
