"""
Which encrypted Settings values are intact, and which are double encrypted.

Run inside the install, from its backend directory:

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

Reads only. Changes nothing. No secret value is ever printed, only its length
and whether it still looks like ciphertext after being decrypted once.

Found 25 August 2026: twilio_auth_token came back 995 characters instead of 32,
while twilio_account_sid on the same row decrypted perfectly. A value that is
still a Fernet token after the field has decrypted it was encrypted more than
once, which happens when an already-encrypted value is written back through the
ORM. The field encrypts on write without checking whether it is looking at
plaintext.

A Fernet token starts with 'gAAAAA'. That prefix in a decrypted value is the
tell.
"""
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()

secure = [f for f in obj._meta.get_fields()
          if 'Encrypted' in type(f).__name__]

if not secure:
    print('No encrypted fields on this model. The encryption library is not')
    print('installed here, so every one of these is stored as plain text.')
    raise SystemExit

# What each field should look like once decrypted. None means no fixed shape.
EXPECT = {
    'twilio_account_sid':      ('AC', 34),
    'twilio_auth_token':       (None, 32),
    'stripe_secret_key':       ('sk_', None),
    'stripe_webhook_secret':   ('whsec_', None),
    'openai_api_key':          ('sk-', None),
    'openai_admin_key':        ('sk-', None),
    'recaptcha_secret_key':    ('6L', None),
    'recaptcha_v2_secret_key': ('6L', None),
    'ga_credentials_json':     ('{', None),
}

print(f'{"field":26} {"len":>5}  state')
print('-' * 64)

bad = []
for f in sorted(secure, key=lambda x: x.name):
    raw = getattr(obj, f.name, '') or ''
    raw = raw.strip() if isinstance(raw, str) else str(raw)
    if not raw:
        print(f'{f.name:26} {"-":>5}  not set')
        continue

    prefix, length = EXPECT.get(f.name, (None, None))
    notes = []
    if raw.startswith('gAAAAA'):
        notes.append('DOUBLE ENCRYPTED')
        bad.append(f.name)
    else:
        if prefix and not raw.startswith(prefix):
            notes.append(f'expected to start {prefix!r}')
            bad.append(f.name)
        if length and len(raw) != length:
            notes.append(f'expected {length} chars')
            if f.name not in bad:
                bad.append(f.name)
    print(f'{f.name:26} {len(raw):>5}  {", ".join(notes) or "looks right"}')

print()
if bad:
    print('Needs attention:')
    for n in bad:
        print(f'  {n}')
    print()
    print('A value marked DOUBLE ENCRYPTED cannot be repaired by retyping alone')
    print('if whatever wrote it is still doing so. Anything else here just')
    print('needs entering again under Settings.')
else:
    print('Every encrypted value decrypts to something of the expected shape.')
print()
