"""One-time helper: run the OAuth flow and save a refresh token for GA4 access.

Use this when the service account can't be granted access to the GA4 property
(e.g., Google Workspace external-sharing restrictions). The refresh token persists
indefinitely for users in the OAuth Client's "Test users" list (or for all users
if the OAuth Client is in Production mode).

Setup before running:
  1. Google Cloud Console -> APIs & Services -> OAuth consent screen
       - User Type: External (or Internal if available for your Workspace)
       - Add gdowns@lmtribune.com to "Test users" if you went with External + Testing
  2. APIs & Services -> Credentials -> + Create Credentials -> OAuth Client ID
       - Application type: Desktop app
       - Name: e.g. "Funnel Tracker Desktop"
       - Click Create, then Download JSON
  3. Save the downloaded JSON in this directory as `oauth-client.json`

Run:
    python auth_ga4.py

This opens a browser window. Sign in with the Google account that has GA4 access
to property 375749594, click through the consent prompt, and the script will
save `ga4-token.json`. After that, run.py and `python -m sources.ga4` will work.
"""

import sys
from pathlib import Path

from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ["https://www.googleapis.com/auth/analytics.readonly"]
CLIENT_SECRETS = "oauth-client.json"
TOKEN_PATH = "ga4-token.json"


def main() -> None:
    if not Path(CLIENT_SECRETS).exists():
        print(f"ERROR: {CLIENT_SECRETS} not found in current directory.")
        print(
            "Download the OAuth Client JSON from Google Cloud Console "
            "(APIs & Services -> Credentials -> click your OAuth Client -> "
            "Download JSON) and save it as ./oauth-client.json before running this."
        )
        sys.exit(1)

    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS, SCOPES)
    creds = flow.run_local_server(
        port=0,
        access_type="offline",
        prompt="consent",
        success_message="Auth complete. You can close this tab.",
    )

    Path(TOKEN_PATH).write_text(creds.to_json(), encoding="utf-8")
    print(f"Saved refresh token to {TOKEN_PATH}.")
    print("Verify with: python -m sources.ga4")


if __name__ == "__main__":
    main()
