"""
Why the panel's Analytics page says Google Analytics is not connected.

Run inside the install, from its backend directory:

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

Reads only. Changes nothing.

The private key is never printed. The service account's own address is, because
that is an identifier you have to paste into Analytics anyway, not a secret.

Two separate things have to be true for that page to work, and the page cannot
tell you which one is missing:

  1. GA_PROPERTY_ID in .env names a property that exists.
  2. The service account has been granted access to THAT property.

A brand new property starts with nobody on it but you. Granting the service
account access to an older property does not carry over.
"""
import json

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)

pid = (getattr(settings, 'GA_PROPERTY_ID', '') or '').strip()
raw = (getattr(obj, 'ga_credentials_json', '') or '').strip()

print()
print('── Configuration ───────────────────────────────────────────────────────')
print(f'  GA_PROPERTY_ID     : {pid or "NOT SET"}')
print(f'  measurement ID     : {obj.google_analytics_id or "not set"}')
print(f'  tag manager ID     : {obj.google_tag_manager_id or "not set"}')
print(f'  service account    : {"saved, " + str(len(raw)) + " chars" if raw else "NOT SAVED"}')

if raw:
    try:
        info = json.loads(raw)
        print(f'  account address    : {info.get("client_email", "?")}')
        print(f'  google project     : {info.get("project_id", "?")}')
        print(f'  private key present: {bool(info.get("private_key"))}')
    except ValueError as exc:
        print(f'  ! the saved JSON does not parse: {exc}')

print()
print('── What the dashboard call actually returns ────────────────────────────')
from apps.accounts.ga_utils import get_ga_dashboard_data
from django.core.cache import cache

# The result is cached for 30 minutes on success, so clear it or this reports
# whatever was true half an hour ago.
cache.delete('ga_dashboard_data_{days}'.format(days=7))
data = get_ga_dashboard_data(days=7)
print(f'  ga_ok    : {data.get("ga_ok")}')
print(f'  ga_error : {data.get("ga_error")}')
print(f'  sessions : {data.get("total_sessions")}   users: {data.get("total_users")}')

print()
if data.get('ga_ok'):
    print('  Connected. If the page still says otherwise, it is reading a cached')
    print('  result. Reload it once more.')
elif not pid:
    print('  No property is set. Add GA_PROPERTY_ID to .env and restart.')
elif raw:
    print('  The credentials and the property ID are both present, so the usual')
    print('  cause is access: that service account has not been added to this')
    print('  property. In Analytics, Admin, with the property selected, open')
    print('  Property access management, add the account address printed above')
    print('  and give it Viewer. It can take a minute or two to take effect.')
print()
