#!/usr/bin/env python3
"""adom-google — programmatic access to a user's Google Workspace from an Adom container.

Layered, REST-direct CLI (no browser automation, no heavyweight base CLI):

  ┌─ adom OAuth layer ── one shared Adom OAuth client + OAuth Gateway redirect →
  │                      a long-lived refresh token stored 0600 per user
  ├─ adom-google ─────── thin, modular wrapper exposing: gmail / contacts /
  │                      (drive, calendar trivially addable — same token plumbing)
  └─ base ────────────── the Google REST APIs themselves, called directly

Generalises (and replaces) the old `adom-gmail`, which was gmail.readonly-only.
The gmail subcommands here are behaviour-compatible with adom-gmail, and the old
~/.config/adom-gmail/config.json is auto-imported on first run.

Auth (one consent, long-lived refresh token):
  adom-google auth            # Adom way — uses the OAuth Gateway (no localhost loopback)
  adom-google auth --manual   # fallback — desktop-client paste flow (like adom-gmail)
  adom-google auth-code '<code>'   # finish the --manual flow
  adom-google status [--json] # show what's authorised (never prints secrets); exit 1 if not

See `adom-google help`.
"""
import sys, os, re, json, base64, argparse, urllib.parse, ssl, socket, hashlib, secrets, struct, time, subprocess, shutil

ADOM_GOOGLE_VERSION = "0.8.32"
if sys.argv[1:2] == ["--version"]:
    print(f"adom-google {ADOM_GOOGLE_VERSION}")
    sys.exit(0)

try:
    import requests
except ModuleNotFoundError:
    # Stock Adom containers (Ubuntu 24.04) do not ship `requests`, and without it
    # the CLI used to die with a traceback before printing any consent URL, which
    # an AI summarised as "bad OAuth". This is a missing module, not an auth
    # problem, so say exactly that and give the one-line fix. install.sh now
    # installs it; this guard covers copies installed before 0.8.23.
    sys.exit("ERROR: adom-google needs the Python 'requests' module, and this container does not have it.\n"
             "  This is a missing dependency, NOT an OAuth problem. Fix (either one):\n"
             "    python3 -m pip install --user --break-system-packages requests\n"
             "    sudo apt-get install -y python3-requests\n"
             "  or reinstall, which now does it for you:  adom-wiki pkg install adom/adom-google-adom")

# --- ACCOUNTS ----------------------------------------------------------------------------------
# adom-google supports multiple Google accounts on one container, fully isolated from each
# other. The unnamed "default" account keeps the original ~/.config/adom-google/ paths; a
# named account (e.g. `--account personal`) lives under ~/.config/adom-google/accounts/<name>/
# with its OWN config.json (refresh token, mode) and its OWN provider.json (which may point at
# a different OAuth client/app — a Workspace-Internal client can't sign in a gmail.com user).
# Select with `--account <name>` (any position) or ADOM_GOOGLE_ACCOUNT=<name>.
def _resolve_account():
    acct = os.environ.get("ADOM_GOOGLE_ACCOUNT", "").strip()
    argv, kept, i = sys.argv, [sys.argv[0]], 1
    while i < len(argv):
        a = argv[i]
        if a == "--account":
            if i + 1 >= len(argv):
                sys.exit("ERROR: --account requires a name, e.g. --account personal")
            acct = argv[i + 1]; i += 2; continue
        if a.startswith("--account="):
            acct = a.split("=", 1)[1]; i += 1; continue
        kept.append(a); i += 1
    sys.argv = kept
    acct = (acct or "default").strip().lower()
    if not acct or not all(c.isalnum() or c in "-_" for c in acct):
        sys.exit(f"ERROR: bad account name {acct!r} — letters/digits/dashes/underscores only")
    return acct

ACCOUNT = _resolve_account()
BASE_CFG_DIR = os.path.expanduser("~/.config/adom-google")
CFG_DIR = BASE_CFG_DIR if ACCOUNT == "default" else os.path.join(BASE_CFG_DIR, "accounts", ACCOUNT)
CFG = os.path.join(CFG_DIR, "config.json")
LEGACY_CFG = os.path.expanduser("~/.config/adom-gmail/config.json")
HERE = os.path.dirname(os.path.realpath(__file__))  # realpath: resolve the ~/.local/bin symlink

# Scopes adom-google requests. Adding drive/calendar later = add one line here and
# re-run `adom-google auth`; everything else (token refresh, API calls) is generic.
# Two scope PROFILES. The consent screen's wording is driven entirely by these.
#   SAFE (default): no "see/delete ALL your files/sheets/calendars" lines. Uses narrowed
#     scopes — drive.file (only files this app creates/opens), calendar.events, gmail.modify
#     (NO permanent delete). Can create+edit Sheets/Docs/Slides it makes (via drive.file)
#     without the broad spreadsheets/documents/presentations "delete all" scopes.
#   FULL (opt-in, `auth --full`): the broad set — can touch ALL of the user's existing
#     Drive/Sheets/Docs/Slides/Calendars. For trusted users who want the whole board.
SCOPES_SAFE = [
    "https://www.googleapis.com/auth/gmail.modify",        # Gmail read/compose/send/labels (NOT permanent-delete)
    "https://www.googleapis.com/auth/contacts",            # People API — contacts read+write
    "https://www.googleapis.com/auth/drive.file",          # only files THIS app creates/opens (not "all your files")
    "https://www.googleapis.com/auth/calendar.events",     # calendar EVENTS (not "delete all your calendars")
    "https://www.googleapis.com/auth/tasks",               # Tasks
    "https://www.googleapis.com/auth/chat.messages",       # Google Chat — read + post (not a "delete all" risk)
    "https://www.googleapis.com/auth/chat.spaces.readonly", # Google Chat — list your spaces
    "https://www.googleapis.com/auth/chat.spaces.create",  # Google Chat — CREATE spaces (create-only, fits SAFE)
    "https://www.googleapis.com/auth/directory.readonly",  # People API — READ the Workspace user directory
    #   (`people find/list`, `chat dm <name>`). Read-only and NOT an Admin SDK scope; see SCOPES_FULL.
]
SCOPES_FULL = [
    "https://www.googleapis.com/auth/gmail.modify",        # Gmail read/compose/send/labels
    "https://www.googleapis.com/auth/contacts",            # contacts read+write
    "https://www.googleapis.com/auth/drive",               # ALL Drive files, sharing, permissions
    "https://www.googleapis.com/auth/spreadsheets",        # ALL Sheets — read+edit
    "https://www.googleapis.com/auth/documents",           # ALL Docs — read+edit
    "https://www.googleapis.com/auth/presentations",       # ALL Slides — read+edit
    "https://www.googleapis.com/auth/calendar",            # full Calendar
    "https://www.googleapis.com/auth/tasks",               # Tasks
    "https://www.googleapis.com/auth/chat.messages",       # Google Chat — read + POST messages as you (user OAuth)
    "https://www.googleapis.com/auth/chat.spaces",         # Google Chat — create spaces + read/update metadata
    #   (supersedes chat.spaces.readonly, which capped FULL users at read-only space listing —
    #    "full" could never create a space no matter what Google granted. wiki-notify-gchat 2026-07-21.)
    "https://www.googleapis.com/auth/chat.memberships",         # add/remove space members + managers
    "https://www.googleapis.com/auth/chat.delete",              # delete conversations/spaces — FULL only, NEVER safe
    "https://www.googleapis.com/auth/chat.customemojis",        # custom emoji
    "https://www.googleapis.com/auth/chat.users.readstate",     # per-user last-read time
    "https://www.googleapis.com/auth/chat.users.spacesettings", # per-user space settings
    "https://www.googleapis.com/auth/chat.users.availability",  # presence
    "https://www.googleapis.com/auth/chat.users.sections",      # sections
    "https://www.googleapis.com/auth/directory.readonly",       # People API — READ the Workspace user
    #   directory (people:searchDirectoryPeople / listDirectoryPeople) for `people find/list` and
    #   `chat dm <name>`. This is NOT an Admin SDK scope: it is the end-user "see your organization's
    #   directory" permission any Workspace member can grant (the data Gmail autocomplete already
    #   shows), read-only, no admin rights involved. Validated against the authorize endpoint
    #   2026-10-30 (accepted; a typo'd variant returns invalid_scope).
    # (Chat works because the shared rock-verbena project has a configured Chat app.)
    # Every string above was validated against Google's authorize endpoint before shipping (issue
    # #233): an invalid scope makes Google reject the WHOLE request with invalid_scope, which
    # breaks sign-in entirely rather than just the new capability. Re-validate before adding more.
    # Admin SDK scopes (admin.directory.*) stay OUT — separate admin-only opt-in (SCOPES_ADMIN).
    #   directory.readonly above is the People API end-user scope, not the Admin SDK. chat.admin.* stays OUT
    # PERMANENTLY: it is an org-wide admin surface, not a "drive my own Chat" capability.
]


# PERSONAL scope set — for connecting a personal @gmail via Adom's global "Adom Personal" OAuth
# client (see ADOM_PERSONAL_* below). Deliberately NON-RESTRICTED so the shared client works for
# every user without Google's restricted-scope CASA assessment: Calendar, Contacts, Tasks, the
# Drive files this app creates, and Gmail SEND/COMPOSE (sensitive, not restricted). NO inbox read
# (gmail.readonly/modify) and NO full Drive — those are restricted and switch on once Adom's
# verification + CASA clears; SCOPES_FULL then applies to the personal client too.
SCOPES_PERSONAL = [
    "https://www.googleapis.com/auth/calendar.events",
    "https://www.googleapis.com/auth/contacts",
    "https://www.googleapis.com/auth/tasks",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/gmail.compose",
]


# ADMIN / Directory bundle — the "separate admin-only opt-in" the policy always anticipated.
# NEVER in safe/full/personal: only a Workspace ADMIN can grant these, and they are org-wide
# (every user, every group), not "drive my own Workspace". Opt in explicitly at auth time with
# `auth --admin` so it costs ONE consent, not a second browser trip later (John, 2026-07-21).
SCOPES_ADMIN = [
    "https://www.googleapis.com/auth/admin.directory.group",         # create/manage groups (distribution lists)
    "https://www.googleapis.com/auth/admin.directory.group.member",  # add/remove group members
    "https://www.googleapis.com/auth/admin.directory.user.readonly", # read the user directory (to populate groups)
    "https://www.googleapis.com/auth/apps.groups.settings",          # Groups Settings API — who may post,
    #   moderation, Collaborative Inbox. WITHOUT it a group can be created but silently rejects
    #   external mail, so a contact@ address would bounce every message from a web form.
]


def _scopes_for(mode):
    if mode == "personal":
        return SCOPES_PERSONAL
    if mode == "youtube":
        return SCOPES_YOUTUBE
    return SCOPES_FULL if mode == "full" else SCOPES_SAFE


# ---------------------------------------------------------------- org onboarding
# Adom's shared OAuth gateway. Its /callback is a PUBLIC, MULTI-TENANT relay: any org can
# register a one-time `state` over the WebSocket and have its auth code relayed back — zero
# per-org config on the gateway, near-zero load (a callback is one tiny request). A new org
# points its OWN Google OAuth client's redirect_uri at this callback and keeps its OWN client
# secret on its OWN container (RELAY mode, broker:false) — Adom never sees the org's secret.
# (Adom employees use BROKER mode instead, where the secret lives on the gateway; see provider.)
ADOM_SHARED_GATEWAY = "https://oauth-9mycwxij7tif.adom.cloud"

# The global "Adom Google Connector" OAuth client — External (User Type = External), so ANY
# Google account OUTSIDE adom.inc can authorize through it: personal @gmail users AND other orgs'
# Workspace employees (the Adom work client is Internal to adom.inc and rejects them). One client
# for everyone external, brokered in BROKER mode, so the SECRET lives only on the gateway
# (creds/adom-connector.json) and the public client_id below is safe to ship. Users connect with
# zero setup via `adom-google connect-personal`. (Constants keep the *_PERSONAL_* names for
# back-compat; they mean the Connector.)
ADOM_PERSONAL_APP = "adom-connector"
ADOM_PERSONAL_CLIENT_ID = "89165832027-6ce69tm6vji6i0v8a5hl6g3cr56d0v0b.apps.googleusercontent.com"

# The nine Google APIs adom-google drives — (console "enable" id, human label).
ONBOARD_APIS = [
    ("gmail.googleapis.com",         "Gmail API"),
    ("people.googleapis.com",        "People API (Contacts)"),
    ("drive.googleapis.com",         "Google Drive API"),
    ("sheets.googleapis.com",        "Google Sheets API"),
    ("docs.googleapis.com",          "Google Docs API"),
    ("slides.googleapis.com",        "Google Slides API"),
    ("calendar-json.googleapis.com", "Google Calendar API"),
    ("tasks.googleapis.com",         "Google Tasks API"),
    ("chat.googleapis.com",          "Google Chat API"),
    # YouTube is enabled up front even though youtube scopes are NOT in the default set: enabling an
    # API costs nothing, and the alternative is what bit us (issue #11) — the first upload fails with
    # SERVICE_DISABLED long after onboarding, when nobody remembers where the project lives.
    ("youtube.googleapis.com",       "YouTube Data API v3 (only needed for `youtube upload`)"),
]

def _enable_apis_url(project=None):
    # One URL that enables ALL of them in one click (the GCP "enable multiple APIs" flow).
    u = "https://console.cloud.google.com/flows/enableapi?apiid=" + ",".join(a for a, _ in ONBOARD_APIS)
    return u + ("&project=" + project if project else "")

def _onboard_config(org=None):
    """The exact, canonical values an org needs to wire up their own Google OAuth client.
    Consumed by the onboarding skill (via `onboard --json`) to auto-fill the Cloud Console."""
    gw = (_provider().get("gateway_url") or ADOM_SHARED_GATEWAY).rstrip("/")
    label = "Adom Workspace CLI" + (f" — {org}" if org else "")
    return {
        "org": org,
        "gateway_url": gw,
        "redirect_uri": gw + "/callback",          # paste verbatim into the OAuth client
        "javascript_origins": [],                   # none needed (no browser JS client)
        "enable_apis_url": _enable_apis_url(),
        "apis": [{"id": a, "label": l} for a, l in ONBOARD_APIS],
        "scopes_safe": SCOPES_SAFE,
        "scopes_full": SCOPES_FULL,
        "consent": {                                # OAuth consent screen settings
            "user_type": "Internal",               # Internal → only the org's Workspace, long-lived tokens
            "app_name": label,
            "client_type": "Web application",       # the OAuth client TYPE to create
            "client_name": label,
        },
        "console": {                                # deep links the skill drives the browser to
            "home":           "https://console.cloud.google.com/",
            "project_create": "https://console.cloud.google.com/projectcreate",
            "consent_screen": "https://console.cloud.google.com/auth/overview",
            "credentials":    "https://console.cloud.google.com/apis/credentials",
            "create_client":  "https://console.cloud.google.com/apis/credentials/oauthclient",
            "chat_config":    "https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat",
        },
    }

ONBOARD_HINT = """Hint: ORG ONBOARDING — drive the user's OWN browser through Google Cloud Console.
Hint: This is the hand-held setup that gives a brand-new org their own Google OAuth client so
Hint: adom-google works for their whole team. Use the `adom-google-onboarding` skill, which
Hint: drives the user's REAL logged-in browser (adom-bridge `nbrowser_*`; pup native-mode as
Hint: fallback) and AUTO-FILLS the Cloud Console fields. Get the exact values to type with:
Hint:     adom-google onboard --json        # redirect_uri, the 9 APIs, scopes, consent settings
Hint: Steps the skill performs (screenshotting + pausing for the user's approval clicks):
Hint:   1. Create/select a Google Cloud project.
Hint:   2. Enable all the APIs in one click (the `enable_apis_url`; includes YouTube Data API v3).
Hint:   3. Configure the OAuth consent screen (User type = Internal; app name from config).
Hint:   4. Create an OAuth client (type = Web application); AUTO-FILL Authorized redirect URI
Hint:      with the gateway `redirect_uri` (the error-prone field — never make the user type it).
Hint:   5. Capture the client_id + client_secret from the final dialog.
Hint:   6. Register for the whole org:  printf '%s\n' "$SECRET" | adom-google org register --org <org> --client-id <id>
Hint:   7. Authorize (full Workspace by default, no mode quiz):   adom-google auth
Hint: `org register` hands the client to Adom's gateway ONCE for the whole org: it verifies the caller
Hint: is an org member (wiki login), checks the client with Google, holds the secret (broker mode), and
Hint: writes the non-secret half to <org>/org-settings so teammates need no setup. `onboard finish
Hint: --relay` keeps the old single-box mode (secret 0600 on this box only; teammates cannot use it)."""

TOKEN_URL = "https://oauth2.googleapis.com/token"
AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
GMAIL_API = "https://gmail.googleapis.com/gmail/v1/users/me"
PEOPLE_API = "https://people.googleapis.com/v1"
CAL_API = "https://www.googleapis.com/calendar/v3"
DRIVE_API = "https://www.googleapis.com/drive/v3"
DRIVE_UPLOAD = "https://www.googleapis.com/upload/drive/v3"
SHEETS_API = "https://sheets.googleapis.com/v4"
DOCS_API = "https://docs.googleapis.com/v1"
SLIDES_API = "https://slides.googleapis.com/v1"
TASKS_API = "https://tasks.googleapis.com/tasks/v1"
YT_API = "https://www.googleapis.com/youtube/v3"
YT_UPLOAD = "https://www.googleapis.com/upload/youtube/v3/videos"
# YouTube is deliberately NOT in safe/full/personal: most users never need it, and youtube.upload is
# a publishing capability. It is ADDED to an account on demand (issue #12):
#   adom-google scopes --require youtube.upload youtube --auto-widen      (or: auth --youtube)
# and the account keeps everything it already holds.
SCOPES_YOUTUBE = ["https://www.googleapis.com/auth/youtube.upload",
                  "https://www.googleapis.com/auth/youtube"]
# Google refuses ONE consent that asks for YouTube AND drive.file together (Error 400
# invalid_request, "This request contains scopes that cannot be requested together"). It appears
# only after the user clicks Allow; the authorize endpoint accepts the URL. Seen on the work client
# (an account holding drive.file, 2026-10-12), on the Connector (issue #12), and in several unrelated
# apps since late 2026-09, always with drive.file in the refused set. A FULL work account (holds
# `drive`, not drive.file) widens fine (issue #11, media@, live).
#
# So YouTube is added one of two ways, and the user only ever sees ONE account:
#   * no drive.file held  -> widen the account's grant in place (one consent, everything kept);
#   * drive.file held     -> a SECOND, YouTube-only grant stored on the same account
#                            (cfg["grants"]["youtube"]). _token_for() hands YouTube API calls that
#                            token and everything else the main one. Google keeps separate refresh
#                            tokens per consent, so the second grant revokes nothing (verified live
#                            2026-11-11: a YouTube-only grant and a drive.file grant for the same user
#                            and client both stay valid across later consents).
# This CLI never sends include_granted_scopes, which is how other apps pull drive.file into a
# YouTube consent by accident.
_YT_INCOMPATIBLE = ["https://www.googleapis.com/auth/drive.file"]
_YT_URL_PREFIXES = ("https://www.googleapis.com/youtube/", "https://youtube.googleapis.com/",
                    "https://www.googleapis.com/upload/youtube/", "https://youtubeanalytics.googleapis.com/",
                    "https://youtubereporting.googleapis.com/")


def _is_yt_scope(scope):
    tail = str(scope).rsplit("/", 1)[-1]
    return tail.startswith("youtube") or tail.startswith("yt-analytics")


def _yt_conflict(scopes):
    """The drive.file-style scopes in `scopes` that Google will not grant in one consent with YouTube."""
    s = set(scopes)
    if not any(_is_yt_scope(x) for x in s):
        return []
    return [x for x in _YT_INCOMPATIBLE if x in s]


def _is_youtube_url(url):
    return str(url or "").startswith(_YT_URL_PREFIXES)


def _yt_grant(cfg):
    """This account's YouTube-only second grant, or None."""
    g = ((cfg or {}).get("grants") or {}).get("youtube")
    return g if g and g.get("refresh_token") else None


def _token_for(cfg, url):
    """Pick the access token for `url`: a YouTube API call uses the account's YouTube grant when it
    has one (it is the explicit YouTube choice, and the only place a Brand Account channel can
    live without taking Gmail/Drive with it); everything else uses the main grant."""
    if _is_youtube_url(url):
        g = _yt_grant(cfg)
        if g:
            return _access_token(g, root=cfg)
    return _access_token(cfg)


def _main_is_youtube_only(cfg):
    """True when the account's MAIN grant is a YouTube-only sign-in (an old `auth --youtube` or a
    dedicated YouTube profile). A Workspace sign-in on top must keep it as the YouTube grant."""
    rec = cfg.get("scopes") or []
    return bool(cfg.get("refresh_token") and rec and all(_is_yt_scope(x) for x in rec))


def _keep_youtube_main(cfg, new_scopes):
    """Before main tokens are replaced: if the current main is YouTube-only and the new main has
    no YouTube scope, move it into grants["youtube"] instead of losing it (issue #12, additive)."""
    if _yt_grant(cfg) or not _main_is_youtube_only(cfg) or any(_is_yt_scope(x) for x in new_scopes):
        return False
    g = {k: cfg[k] for k in ("refresh_token", "access_token", "access_expires", "broker", "app", "scopes",
                             "client_id", "client_secret") if k in cfg}
    g["mode"] = "youtube"
    g["granted_at"] = int(time.time())
    cfg.setdefault("grants", {})["youtube"] = g
    return True


def _tokeninfo_scopes(cfg, root=None):
    """Scopes Google actually granted to this token (tokeninfo), or None if it cannot be asked.
    Never exits: a dead refresh token is a None here, so one broken grant cannot take down
    `scopes` or `auth --youtube` for the whole account."""
    try:
        tok = _access_token(cfg, root=root)
        r = requests.get("https://oauth2.googleapis.com/tokeninfo", params={"access_token": tok}, timeout=20)
        if r.status_code == 200:
            return sorted(r.json().get("scope", "").split())
    except (requests.RequestException, SystemExit):
        pass
    return None

# --- OAuth PROVIDER (gateway URL + client) — deliberately NOT hardcoded -----------------------
# This open-source CLI ships with ZERO provider baked in. The provider (which OAuth gateway to
# talk to + which Google client_id) is resolved at runtime so the public code carries no
# Adom-specific infrastructure. Resolution, later wins:
#   1. bundled provider.json next to the script  (a private *provider* package may ship this)
#   2. legacy credentials.json next to the script (old {clientId,...}; back-compat only)
#   3. ~/.config/adom-google/provider.json        (what `provider set` / the employee pkg writes)
#   4. env: OAUTH_GATEWAY_URL, OAUTH_GATEWAY_WS, ADOM_GOOGLE_CLIENT_ID/SECRET/APP
# Adom employees get the Adom provider via the private `adom-google-adom` package; everyone else
# self-hosts a gateway or buys a managed one (support@adom.inc). See README.
DEFAULT_APP = "adom-google"
PROVIDER_PATH = os.path.join(CFG_DIR, "provider.json")          # per-account when --account is set
BASE_PROVIDER_PATH = os.path.join(BASE_CFG_DIR, "provider.json")  # named accounts inherit from this
BUNDLED_PROVIDER = os.path.join(HERE, "provider.json")
LEGACY_CREDS = os.path.join(HERE, "credentials.json")
MANUAL_REDIRECT = "http://localhost"  # manual desktop-client flow: loopback, user copies the code

ORG_INTEGRATION = "google-oauth"   # file integrations/google-oauth.json on <org>/org-settings


def _wiki_json(args, timeout=25):
    """Run `adom-wiki <args> --json`; return the envelope dict, or None on any failure."""
    if not shutil.which("adom-wiki"):
        return None
    try:
        out = subprocess.run(["adom-wiki", *args, "--json"], capture_output=True, text=True,
                             timeout=timeout).stdout
        return json.loads(out)
    except Exception:
        return None


def _discover_org_providers(only_org=None):
    """Find the Google OAuth provider in the signed-in wiki user's ORG SETTINGS.

    Every wiki org can keep shared, NON-secret integration config on its members-only
    `<org>/org-settings` page (`adom-wiki settings`). An org that has set adom-google up stores
    `integrations/google-oauth.json` there: {client_id, gateway_url, app, mode:"broker", ...}.
    The client secret is never in it; in broker mode it lives on the OAuth gateway, which does
    the token exchange. So any member's first `adom-google auth` just works, with no extra
    package. Returns (orgs_checked, [(org, data), ...])."""
    who = _wiki_json(["whoami"])
    orgs = [o.get("name") for o in (((who or {}).get("data") or {}).get("orgs") or []) if o.get("name")]
    if only_org:
        orgs = [only_org]
    found = []
    for org in orgs:
        d = _wiki_json(["settings", "get", org, ORG_INTEGRATION])
        if not d or d.get("status") != "ok":
            continue
        data = d.get("data") or {}
        if data.get("client_secret") or data.get("secret") is True:
            continue          # never accept a secret from shared settings; it does not belong there
        if data.get("client_id") and data.get("gateway_url"):
            found.append((org, data))
    return orgs, found


def _write_org_provider(org, data):
    """Cache an org-settings provider as provider.json (0600), tagged with its source."""
    prov = {"gateway_url": data["gateway_url"].rstrip("/"), "client_id": data["client_id"],
            "app": data.get("app") or org, "broker": (data.get("mode") or "broker") == "broker",
            "_source": f"org-settings:{org}", "_fetched": time.strftime("%Y-%m-%d")}
    if data.get("gateway_ws"):
        prov["gateway_ws"] = data["gateway_ws"]
    os.makedirs(CFG_DIR, exist_ok=True)
    fd = os.open(PROVIDER_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(prov, f, indent=2)
    os.chmod(PROVIDER_PATH, 0o600)
    return prov


_DISCOVERY = {"tried": False, "candidates": [], "orgs": []}


def _maybe_discover():
    """If NOTHING configures a provider, try the user's org settings once per process.
    An explicit provider (provider set, env, a bundled file) always wins and is never touched."""
    if _DISCOVERY["tried"] or os.environ.get("ADOM_GOOGLE_NO_DISCOVER"):
        return False
    _DISCOVERY["tried"] = True
    orgs, found = _discover_org_providers()
    _DISCOVERY["orgs"], _DISCOVERY["candidates"] = orgs, [o for o, _ in found]
    if len(found) == 1:
        _write_org_provider(*found[0])
        return True
    return False       # none, or several orgs: never guess which org a Google login belongs to


_PROVIDER = None
def _provider():
    """Resolve {app, gateway_url, gateway_ws, gateway_redirect, client_id, client_secret}."""
    global _PROVIDER
    if _PROVIDER is not None:
        return _PROVIDER
    p = {"app": DEFAULT_APP, "gateway_url": None, "gateway_ws": None,
         "client_id": None, "client_secret": None, "broker": None}
    def merge(path, keymap):
        if not os.path.exists(path):
            return
        try:
            with open(path) as f:
                d = json.load(f)
        except Exception:
            return
        for src, dst in keymap.items():
            if d.get(src):
                p[dst] = d[src]
    full = {"gateway_url": "gateway_url", "gateway_ws": "gateway_ws", "client_id": "client_id",
            "client_secret": "client_secret", "app": "app"}
    merge(BUNDLED_PROVIDER, full)
    merge(LEGACY_CREDS, {"clientId": "client_id", "clientSecret": "client_secret", "app": "app"})
    merge(BASE_PROVIDER_PATH, full)
    if PROVIDER_PATH != BASE_PROVIDER_PATH:
        merge(PROVIDER_PATH, full)   # named account's own provider wins over the inherited base
    e = os.environ
    p["gateway_url"]    = e.get("OAUTH_GATEWAY_URL",      p["gateway_url"])
    p["gateway_ws"]     = e.get("OAUTH_GATEWAY_WS",       p["gateway_ws"])
    p["client_id"]      = e.get("ADOM_GOOGLE_CLIENT_ID",  p["client_id"])
    p["client_secret"]  = e.get("ADOM_GOOGLE_CLIENT_SECRET", p["client_secret"])
    p["app"]            = e.get("ADOM_GOOGLE_APP",        p["app"])
    # broker is a bool — merge() skips falsy values, so read it explicitly (later wins).
    for path in (BUNDLED_PROVIDER, BASE_PROVIDER_PATH, PROVIDER_PATH):
        if os.path.exists(path):
            try:
                d = json.load(open(path))
                if "broker" in d:
                    p["broker"] = bool(d["broker"])
            except Exception:
                pass
    if "ADOM_GOOGLE_BROKER" in e:
        p["broker"] = e["ADOM_GOOGLE_BROKER"].strip().lower() in ("1", "true", "yes", "on")
    if p["gateway_url"]:
        p["gateway_url"] = p["gateway_url"].rstrip("/")
        p["gateway_ws"] = (p["gateway_ws"] or "wss://" + p["gateway_url"].split("://", 1)[-1]).rstrip("/")
        p["gateway_redirect"] = p["gateway_url"] + "/callback"
    else:
        p["gateway_redirect"] = None
        if _maybe_discover():             # wrote provider.json from org settings: resolve again
            return _provider()
    _PROVIDER = p
    return p


NO_PROVIDER_HINT = """ERROR: adom-google has no OAuth provider configured (gateway URL + client_id).
Hint: adom-google looks for one in your wiki org's settings first (adom-wiki settings get <org> google-oauth).
Hint:   • Your org already set adom-google up (Adom does)? Run: adom-google provider discover
Hint:     If you belong to SEVERAL such orgs it will not guess: adom-google provider discover --org <org>
Hint:   • First person in your org? Set it up once for everyone: adom-google onboard --org <org>
Hint:   • Personal @gmail or any org, zero setup: adom-google connect-personal (Adom's hosted Connector)
Hint:   • Self-host: adom-google provider set --gateway https://your-gateway.example --client-id <id>
Hint: Check the current provider any time with: adom-google provider show"""

# AI hint emitted whenever adom-google is unconfigured. Per ai-hints-in-clis: this is how the
# CLI forces the installing AI to ASK THE USER the safe/full choice at the moment of setup,
# instead of silently picking. Read at the moment of need — survives context compaction.
SETUP_HINT = """ERROR: adom-google is not authorized yet (no Google token for this container).
Hint: Just run:  adom-google auth
Hint: It prints a Google consent URL — open it in the user's browser; they click Allow ONCE.
Hint: ⚠ That URL contains '&'. Open it as ONE value (a browser tool with the URL inside JSON, or a
Hint:   SINGLE-QUOTED shell arg). If you drop it UNQUOTED into a shell, it truncates at the first
Hint:   '&' and Google shows "Error 400: missing response_type". The auth output shows the safe way.
Hint: Default access is FULL Workspace (Gmail, Contacts, Drive, Sheets, Docs, Slides, Calendar,
Hint: Tasks, Chat + any Google API). There is NO mode question to ask the user — full is the
Hint: default so the tool "just works".
Hint:   (Advanced/rare only: `adom-google auth --safe` grants narrower scopes — just the
Hint:    Drive/Sheets/Docs/Slides files this app creates, no delete-all. Do NOT prompt for it;
Hint:    use --safe only if the user explicitly asks to minimize scopes.)
Hint: The user has ~60 minutes to click Allow (the gateway keeps the sign-in session alive), so
Hint: there's no rush. If they ever see a "Session Expired" page, just re-run `adom-google auth`."""


# ---------------------------------------------------------------- config / creds
def _load():
    cfg = _maybe_load_raw()
    if cfg is None:
        sys.exit(SETUP_HINT)
    if not cfg.get("refresh_token"):
        sys.exit(SETUP_HINT)
    return cfg


def _maybe_load_raw():
    if os.path.exists(CFG):
        with open(CFG) as f:
            return json.load(f)
    # One-time migration from adom-gmail (default account only — named accounts start clean).
    if ACCOUNT == "default" and os.path.exists(LEGACY_CFG):
        with open(LEGACY_CFG) as f:
            legacy = json.load(f)
        legacy.setdefault("scopes", ["https://www.googleapis.com/auth/gmail.readonly"])
        legacy["_migrated_from"] = LEGACY_CFG
        _save(legacy)
        sys.stderr.write(f"[adom-google] imported credentials from {LEGACY_CFG} "
                         f"(gmail.readonly only — run `adom-google auth` to add contacts).\n")
        return legacy
    return None


def _save(cfg):
    os.makedirs(CFG_DIR, exist_ok=True)
    fd = os.open(CFG, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(cfg, f, indent=2)
    os.chmod(CFG, 0o600)


def _client_creds(cfg):
    """client_id (public) + client_secret, from the per-user config or the resolved provider.
    In BROKER mode the secret is None — it lives only on the gateway; the manual/local flow
    still uses a real secret (via `init` or a self-host provider)."""
    pr = _provider()
    cid = cfg.get("client_id") or pr["client_id"]
    csec = cfg.get("client_secret") or pr.get("client_secret")
    if not cid:
        sys.exit(NO_PROVIDER_HINT)
    return cid, csec


# ---------------------------------------------------------------- token / API
def _access_token(cfg, root=None):
    """`root`: when `cfg` is a nested grant (cfg["grants"][...]), the account config to save."""
    # Reuse a cached access token while it's still valid.
    if cfg.get("access_token") and cfg.get("access_expires", 0) > time.time():
        return cfg["access_token"]
    if cfg.get("broker"):
        # Confidential-client broker: the gateway holds the secret and does the refresh.
        pr = _provider()
        if not pr["gateway_url"]:
            sys.exit(NO_PROVIDER_HINT)
        r = requests.post(pr["gateway_url"] + "/refresh",
                          json={"app": cfg.get("app", pr["app"]), "refresh_token": cfg["refresh_token"]},
                          timeout=30)
        if r.status_code != 200:
            if root is not None:
                sys.exit(f"Gateway token refresh failed ({r.status_code}) for this account's YOUTUBE grant.\n"
                         f"Hint: re-add it: adom-google{_acct_flag()} auth --youtube --rebind")
            sys.exit(f"Gateway token refresh failed ({r.status_code}). Re-run `adom-google auth`.")
        j = r.json()
    else:
        cid, csec = _client_creds(cfg if (cfg.get("client_id") or root is None) else root)
        if not csec:
            sys.exit("No client secret for local refresh. Re-run `adom-google auth` (uses the broker).")
        r = requests.post(TOKEN_URL, data={
            "client_id": cid, "client_secret": csec,
            "refresh_token": cfg["refresh_token"], "grant_type": "refresh_token",
        }, timeout=30)
        if r.status_code != 200:
            if root is not None:
                sys.exit(f"Token refresh failed ({r.status_code}) for this account's YOUTUBE grant.\n"
                         f"Hint: re-add it: adom-google{_acct_flag()} auth --youtube --rebind")
            sys.exit(f"Token refresh failed ({r.status_code}). Re-run `adom-google auth`.")
        j = r.json()
    cfg["access_token"] = j["access_token"]
    cfg["access_expires"] = time.time() + int(j.get("expires_in", 3600)) - 60
    if root is None:
        _save(cfg)
    else:
        # A nested grant: update just that grant in the CURRENT file, so a long YouTube upload
        # never writes back a stale copy of the main grant over a re-auth done meanwhile.
        disk = _maybe_load_raw() or root
        for name, g in (disk.get("grants") or {}).items():
            if g.get("refresh_token") == cfg.get("refresh_token"):
                g["access_token"], g["access_expires"] = cfg["access_token"], cfg["access_expires"]
                break
        else:
            disk = root
        _save(disk)
    return cfg["access_token"]


def _request(cfg, method, url, **kw):
    tok = _token_for(cfg, url)
    headers = kw.pop("headers", {})
    headers["Authorization"] = f"Bearer {tok}"
    r = requests.request(method, url, headers=headers, timeout=30, **kw)
    if r.status_code == 403 and "people.googleapis.com" in url:
        sys.exit(f"403 from People API ({r.status_code}). The stored token likely lacks the "
                 f"contacts scope — run `adom-google auth` to re-consent with the full scope set.")
    if r.status_code >= 400:
        sys.exit(f"Google API error ({r.status_code}) {method} {url}:\n{r.text}")
    return r.json() if r.content else {}


def _request_raw(cfg, method, url, **kw):
    """Like _request but returns the RESPONSE and never exits.

    Needed wherever the caller must read status/headers itself or handle a non-2xx on purpose: the
    YouTube resumable upload lives on 308 + the Range/Location headers, which _request throws away."""
    headers = kw.pop("headers", {})
    headers["Authorization"] = "Bearer " + _token_for(cfg, url)
    kw.setdefault("timeout", 120)
    return requests.request(method, url, headers=headers, **kw)


def _gmail(cfg, path):
    return _request(cfg, "GET", f"{GMAIL_API}/{path}")


def _has_scope(cfg, scope):
    return scope in (cfg.get("scopes") or [])


# ---------------------------------------------------------------- gmail (migrated)
def _walk_parts(part, out):
    body = part.get("body", {})
    if body.get("attachmentId"):
        out.append({
            "attachmentId": body["attachmentId"],
            "filename": part.get("filename", ""),
            "mimeType": part.get("mimeType", ""),
            "size": body.get("size", 0),
        })
    for p in part.get("parts", []):
        _walk_parts(p, out)


def _list_attachments(cfg, msg_id):
    msg = _gmail(cfg, f"messages/{msg_id}")
    out = []
    _walk_parts(msg.get("payload", {}), out)
    return out


def _fetch_attachment_bytes(cfg, msg_id, att_id):
    data = _gmail(cfg, f"messages/{msg_id}/attachments/{att_id}")["data"]
    return base64.urlsafe_b64decode(data + "===")


def _unfold(text):
    lines, cur = [], ""
    for raw in text.replace("\r\n", "\n").split("\n"):
        if raw[:1] in (" ", "\t"):
            cur += raw[1:]
        else:
            if cur:
                lines.append(cur)
            cur = raw
    if cur:
        lines.append(cur)
    return lines


def _fmt_dt(val):
    v = val.strip()
    try:
        if v.endswith("Z"):
            return f"{v[0:4]}-{v[4:6]}-{v[6:8]} {v[9:11]}:{v[11:13]} UTC"
        if "T" in v and len(v) >= 15:
            return f"{v[0:4]}-{v[4:6]}-{v[6:8]} {v[9:11]}:{v[11:13]}"
        if len(v) == 8:
            return f"{v[0:4]}-{v[4:6]}-{v[6:8]} (all day)"
    except Exception:
        pass
    return v


def parse_ics(raw):
    text = raw.decode("utf-8", "replace")
    events, ev = [], None
    for line in _unfold(text):
        if line.startswith("BEGIN:VEVENT"):
            ev = {}
        elif line.startswith("END:VEVENT"):
            if ev is not None:
                events.append(ev)
            ev = None
        elif ev is not None and ":" in line:
            key, val = line.split(":", 1)
            name = key.split(";", 1)[0].upper()
            tzid = ""
            if "TZID=" in key:
                tzid = " " + key.split("TZID=", 1)[1].split(";")[0]
            if name in ("SUMMARY", "LOCATION", "DESCRIPTION", "ORGANIZER", "STATUS"):
                ev[name] = val.replace("\\,", ",").replace("\\n", " ").replace("\\;", ";")
            elif name in ("DTSTART", "DTEND"):
                ev[name] = _fmt_dt(val) + tzid
            elif name == "ATTENDEE":
                ev.setdefault("ATTENDEES", []).append(val.replace("mailto:", ""))
    return events


def cmd_gmail_attachments(a):
    cfg = _load()
    atts = _list_attachments(cfg, a.message_id)
    if not atts:
        print("(no attachments on this message)")
        return
    for x in atts:
        print(f"{x['mimeType']:24} {x['size']:>8}B  {x['filename']}\n    id: {x['attachmentId']}")


def cmd_gmail_read(a):
    cfg = _load()
    data = _fetch_attachment_bytes(cfg, a.message_id, a.attachment_id)
    if a.out:
        with open(a.out, "wb") as f:
            f.write(data)
        print(f"Wrote {len(data)} bytes to {a.out}")
    else:
        sys.stdout.buffer.write(data)


def cmd_gmail_ics(a):
    cfg = _load()
    atts = [x for x in _list_attachments(cfg, a.message_id)
            if x["filename"].lower().endswith(".ics") or "calendar" in x["mimeType"]]
    if not atts:
        sys.exit("No .ics/calendar attachment found on this message.")
    for x in atts:
        raw = _fetch_attachment_bytes(cfg, a.message_id, x["attachmentId"])
        for ev in parse_ics(raw):
            print("── Calendar event ──")
            for label in ("SUMMARY", "DTSTART", "DTEND", "LOCATION", "STATUS", "ORGANIZER"):
                if ev.get(label):
                    print(f"  {label.title():10}: {ev[label]}")
            if ev.get("ATTENDEES"):
                print(f"  Attendees : {', '.join(ev['ATTENDEES'])}")
            if ev.get("DESCRIPTION"):
                print(f"  Notes     : {ev['DESCRIPTION']}")
            print()


# ---------------------------------------------------------------- contacts (People API)
def cmd_contacts_create(a):
    cfg = None if a.dry_run else _load()
    person = {}
    if a.name:
        parts = a.name.split(" ", 1)
        person["names"] = [{"givenName": parts[0], "familyName": parts[1] if len(parts) > 1 else ""}]
    if a.email:
        person["emailAddresses"] = [{"value": e} for e in a.email]
    if a.org or a.title:
        org = {}
        if a.org:
            org["name"] = a.org
        if a.title:
            org["title"] = a.title
        person["organizations"] = [org]
    if a.phone:
        person["phoneNumbers"] = [{"value": p} for p in a.phone]
    if a.notes:
        # Google Contacts "Notes" == People API biographies (plain text).
        person["biographies"] = [{"value": a.notes, "contentType": "TEXT_PLAIN"}]
    if a.dry_run:
        print("DRY RUN — would POST to people:createContact:\n")
        print(json.dumps(person, indent=2))
        return
    res = _request(cfg, "POST", f"{PEOPLE_API}/people:createContact",
                   headers={"Content-Type": "application/json"}, json=person)
    rn = res.get("resourceName", "?")
    nm = (res.get("names") or [{}])[0].get("displayName", a.name or "(no name)")
    print(f"✅ Created contact: {nm}")
    print(f"   resourceName: {rn}")
    if res.get("organizations"):
        print(f"   org: {res['organizations'][0].get('name','')}")
    if a.json:
        print(json.dumps(res, indent=2))


def cmd_contacts_list(a):
    cfg = _load()
    params = {
        "personFields": "names,emailAddresses,organizations,phoneNumbers",
        "pageSize": str(a.limit),
        "sortOrder": "LAST_MODIFIED_DESCENDING",
    }
    res = _request(cfg, "GET", f"{PEOPLE_API}/people/me/connections?{urllib.parse.urlencode(params)}")
    conns = res.get("connections", [])
    if a.json:
        print(json.dumps(conns, indent=2))
        return
    if not conns:
        print("(no contacts)")
        return
    for c in conns:
        name = (c.get("names") or [{}])[0].get("displayName", "(no name)")
        email = (c.get("emailAddresses") or [{}])[0].get("value", "")
        org = (c.get("organizations") or [{}])[0].get("name", "")
        line = f"{name:32} {email:30}"
        if org:
            line += f" [{org}]"
        print(line.rstrip())
    if res.get("totalpeople"):
        print(f"\n({len(conns)} shown of {res['totalpeople']} total)")


def cmd_contacts_search(a):
    cfg = _load()
    # People API requires a "warmup" request before the first searchContacts call.
    base = f"{PEOPLE_API}/people:searchContacts"
    rm = "names,emailAddresses,organizations,phoneNumbers,biographies"
    requests.get(base, params={"query": "", "readMask": rm},
                 headers={"Authorization": f"Bearer {_access_token(cfg)}"}, timeout=30)
    time.sleep(1)
    res = _request(cfg, "GET", f"{base}?{urllib.parse.urlencode({'query': a.query, 'readMask': rm, 'pageSize': '20'})}")
    results = res.get("results", [])
    if a.json:
        print(json.dumps(results, indent=2))
        return
    if not results:
        print("(no matches)")
        return
    for r in results:
        p = r.get("person", {})
        name = (p.get("names") or [{}])[0].get("displayName", "(no name)")
        email = (p.get("emailAddresses") or [{}])[0].get("value", "")
        org = (p.get("organizations") or [{}])[0].get("name", "")
        print(f"{name:32} {email:30}" + (f" [{org}]" if org else ""))
        notes = (p.get("biographies") or [{}])[0].get("value", "")
        if a.verbose and notes:
            print(f"    notes: {notes}")
        if a.verbose:
            print(f"    resourceName: {p.get('resourceName','')}")


# ---------------------------------------------------------------- people (Workspace domain directory)
# "Who is Kale?" -> name, email, title, Chat DM space, straight from the Google Workspace directory,
# so nobody has to hand-maintain a people table. Uses the People API DIRECTORY endpoints
# (people:searchDirectoryPeople / people:listDirectoryPeople) under the
# `directory.readonly` scope. That scope is NOT an Admin SDK scope: it is the ordinary
# end-user "see your organization's directory" permission (the same data Gmail autocomplete
# shows), any Workspace member can grant it, and it is read-only. The Admin SDK
# (admin.directory.*) stays out of every tier; see SCOPES_ADMIN.
#
# DOMAIN-ONLY GUARANTEE (Drew, 2026-10-30): every lookup here, and every NAME passed to
# `chat dm`, resolves only to accounts in the signed-in user's OWN Workspace domain, so nobody
# DMs someone outside the team by accident:
#   * the only source is DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE (the domain's user accounts).
#     Never DOMAIN_CONTACT (admin-shared EXTERNAL contacts), never personal Contacts, "other
#     contacts" or Gmail headers;
#   * every result is then filtered to emails ending in @<the signed-in account's domain>, derived
#     from the token at run time (never hard-coded, since other orgs use this public CLI);
#   * when the domain cannot be determined, nothing is returned: an ERROR, never a guess.
SCOPE_DIRECTORY = "https://www.googleapis.com/auth/directory.readonly"
DIRECTORY_SOURCE = "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"
DIRECTORY_READMASK = "names,emailAddresses,organizations,photos"
_CONSUMER_DOMAINS = {"gmail.com", "googlemail.com"}


def _acct_flag():
    return "" if ACCOUNT == "default" else f" --account {ACCOUNT}"


def _people_fail(as_json, msg, hints, code=1, data=None):
    """Print ERROR + Hint lines (or the JSON envelope) and exit with `code`. Never a traceback."""
    if as_json:
        print(json.dumps({"status": "error", "error": msg, "data": data, "hints": hints}, indent=2))
    else:
        sys.stderr.write(f"ERROR: {msg}\n" + "".join(f"Hint: {h}\n" for h in hints))
    sys.exit(code)


def _account_email(cfg):
    """The signed-in account's email, used ONLY to derive the domain filter. Cached in the config
    (keyed to the refresh token, so a re-auth as someone else invalidates it). Tries tokeninfo
    (has `email` when an email/openid scope is held), then Gmail users/me/profile (gmail.modify /
    gmail.compose, which every tier holds), then People people/me. Returns '' when none works."""
    rt_tag = hashlib.sha256((cfg.get("refresh_token") or "").encode()).hexdigest()[:16]
    if cfg.get("account_email") and cfg.get("account_email_for") == rt_tag:
        return cfg["account_email"]
    email = ""
    probes = [
        ("https://oauth2.googleapis.com/tokeninfo", lambda j: j.get("email")),
        (f"{GMAIL_API}/profile", lambda j: j.get("emailAddress")),
        (f"{PEOPLE_API}/people/me?personFields=emailAddresses",
         lambda j: next((e.get("value") for e in j.get("emailAddresses") or []
                         if (e.get("metadata") or {}).get("primary")), None)),
    ]
    for url, pick in probes:
        try:
            if "tokeninfo" in url:
                r = requests.get(url, params={"access_token": _access_token(cfg)}, timeout=20)
            else:
                r = _request_raw(cfg, "GET", url, timeout=20)
            if r.status_code == 200:
                email = (pick(r.json()) or "").strip().lower()
        except (requests.RequestException, ValueError):
            email = ""
        if "@" in email:
            break
    if "@" in email:
        cfg["account_email"], cfg["account_email_for"] = email, rt_tag
        _save(cfg)
        return email
    return ""


def _own_domain(cfg, as_json):
    email = _account_email(cfg)
    if not email:
        _people_fail(as_json, "could not determine which Google account this token belongs to, so the "
                     "domain-only filter cannot be applied; refusing to return anyone.",
                     [f"check the token works: adom-google{_acct_flag()} scopes",
                      f"re-authorize if it is stale: adom-google{_acct_flag()} auth"])
    domain = email.rsplit("@", 1)[1]
    if domain in _CONSUMER_DOMAINS:
        _people_fail(as_json, f"{email} is a personal Google account; it has no Workspace domain "
                     "directory to look people up in.",
                     ["use a Workspace account: adom-google --account <work-account> people find <name>",
                      "or pass an explicit email to the command you were running"])
    return domain


def _primary_email(p):
    ems = p.get("emailAddresses") or []
    for e in ems:
        if (e.get("metadata") or {}).get("primary"):
            return (e.get("value") or "").strip()
    return (ems[0].get("value") or "").strip() if ems else ""


def _person_row(p):
    """Flatten a People API Person into the fields we print / return."""
    n = (p.get("names") or [{}])[0]
    org = (p.get("organizations") or [{}])[0]
    photo = (p.get("photos") or [{}])[0]
    email = _primary_email(p)
    return {
        "name": n.get("displayName") or email or "(no name)",
        "givenName": n.get("givenName", ""),
        "familyName": n.get("familyName", ""),
        "email": email,
        "otherEmails": [e.get("value") for e in (p.get("emailAddresses") or [])
                        if e.get("value") and e.get("value") != email],
        "title": org.get("title", ""),
        "department": org.get("department", ""),
        "photo": photo.get("url", "") if not photo.get("default") else "",
        "resourceName": p.get("resourceName", ""),
    }


def _in_domain(row, domain):
    return row["email"].lower().endswith("@" + domain.lower())


def _match_rank(row, q):
    """Lower is better. Exact identity first so 'Kale' never silently becomes 'Caleb':
    0 exact email / full name; 1 exact first name or email local part; 2 prefix of
    first/last name or local part; 3 anything else the directory returned."""
    q = q.strip().lower()
    email = row["email"].lower()
    local = email.split("@", 1)[0]
    name, given, family = row["name"].lower(), row["givenName"].lower(), row["familyName"].lower()
    if q == email or q == name:
        return 0
    if q == given or q == local:
        return 1
    if any(x.startswith(q) for x in (given, family, local) if x):
        return 2
    return 3


def _directory_get(cfg, endpoint, params, as_json):
    """GET a People API directory endpoint, all pages. Turns every failure into ERROR + Hint."""
    out, page = [], None
    while True:
        q = dict(params)
        if page:
            q["pageToken"] = page
        try:
            r = _request_raw(cfg, "GET", f"{PEOPLE_API}/people:{endpoint}", params=q, timeout=30)
        except requests.RequestException as e:
            _people_fail(as_json, f"could not reach the People API: {e}",
                         ["check network access to people.googleapis.com, then retry"])
        if r.status_code == 403:
            text = r.text or ""
            if "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text or "insufficientPermissions" in text:
                _people_fail(as_json,
                             "this token cannot read the Workspace directory yet (missing the "
                             "directory.readonly scope; it is a read-only, non-admin scope).",
                             [f"widen it, ONE browser Allow click, everything you already hold is kept: "
                              f"adom-google{_acct_flag()} scopes --require directory.readonly --auto-widen",
                              "then re-run the same command"],
                             code=2, data={"missing_scope": SCOPE_DIRECTORY})
            if "SERVICE_DISABLED" in text or "accessNotConfigured" in text:
                _scope_wall_hint(r.url, r)
                _people_fail(as_json, "the People API is not enabled in this OAuth client's Google Cloud project.",
                             ["see the block above for the console link and who can enable it"])
            _people_fail(as_json, f"People API refused the directory read (403): {text[:300]}",
                         ["the Workspace admin may have turned off directory sharing "
                          "(Admin console > Directory > Directory settings > Sharing settings > Contact sharing)",
                          "or this is not a Workspace account; personal Google accounts have no domain directory"])
        if r.status_code >= 400:
            _people_fail(as_json, f"People API error {r.status_code} on {endpoint}: {(r.text or '')[:300]}",
                         ["retry; if it persists check `adom-google scopes` and the People API status"])
        j = r.json() if r.content else {}
        out += j.get("people") or []
        page = j.get("nextPageToken")
        if not page:
            return out


def _people_search(cfg, query, domain, as_json, limit=200):
    """Domain-profile search -> ranked, de-duplicated, own-domain-only rows."""
    people = _directory_get(cfg, "searchDirectoryPeople",
                            {"query": query, "readMask": DIRECTORY_READMASK,
                             "sources": DIRECTORY_SOURCE, "pageSize": 100}, as_json)
    rows, seen = [], set()
    for p in people:
        row = _person_row(p)
        if not row["email"] or not _in_domain(row, domain):
            continue                                  # domain-only guarantee
        key = row["email"].lower()
        if key in seen:
            continue
        seen.add(key)
        row["rank"] = _match_rank(row, query)
        rows.append(row)
    rows.sort(key=lambda r: (r["rank"], r["name"].lower()))
    return rows[:limit]


def _dm_for(cfg, email):
    """(space_name, spaceUri, error) for the 1:1 DM with `email`; never exits."""
    try:
        sp = _find_dm(cfg, email)
    except SystemExit as e:                           # _chat exits on non-404 errors
        return None, None, str(e.code if e.code is not None else "Chat API error")[:300]
    return sp.get("name"), sp.get("spaceUri"), None


def _fmt_person(r):
    extra = " · ".join(x for x in (r["title"], r["department"]) if x)
    return f"  {r['name']:28} {r['email']:32}" + (f" {extra}" if extra else "")


_RANK_LABEL = {0: "exact", 1: "exact first name / email", 2: "prefix", 3: "partial"}


def _limit_arg(minimum):
    def f(v):
        n = int(v)
        if n < minimum:
            raise argparse.ArgumentTypeError(f"must be >= {minimum}")
        return n
    return f


def cmd_people_find(a):
    cfg = _load()
    q = a.query.strip()
    if not q:
        _people_fail(a.json, "empty query", ["pass a name or email, e.g. adom-google people find Kale"])
    domain = _own_domain(cfg, a.json)
    rows = _people_search(cfg, q, domain, a.json, limit=a.limit)
    if not rows:
        _people_fail(a.json, f'no one in the {domain} directory matches "{q}".',
                     ["try a first name, a last name, or the email local part",
                      f"see everyone: adom-google{_acct_flag()} people list"],
                     data={"query": q, "domain": domain, "people": []})
    if a.dm:
        for r in rows[:10]:                           # cap Chat lookups on very broad queries
            r["dm_space"], r["dm_uri"], r["dm_error"] = _dm_for(cfg, r["email"])
    hints = []
    best = [r for r in rows if r["rank"] == rows[0]["rank"]]
    if len(rows) > 1:
        hints.append(f'{len(rows)} people match "{q}"; nothing was picked for you. '
                     "Use the exact email of the one you mean, e.g. "
                     f"adom-google{_acct_flag()} chat dm {rows[0]['email']}")
    if a.dm and any(r.get("dm_space") is None and not r.get("dm_error") for r in rows[:10]):
        hints.append("no DM space exists yet with some of these people; findDirectMessage only finds an "
                     "existing 1:1 conversation. Start one in Google Chat first (this CLI never creates it).")
    if a.dm and len(rows) > 10:
        hints.append("DM spaces resolved for the first 10 matches only; narrow the query for the rest")
    if a.json:
        print(json.dumps({"status": "ok", "data": {"query": q, "domain": domain, "count": len(rows),
                                                    "exact": len(best) == 1 and best[0]["rank"] <= 1,
                                                    "people": rows},
                          "hints": hints}, indent=2, ensure_ascii=False))
        return
    print(f'OK: {len(rows)} match{"es" if len(rows) != 1 else ""} for "{q}" in the {domain} directory')
    for r in rows:
        print(_fmt_person(r) + f"   [{_RANK_LABEL[r['rank']]}]")
        if a.dm and "dm_space" in r:
            if r["dm_space"]:
                print(f"      DM: {r['dm_space']}" + (f"  ·  {r['dm_uri']}" if r.get("dm_uri") else ""))
            elif r.get("dm_error"):
                print(f"      DM: lookup failed ({r['dm_error'].splitlines()[0]})")
            else:
                print("      DM: none yet (no existing 1:1 conversation)")
    for h in hints:
        print(f"Hint: {h}")


def cmd_people_list(a):
    cfg = _load()
    domain = _own_domain(cfg, a.json)
    people = _directory_get(cfg, "listDirectoryPeople",
                            {"readMask": DIRECTORY_READMASK, "sources": DIRECTORY_SOURCE,
                             "pageSize": 1000}, a.json)
    rows, seen = [], set()
    for p in people:
        row = _person_row(p)
        if not row["email"] or not _in_domain(row, domain) or row["email"].lower() in seen:
            continue                                  # domain-only guarantee
        seen.add(row["email"].lower())
        rows.append(row)
    rows.sort(key=lambda r: r["name"].lower())
    if a.limit:
        rows = rows[:a.limit]
    if a.json:
        print(json.dumps({"status": "ok", "data": {"domain": domain, "count": len(rows), "people": rows},
                          "hints": []}, indent=2, ensure_ascii=False))
        return
    print(f"OK: {len(rows)} people in the {domain} directory")
    for r in rows:
        print(_fmt_person(r))
    if not rows:
        print("Hint: an empty directory usually means the Workspace admin turned off directory sharing "
              "(Admin console > Directory > Directory settings > Sharing settings > Contact sharing)")


def _resolve_name_to_email(cfg, name, as_json):
    """`chat dm <name>`: resolve through the DOMAIN directory only. Exactly one best match or ERROR.
    Only an EXACT hit (full name / first name / email local part) can be picked, and it must be
    unique in its tier. Prefix-only hits are listed, never picked: if Kale is not in the directory
    but Kaleb is, `chat dm Kale` errors instead of opening Kaleb's DM. Never guesses."""
    domain = _own_domain(cfg, as_json)
    rows = _people_search(cfg, name, domain, as_json)
    if not rows:
        _people_fail(as_json, f'no one in the {domain} directory matches "{name}"; not guessing.',
                     [f"search more broadly: adom-google{_acct_flag()} people find <part-of-name>",
                      "or pass the exact email: adom-google chat dm <email>"])
    # Only the best EXACT tier (rank <= 1) can be picked, and only when it holds one person.
    if rows[0]["rank"] > 1:
        listing = "; ".join(f"{r['name']} <{r['email']}>" for r in rows[:15])
        _people_fail(as_json, f'no exact match for "{name}" in the {domain} directory (only partial matches: {listing}); not guessing.',
                     ["re-run with the full name or the exact email of the one you mean: adom-google chat dm <email>"],
                     data={"query": name, "domain": domain, "people": rows})
    pick = [r for r in rows if r["rank"] == rows[0]["rank"]]
    if len(pick) != 1:
        listing = "; ".join(f"{r['name']} <{r['email']}>" for r in pick[:15])
        _people_fail(as_json, f'"{name}" matches {len(pick)} people in the {domain} directory: {listing}',
                     ["re-run with the exact email of the one you mean: adom-google chat dm <email>"],
                     data={"query": name, "domain": domain, "people": pick})
    return pick[0]


# ---------------------------------------------------------------- Google Chat (as the user)
# Posts as the SIGNED-IN user (their own Google identity) — no attribution prefix. This is
# distinct from adom-gchat, which posts via an org webhook and prefixes "(on behalf of …)".
# ====================================================================================== dashboard
# `adom-google dashboard`: the Hydrogen Dock Bar card (adom/adom-google#10).
#
# ONE page on 127.0.0.1: which Google accounts are signed in on this container and what each one
# lets the AI do, grouped by service, with the exact widen command for anything missing, the OAuth
# gateway's health and the CLI version. adom-google has no other UI, so this page IS the app.
# dockbar.json at the repo root points the dock at `adom-google dashboard --print-url`.
#
# Security model (the reason the code is shaped like this):
#   * Loopback only. The server binds 127.0.0.1 and refuses any request whose Host header is not a
#     loopback name for its port (a DNS-rebinding guard), and any request that carries forwarding
#     headers. That second rule matters on a cloud container: its VS Code `/proxy/<port>/` path relays
#     requests from the public internet to 127.0.0.1 with NO login (measured 2026-11-11: a cookie-less
#     request reached the page), arriving with the public Host and X-Forwarded-* / CF-* headers.
#   * THE SERVER PROCESS NEVER READS A CREDENTIAL. Each account is checked by a short-lived child,
#     `adom-google --account <name> dashboard --probe-account`, which reuses the CLI's own
#     _maybe_load_raw, cmd_scopes (tokeninfo), _access_token and _account_email with _save stubbed
#     out, so a probe writes NOTHING to disk, and prints one whitelisted JSON line (email, mode,
#     granted scopes, refresh ok). Tokens, secrets and exception text never leave that child.
#   * Read only. No route runs auth or a widen, or touches mail, files or people. Widen commands
#     are TEXT for the user to copy and run themselves. The probe also replaces cmd_auth with a
#     function that refuses, so a future code path cannot start a consent flow from the page.
#   * CORS `*` only on /health and /api/status, which the dock probes cross-origin and which carry
#     no email. /api/accounts and the proxied Hydrogen control routes are same-origin only.
import contextlib, hmac, io, threading, types   # stdlib, used only by the dashboard

DASH_APP = "adom-google-dashboard"
DASH_PORT = 8861
DASH_SLUG = "adom-google"        # the wiki page slug: Send to AI tags threads dock:adom-google
DASH_NOUN = "google"             # the trigger noun the say strip highlights
DASH_NAME = "Adom Google"
DASH_TAB = "Google"              # == dockbar.json webview.title (the dock finds the tab by it)
DASH_PROBE_EVERY = 600           # seconds between background rechecks
DASH_RECHECK_MIN = 20            # the Recheck button cannot fire more often than this
DASH_STATE_DIR = os.path.expanduser("~/.cache/adom-google")
DASH_MIN_SHELL = (1, 0, 142)     # Send to AI needs Hydrogen >= 1.0.142 (say-strip skill)

# The single source for both the page and dockbar.json (tests/test_dashboard.py asserts they match).
DASH_SAY = [
    "summarize my unread gmail",
    "what's on my google calendar tomorrow",
    "find the latest quote in my google drive",
    "put this week's meetings in a google sheet",
    "check my google permissions",
]
DASH_DEMO_PROMPT = (
    "Give me the guided tour of Adom Google, the Google Workspace CLI on this container. "
    "This tour only READS: do not send, draft, reply to, delete, move or label any mail; do not "
    "post or react in Google Chat; do not create, edit or share any file or event; and do not run "
    "`adom-google auth` or any `--auto-widen` command.\n\n"
    "1. Run `adom-google accounts` and `adom-google scopes`, then tell me in plain words which "
    "Google account is signed in and which services you can use for me: Gmail, Drive, "
    "Docs/Sheets/Slides, Calendar, Tasks, Contacts, Chat, the Workspace directory and YouTube. "
    "The Google dashboard tab shows the same thing.\n"
    "2. If a service I might want is missing, show me the exact widen command from the dashboard "
    "and let me decide. Never run it for me.\n"
    "3. Show me one calendar read: my next three events (`adom-google calendar list --max 3`), "
    "titles and times only.\n"
    "4. Tell me how many unread messages are in my Gmail inbox without opening any message: "
    "`adom-google api https://gmail.googleapis.com/gmail/v1/users/me/labels/INBOX`, then read "
    "messagesUnread.\n"
    "5. Ask me what I want to do next, and suggest three things I could say, such as "
    "\"summarize my unread gmail\" or \"put this week's meetings in a google sheet\"."
)
# The app mark: an envelope and a key, i.e. access to your mail and Workspace. A line drawing in
# #e6edf3 (it is loaded as its own document by the favicon and the dock, where currentColor would
# resolve to black). Byte-identical to docs/img/dock-google.svg; the header inlines a currentColor
# copy built from the same paths.
DASH_ICON_PATHS = ('<rect x="1.5" y="3.5" width="14" height="10" rx="1.6"/>'
                   '<path d="M2.2 4.7 8.5 9.6 14.8 4.7"/>'
                   '<circle cx="18" cy="17" r="3"/>'
                   '<path d="M20.1 19.1 22.6 21.6"/>'
                   '<path d="M21.4 20.4 22.6 19.2"/>')
DASH_ICON_SVG = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" '
                 'fill="none" stroke="#e6edf3" stroke-width="1.8" stroke-linecap="round" '
                 'stroke-linejoin="round">' + DASH_ICON_PATHS + '</svg>\n')

# --- services: how granted scopes map onto what the AI can actually do ----------------------------
# A service is USABLE when every part holds a full scope, LIMITED when some part holds only a
# narrower one (or one part is missing), MISSING when nothing is granted. YouTube is opt-in (not in
# any default tier), and the Workspace directory does not exist for a personal @gmail account.
_GAUTH = "https://www.googleapis.com/auth/"
_DASH_FILES_NOTE = "only files adom-google creates or opens"
_DASH_SERVICES = [
    {"key": "gmail", "label": "Gmail", "widen": ["gmail.modify"],
     "parts": [{"name": "Gmail", "full": ["gmail.modify", "gmail.readonly", "https://mail.google.com/"],
                "limited": [("gmail.compose", "drafts and sending only, cannot read the inbox"),
                            ("gmail.send", "sending only, cannot read the inbox"),
                            ("gmail.metadata", "message headers only")]}]},
    {"key": "drive", "label": "Drive", "widen": ["drive"],
     "parts": [{"name": "Drive", "full": ["drive"],
                "limited": [("drive.readonly", "read only"), ("drive.file", _DASH_FILES_NOTE)]}]},
    {"key": "docs", "label": "Docs, Sheets, Slides", "widen": ["documents", "spreadsheets", "presentations"],
     "parts": [{"name": name, "full": [scope, "drive"],
                "limited": [(scope + ".readonly", "read only"), ("drive.readonly", "read only"),
                            ("drive.file", _DASH_FILES_NOTE)]}
               for name, scope in (("Docs", "documents"), ("Sheets", "spreadsheets"),
                                   ("Slides", "presentations"))]},
    {"key": "calendar", "label": "Calendar", "widen": ["calendar"],
     "parts": [{"name": "Calendar", "full": ["calendar"],
                "limited": [("calendar.events", "events only, not the calendar list"),
                            ("calendar.readonly", "read only"),
                            ("calendar.events.readonly", "read events only")]}]},
    {"key": "tasks", "label": "Tasks", "widen": ["tasks"],
     "parts": [{"name": "Tasks", "full": ["tasks"], "limited": [("tasks.readonly", "read only")]}]},
    {"key": "contacts", "label": "Contacts", "widen": ["contacts"],
     "parts": [{"name": "Contacts", "full": ["contacts"], "limited": [("contacts.readonly", "read only")]}]},
    {"key": "chat", "label": "Chat", "widen": ["chat.messages", "chat.spaces"],
     "widen_safe": ["chat.messages", "chat.spaces.readonly"],
     "parts": [{"name": "Messages", "full": ["chat.messages"],
                "limited": [("chat.messages.readonly", "read only"), ("chat.messages.create", "post only")]},
               {"name": "Spaces", "full": ["chat.spaces", "chat.spaces.readonly"], "limited": []}]},
    {"key": "directory", "label": "Workspace directory", "widen": ["directory.readonly"], "workspace_only": True,
     "parts": [{"name": "Directory", "full": ["directory.readonly"], "limited": []}]},
    {"key": "youtube", "label": "YouTube", "widen": ["youtube.upload", "youtube"], "optional": True,
     "parts": [{"name": "YouTube", "full": ["youtube", "youtube.force-ssl"],
                "limited": [("youtube.upload", "upload only"), ("youtube.readonly", "read only")]}]},
]
# The RECORDED mode (what auth asked for). Labelled as a mode, not a capability: what the account
# can really do is the per-service list, read from tokeninfo.
_DASH_TIERS = {"full": "full mode", "safe": "safe mode (narrow Drive)", "personal": "personal mode (Adom Connector)"}
_DASH_BOTH_NOTE = "reads everything, edits only files adom-google creates or opens"


def _dash_tail(scope):
    return scope[len(_GAUTH):] if scope.startswith(_GAUTH) else scope


def _dash_acct_flag(acct):
    return "" if acct in (None, "", "default") else f" --account {acct}"


def _dash_services(granted, mode, email, acct):
    """Group GRANTED scopes (tokeninfo truth, not the recorded request) by service. Returns rows of
    {key, label, state, note, granted[], missing[], widen}; `widen` is a command STRING, never run."""
    have = {_dash_tail(s) for s in (granted or [])}
    consumer = "@" in (email or "") and email.rsplit("@", 1)[1].lower() in _CONSUMER_DOMAINS
    rows = []
    for sv in _DASH_SERVICES:
        mentioned, parts = set(), []
        for p in sv["parts"]:
            mentioned.update(p["full"]); mentioned.update(t for t, _ in p["limited"])
            if any(t in have for t in p["full"]):
                parts.append((p["name"], "full", ""))
                continue
            lims = [(t, n) for t, n in p["limited"] if t in have]
            if not lims:
                parts.append((p["name"], "missing", ""))
            elif "drive.file" in have and any(t.endswith(".readonly") for t, _ in lims):
                parts.append((p["name"], "limited", _DASH_BOTH_NOTE))      # read-all + write-own, together
            else:
                parts.append((p["name"], "limited", "; ".join(dict.fromkeys(n for _, n in lims))))
        n_full = sum(1 for _, st, _ in parts if st == "full")
        n_any = sum(1 for _, st, _ in parts if st != "missing")
        if sv.get("workspace_only") and consumer:
            state = "n/a"
        elif n_full == len(parts):
            state = "usable"
        elif n_any:
            state = "limited"
        else:
            state = "opt-in" if sv.get("optional") else "missing"
        if state == "n/a":
            note = "personal Google accounts have no Workspace directory"
        elif len(parts) == 1:
            note = parts[0][2] if state == "limited" else ""
        elif state == "limited" and all(st == "limited" for _, st, _ in parts) and len({nt for _, _, nt in parts}) == 1:
            note = parts[0][2]                                   # every part limited the same way: say it once
        else:
            note = "; ".join(f"{n}: {nt or ('not granted' if st == 'missing' else 'full')}"
                             for n, st, nt in parts if st != "full") if state == "limited" else ""
        if state == "opt-in":
            note = "not in any default tier; widen once if you want it"
        want = sv.get("widen_safe") if (mode == "safe" and sv.get("widen_safe")) else sv["widen"]
        missing = [t for t in want if t not in have] if state in ("limited", "missing", "opt-in") else []
        widen = (f"adom-google{_dash_acct_flag(acct)} scopes --require {' '.join(missing)} --auto-widen"
                 if missing else None)
        rows.append({"key": sv["key"], "label": sv["label"], "state": state, "note": note,
                     "granted": sorted(t for t in have if t in mentioned), "missing": missing, "widen": widen})
    return rows


# --- the probe: runs in its OWN process, one per account ------------------------------------------
_DASH_SECRET_RE = None


def _dash_redact(text, secrets_=()):
    """Scrub anything token-shaped from a message before it can leave the probe process."""
    global _DASH_SECRET_RE
    import re
    if _DASH_SECRET_RE is None:
        _DASH_SECRET_RE = re.compile(r"ya29\.[A-Za-z0-9._\-]+|1//[A-Za-z0-9._\-]+|GOCSPX-[A-Za-z0-9_\-]+"
                                     r"|(access_token|refresh_token|client_secret)=[^&\s\"']+")
    text = str(text or "")
    for s in secrets_:
        if s and isinstance(s, str) and len(s) >= 8:
            text = text.replace(s, "[redacted]")
    return _DASH_SECRET_RE.sub("[redacted]", text)[:300]


def _dash_refuse_auth(*_a, **_k):
    raise RuntimeError("the dashboard probe never starts an auth or a widen")


def _dash_probe_account():
    """`adom-google --account <name> dashboard --probe-account`: check ONE account, print ONE JSON line.

    Reuses the CLI's own functions so the dashboard can never disagree with the CLI:
      _maybe_load_raw  the account's config (pinned for this process, so every step below shares
                       ONE in-memory copy and its single refreshed access token)
      cmd_scopes       GRANTED scopes from Google's tokeninfo (+ requested, mode)
      _access_token    the refresh path; exercised exactly once per probe, in memory
      _account_email   which Google account the token belongs to
    _save is stubbed for the whole process: a probe never writes the config, never caches a
    tokeninfo answer, and never persists a refreshed token. cmd_auth is replaced with a refusal."""
    os.environ["ADOM_GOOGLE_NO_DISCOVER"] = "1"          # never write provider.json from org settings
    g = globals()
    g["_save"] = lambda cfg: None
    g["cmd_auth"] = _dash_refuse_auth
    out = {"account": ACCOUNT, "authorized": False, "mode": None, "app": None, "auth_path": None,
           "gateway_url": None, "email": "", "granted": None, "requested": [], "youtube_grant": None,
           "refresh": {"ok": None, "how": None, "error": None}, "error": None}
    secrets_ = []

    def emit():
        print(json.dumps(out))

    try:
        cfg = _maybe_load_raw()
    except Exception as e:       # unreadable/corrupt config: say so, never echo it
        out["error"] = f"config.json could not be read ({type(e).__name__})"
        return emit()
    if not cfg or not cfg.get("refresh_token"):
        # Not signed in yet. Still say whether a provider is configured for this account (e.g. a
        # fresh `connect-personal` profile), so first-run status can name the right next step.
        try:
            pr = _provider()
            out["gateway_url"] = pr.get("gateway_url")
            out["app"] = pr.get("app")
        except SystemExit:
            pass
        return emit()
    g["_maybe_load_raw"] = lambda: cfg
    out["authorized"] = True
    out["mode"] = cfg.get("mode")
    secrets_ += [cfg.get("refresh_token"), cfg.get("access_token"), cfg.get("client_secret")]
    for _g in (cfg.get("grants") or {}).values():          # the YouTube grant's tokens too (issue #12)
        if isinstance(_g, dict):
            secrets_ += [_g.get("refresh_token"), _g.get("access_token"), _g.get("client_secret")]
    try:
        pr = _provider()
        secrets_.append(pr.get("client_secret"))
        out["gateway_url"] = pr.get("gateway_url")
        out["app"] = cfg.get("app") or pr.get("app")
    except SystemExit:
        pass
    out["auth_path"] = "broker" if cfg.get("broker") else "local"
    cached_valid = bool(cfg.get("access_token")) and cfg.get("access_expires", 0) > time.time()

    # 1. granted scopes, through the CLI's own `scopes --json` (it refreshes first if the cached
    #    access token has expired: that IS the refresh check in that case).
    buf, phase_err = io.StringIO(), None
    try:
        with contextlib.redirect_stdout(buf):
            cmd_scopes(types.SimpleNamespace(json=True, require=None, auto_widen=False, url_file=None))
        sc = json.loads(buf.getvalue() or "{}")
        out["granted"] = [s for s in sc.get("granted") or [] if isinstance(s, str)]
        out["requested"] = [s for s in sc.get("requested") or [] if isinstance(s, str)]
        out["mode"] = sc.get("mode") or out["mode"]
        yg = (sc.get("grants") or {}).get("youtube")
        if isinstance(yg, dict):
            out["youtube_grant"] = [s for s in yg.get("granted") or [] if isinstance(s, str)]
    except SystemExit as e:
        phase_err = _dash_redact(e.code, secrets_)
    except requests.RequestException as e:
        phase_err = f"could not reach Google ({type(e).__name__})"
    except Exception as e:
        phase_err = f"scope check failed ({type(e).__name__})"
    refresh_phase = bool(phase_err) and any(k in phase_err for k in (
        "refresh failed", "No client secret", "no OAuth provider", "could not reach"))
    if cached_valid:
        # scopes used the cached token, so the refresh path has not run yet: run it once, on a
        # COPY, in memory. Nothing is written; the fresh token dies with this process.
        try:
            trial = dict(cfg)
            trial.pop("access_token", None)
            trial["access_expires"] = 0
            _access_token(trial)
            out["refresh"] = {"ok": True, "how": "refreshed just now (in memory, nothing written)", "error": None}
        except SystemExit as e:
            out["refresh"] = {"ok": False, "how": None, "error": _dash_redact(e.code, secrets_)}
        except requests.RequestException as e:
            out["refresh"] = {"ok": False, "how": None, "error": f"could not reach the token endpoint ({type(e).__name__})"}
        if phase_err:
            out["error"] = phase_err
    elif refresh_phase:
        out["refresh"] = {"ok": False, "how": None, "error": phase_err}
    elif phase_err:
        out["refresh"] = {"ok": True, "how": "refreshed just now (in memory, nothing written)", "error": None}
        out["error"] = phase_err
    else:
        out["refresh"] = {"ok": True, "how": "refreshed just now (in memory, nothing written)", "error": None}

    # 2. which Google account this is (cached in the config by `people find`; else one live lookup).
    if out["refresh"]["ok"] or cached_valid:
        try:
            out["email"] = (_account_email(cfg) or "").strip().lower()
        except (SystemExit, Exception):
            out["email"] = ""
    return emit()


# --- server-side collection (no credentials in this process) --------------------------------------
def _dash_script():
    return os.path.realpath(__file__)


def _dash_account_names():
    """The same rule as `adom-google accounts`: the default account plus every directory under
    accounts/. Lists names only; it never opens a config file."""
    names = ["default"]
    root = os.path.join(BASE_CFG_DIR, "accounts")
    if os.path.isdir(root):
        names += sorted(n for n in os.listdir(root)
                        if os.path.isdir(os.path.join(root, n)) and all(c.isalnum() or c in "-_" for c in n))
    return names


def _dash_run_probe(name):
    """Spawn the probe for one account and parse its one line. Its stderr is NEVER forwarded."""
    env = dict(os.environ, ADOM_GOOGLE_NO_DISCOVER="1")
    env.pop("ADOM_GOOGLE_ACCOUNT", None)
    try:
        r = subprocess.run([sys.executable, _dash_script(), "--account", name, "dashboard", "--probe-account"],
                           capture_output=True, text=True, timeout=90, env=env, stdin=subprocess.DEVNULL)
        line = (r.stdout or "").strip().splitlines()[-1] if (r.stdout or "").strip() else ""
        return json.loads(line) if line else {"account": name, "error": f"probe exited {r.returncode} with no answer"}
    except subprocess.TimeoutExpired:
        return {"account": name, "error": "probe timed out after 90s"}
    except Exception as e:
        return {"account": name, "error": f"probe failed ({type(e).__name__})"}


def _dash_gateway_health(url):
    try:
        r = requests.get(url.rstrip("/") + "/health", timeout=4)
        j = {}
        try:
            j = r.json() if r.content else {}
        except ValueError:
            pass
        apps = [a for a in (j.get("brokerApps") or []) if isinstance(a, str)] if isinstance(j, dict) else []
        ok = r.status_code == 200 and (not isinstance(j, dict) or j.get("ok", True) is not False)
        return {"ok": ok, "status": r.status_code, "apps": apps}
    except requests.RequestException as e:
        return {"ok": False, "status": None, "apps": [], "error": type(e).__name__}


def _dash_collect():
    names = _dash_account_names()
    results = {}
    threads = [threading.Thread(target=lambda n=n: results.__setitem__(n, _dash_run_probe(n)), daemon=True)
               for n in names]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=100)
    probes = [results.get(n) or {"account": n, "error": "probe did not finish"} for n in names]
    gws = sorted({p.get("gateway_url") for p in probes if isinstance(p.get("gateway_url"), str)
                  and p["gateway_url"].startswith(("https://", "http://"))})
    setup = None if gws else _dash_setup_discovery()
    return {"probes": probes, "gateways": {u: _dash_gateway_health(u) for u in gws}, "setup": setup,
            "checked_at": time.time()}


def _dash_setup_discovery():
    """First run (issue #13): nothing on this box configures an OAuth gateway yet. Ask, READ-ONLY,
    whether the user's wiki org offers Google sign-in (the same lookup `adom-google auth` does on
    its own), so status can say "sign in" or "your organization has not set this up", not "broken".
    Never writes provider.json; carries only org names and the gateway host, never a client id."""
    out = {"checked": False, "orgs": [], "found": [], "gateway_url": None, "gateway_ok": None, "error": None}
    try:
        if not _wiki_json(["whoami"]):
            out["error"] = "the adom-wiki CLI is not signed in (or not installed), so org settings could not be read"
            return out
        orgs, found = _discover_org_providers()
    except Exception as e:
        out["error"] = f"org settings could not be read ({type(e).__name__})"
        return out
    out["checked"] = True
    out["orgs"] = [o for o in orgs if isinstance(o, str)][:20]
    out["found"] = [org for org, _d in found]
    if found:
        url = str(found[0][1].get("gateway_url") or "").rstrip("/")
        if url.startswith(("https://", "http://")):
            out["gateway_url"] = url
            out["gateway_ok"] = bool(_dash_gateway_health(url).get("ok"))
    return out


_DASH_CONNECTOR_STEPS = ("Zero setup, for a personal Gmail or any organization: Adom's hosted Connector, "
                         "`adom-google connect-personal`, then `adom-google --account personal auth`. "
                         "Or set Google sign-in up once for your whole organization: `adom-google onboard --org <your-org>`.")


def _dash_clean_probe(p):
    """Whitelist every field the server forwards from a probe, with type checks."""
    def s(v, n=200):
        return v[:n] if isinstance(v, str) else None
    rf = p.get("refresh") if isinstance(p.get("refresh"), dict) else {}
    granted = p.get("granted")
    return {"account": s(p.get("account"), 64) or "?", "authorized": p.get("authorized") is True,
            "mode": s(p.get("mode"), 32), "app": s(p.get("app"), 64), "auth_path": s(p.get("auth_path"), 16),
            "gateway_url": s(p.get("gateway_url")), "email": s(p.get("email"), 254) or "",
            "granted": [x for x in granted if isinstance(x, str)] if isinstance(granted, list) else None,
            "requested": [x for x in (p.get("requested") or []) if isinstance(x, str)],
            "youtube_grant": ([x for x in p.get("youtube_grant") if isinstance(x, str)]
                              if isinstance(p.get("youtube_grant"), list) else None),
            "refresh": {"ok": rf.get("ok") if isinstance(rf.get("ok"), bool) else None,
                        "how": s(rf.get("how")), "error": s(rf.get("error"), 300)},
            "error": s(p.get("error"), 300)}


def _dash_account_view(p):
    p = _dash_clean_probe(p)
    acct, flag = p["account"], _dash_acct_flag(p["account"])
    v = {"account": acct, "has_provider": bool(p["gateway_url"]),
         "email": p["email"], "mode": p["mode"], "tier": _DASH_TIERS.get(p["mode"] or "", p["mode"]),
         "app": p["app"], "auth_path": p["auth_path"], "authorized": p["authorized"], "error": p["error"],
         "services": [], "drift": [], "probe_failed": False,
         "refresh": {"state": "unknown", "text": "not checked", "fix": None}}
    if p["error"] and not p["authorized"]:
        v["probe_failed"] = True
        v["refresh"] = {"state": "fail", "text": p["error"], "fix": f"adom-google{flag} status"}
        return v
    if not p["authorized"]:
        v["refresh"] = {"state": "fail", "text": "not signed in", "fix": f"adom-google{flag} auth"}
        return v
    rf = p["refresh"]
    if rf["ok"] is True:
        v["refresh"] = {"state": "ok", "text": rf["how"] or "refreshes", "fix": None}
    elif rf["ok"] is False:
        v["refresh"] = {"state": "fail", "text": rf["error"] or "refresh failed",
                        "fix": f"adom-google{flag} auth{' --safe' if p['mode'] == 'safe' else ''}"}
    if p["granted"] is not None:
        # YouTube may live on the account's separate YouTube grant (issue #12): it counts for the
        # YouTube row, and the row says where it comes from.
        yt = [x for x in (p["youtube_grant"] or []) if _is_yt_scope(x)]
        v["services"] = _dash_services(list(p["granted"]) + yt, p["mode"], p["email"], acct)
        if p["youtube_grant"] is not None:
            for row in v["services"]:
                if row["key"] == "youtube":
                    if yt:
                        row["note"] = (row["note"] + "; " if row["note"] else "") + "via this account's separate YouTube grant"
                    else:
                        row["note"] = "this account's YouTube grant no longer works"
                        row["widen"] = f"adom-google{flag} auth --youtube --rebind"
        have = {_dash_tail(x) for x in p["granted"]}
        v["drift"] = sorted(_dash_tail(x) for x in p["requested"] if _dash_tail(x) not in have)
    return v


def _dash_facets(views, gateways, probing, version, installed, panel_ok, setup=None):
    """The status pill row. Every facet: {id, label, state ok|warn|fail|unknown, short, detail, _hint}.
    `short` is the pill text, emitted here so the page never truncates prose (status-leds skill)."""
    facets = []
    stale = bool(installed) and installed != version
    if stale:
        facets.append({"id": "dashboard", "label": "Dashboard", "state": "warn", "short": "stale build",
                       "detail": f"This page is served by v{version}, but v{installed} is installed. It switches "
                                 "over by itself within a minute; relaunching from the dock does it now.",
                       "_hint": "adom-google dashboard"})
    elif not panel_ok:
        facets.append({"id": "dashboard", "label": "Dashboard", "state": "warn", "short": "panel missing",
                       "detail": f"v{version} is serving, but the prompts panel module (newbie-panel.js) is not "
                                 "installed next to it, so the Say it panel cannot render.",
                       "_hint": "adom-wiki pkg install adom/adom-google"})
    else:
        facets.append({"id": "dashboard", "label": "Dashboard", "state": "ok", "short": f"v{version} serving",
                       "detail": f"adom-google v{version} is serving this page on 127.0.0.1.", "_hint": None})
    if views is None:
        for fid, label in (("gateway", "Gateway"), ("accounts", "Accounts"), ("token", "Token"), ("services", "Services")):
            facets.append({"id": fid, "label": label, "state": "unknown", "short": "checking",
                           "detail": "The first check is still running.", "_hint": None})
        return facets
    # gateway
    if not gateways:
        st = setup or {}
        if st.get("found") and st.get("gateway_url"):
            org, host = st["found"][0], urllib.parse.urlparse(st["gateway_url"]).netloc
            if st.get("gateway_ok"):
                facets.append({"id": "gateway", "label": "Gateway", "state": "ok", "short": f"ready via {org}",
                               "detail": f"Your organization ({org}) provides Google sign-in through {host}, which "
                                         "answered its health check. `adom-google auth` picks it up by itself.",
                               "_hint": None})
            else:
                facets.append({"id": "gateway", "label": "Gateway", "state": "fail", "short": "not answering",
                               "detail": f"Your organization ({org}) provides Google sign-in through {host}, but it did "
                                         "not answer its health check, so signing in will fail until it is back.",
                               "_hint": f"curl -s {st['gateway_url']}/health"})
        elif st.get("checked"):
            facets.append({"id": "gateway", "label": "Gateway", "state": "warn", "short": "not set up",
                           "detail": "Your organization has not set up Google sign-in yet, so there is no OAuth "
                                     "gateway to sign in through. " + _DASH_CONNECTOR_STEPS,
                           "_hint": "adom-google connect-personal"})
        else:
            why = st.get("error") or "your wiki organization's settings could not be checked"
            facets.append({"id": "gateway", "label": "Gateway", "state": "warn", "short": "not set up",
                           "detail": f"No OAuth gateway is configured on this machine yet, and {why}. If your "
                                     "organization has set up Google sign-in, `adom-google auth` finds it. "
                                     + _DASH_CONNECTOR_STEPS,
                           "_hint": "adom-google provider discover"})
    else:
        down = [u for u, h in gateways.items() if not h.get("ok")]
        hosts = ", ".join(urllib.parse.urlparse(u).netloc for u in gateways)
        if down:
            facets.append({"id": "gateway", "label": "Gateway", "state": "fail", "short": "not answering",
                           "detail": f"The OAuth gateway ({', '.join(urllib.parse.urlparse(u).netloc for u in down)}) "
                                     "did not answer its health check, so broker-mode token refreshes fail until it is back.",
                           "_hint": f"curl -s {down[0].rstrip('/')}/health"})
        else:
            facets.append({"id": "gateway", "label": "Gateway", "state": "ok", "short": "answering",
                           "detail": f"{hosts} answered its health check.", "_hint": None})
    # accounts
    signed = [v for v in views if v["authorized"]]
    failed = [v for v in views if v.get("probe_failed")]
    out = [v for v in views if not v["authorized"] and not v.get("probe_failed")]
    if not signed:
        if failed:
            facets.append({"id": "accounts", "label": "Accounts", "state": "fail", "short": "check failed",
                           "detail": "; ".join(f"{v['account']}: {v['error']}" for v in failed) + ".",
                           "_hint": f"adom-google{_dash_acct_flag(failed[0]['account'])} status"})
        else:
            # Waiting for the user, not broken: amber with the one command to run (issue #13).
            ready = [v for v in out if v.get("has_provider")]
            st = setup or {}
            if ready or gateways or st.get("found") or not st.get("checked"):
                who = (ready or out or [{"account": None}])[0]["account"]
                hint = f"adom-google{_dash_acct_flag(who)} auth"
                detail = ("No Google account is signed in yet. That is the one setup step: run "
                          f"`{hint}` and click Allow once in the browser.")
            else:
                hint = "adom-google connect-personal"
                detail = ("No Google account is signed in yet, and your organization has not set up Google "
                          "sign-in. " + _DASH_CONNECTOR_STEPS)
            facets.append({"id": "accounts", "label": "Accounts", "state": "warn", "short": "not signed in",
                           "detail": detail, "_hint": hint})
    elif len(signed) < len(views):
        bits = ([f"not signed in: {', '.join(v['account'] for v in out)}"] if out else []) + \
               ([f"check failed: {', '.join(v['account'] for v in failed)}"] if failed else [])
        first = (out or failed)[0]
        facets.append({"id": "accounts", "label": "Accounts", "state": "warn",
                       "short": f"{len(signed)}/{len(views)} signed in",
                       "detail": "; ".join(bits).capitalize() + ".",
                       "_hint": f"adom-google{_dash_acct_flag(first['account'])} " + ("auth" if out else "status")})
    else:
        facets.append({"id": "accounts", "label": "Accounts", "state": "ok", "short": f"{len(signed)} signed in",
                       "detail": "Every configured account holds a refresh token.", "_hint": None})
    # token
    bad = [v for v in signed if v["refresh"]["state"] == "fail"]
    if not signed:
        facets.append({"id": "token", "label": "Token", "state": "unknown", "short": "no account",
                       "detail": "Nothing to refresh until an account signs in.", "_hint": None})
    elif bad:
        worst = "fail" if any(v["account"] == "default" for v in bad) or len(bad) == len(signed) else "warn"
        facets.append({"id": "token", "label": "Token", "state": worst, "short": f"{len(bad)} failing",
                       "detail": "Refresh failed for " + ", ".join(f"{v['account']} ({v['refresh']['text']})" for v in bad) + ".",
                       "_hint": bad[0]["refresh"]["fix"]})
    else:
        facets.append({"id": "token", "label": "Token", "state": "ok", "short": "refreshes",
                       "detail": "Every signed-in account refreshed its access token just now (in memory; nothing was written).",
                       "_hint": None})
    # services, judged on the primary account: the default when signed in, else the first signed-in one
    prim = next((v for v in signed if v["account"] == "default"), signed[0] if signed else None)
    if not prim or not prim["services"]:
        facets.append({"id": "services", "label": "Services", "state": "unknown" if not prim else "fail",
                       "short": "unknown" if not prim else "check failed",
                       "detail": (prim or {}).get("error") or "No granted scopes could be read yet.",
                       "_hint": f"adom-google{_dash_acct_flag(prim['account'])} scopes" if prim else None})
    else:
        core = [s for s in prim["services"] if s["state"] not in ("opt-in", "n/a")]
        miss = [s for s in core if s["state"] == "missing"]
        lim = [s for s in core if s["state"] == "limited"]
        usable = len(core) - len(miss)
        who = "" if prim["account"] == "default" else f" ({prim['account']})"
        if miss:
            facets.append({"id": "services", "label": "Services", "state": "warn", "short": f"{usable} of {len(core)} usable",
                           "detail": f"Missing{who}: " + ", ".join(s["label"] for s in miss) + ".", "_hint": miss[0]["widen"]})
        else:
            facets.append({"id": "services", "label": "Services", "state": "ok",
                           "short": f"{usable} usable, {len(lim)} limited" if lim else f"all {usable} usable",
                           "detail": (f"Limited{who}: " + ", ".join(f"{s['label']} ({s['note']})" for s in lim) + "."
                                      if lim else f"Every core service is usable{who}."),
                           "_hint": lim[0]["widen"] if lim else None})
    return facets


def _dash_rollup(facets):
    """Top-level `state` the dock paints the card LED from: the worst facet, fail > warn > unknown."""
    states = {f["state"] for f in facets}
    for s in ("fail", "warn", "unknown"):
        if s in states:
            return s
    return "ok"


def _dash_file_version(path):
    """The ADOM_GOOGLE_VERSION written in the file at `path` NOW (it may be newer than the running process)."""
    import re
    try:
        with open(path, encoding="utf-8", errors="replace") as f:
            head = f.read(4096)
        m = re.search(r'^ADOM_GOOGLE_VERSION = "([^"]+)"', head, re.M)
        return m.group(1) if m else None
    except OSError:
        return None


def _dash_build_id(path):
    try:
        with open(path, "rb") as f:
            return hashlib.sha256(f.read()).hexdigest()[:12]
    except OSError:
        return None


def _dash_panel_path():
    """The vendored newbie-panel.js: the installed copy, else the repo checkout's vendor/ copy."""
    for p in (os.path.expanduser("~/.local/share/adom-google/newbie-panel.js"),
              os.path.join(HERE, "..", "vendor", "newbie-panel.js")):
        if os.path.isfile(p):
            return os.path.realpath(p)
    return None


def _dash_control_url():
    """The Hydrogen control API, read at REQUEST time: its port changes on every ah launch."""
    for name in ("hydrogen-control-url", "hd-control-url"):
        try:
            with open(os.path.expanduser(f"~/.adom/{name}")) as f:
                u = f.read().strip().rstrip("/")
            if u.startswith(("http://", "https://")):
                return u
        except OSError:
            pass
    return "http://127.0.0.1:47084"


class _DashState:
    """Everything the server shows lives here, behind one lock; the probe thread fills it."""

    def __init__(self, port, prober=None):
        self.port, self.prober = port, prober or _dash_collect
        self.version, self.script = ADOM_GOOGLE_VERSION, _dash_script()
        self.build = _dash_build_id(self.script)
        self.started, self.token = time.time(), secrets.token_urlsafe(24)
        self.lock, self.wake = threading.Lock(), threading.Event()
        self.data, self.probing, self.last_probe_start = None, False, 0.0
        self.panel = _dash_panel_path()
        self.panel_sha, self.panel_version = None, None
        if self.panel:
            import re
            with open(self.panel, "rb") as f:
                raw = f.read()
            self.panel_sha = hashlib.sha256(raw).hexdigest()
            m = re.search(rb"version:\s*'([0-9.]+)'", raw)
            self.panel_version = m.group(1).decode() if m else None

    def installed_version(self):
        return _dash_file_version(self.script)

    def probe_once(self):
        with self.lock:
            if self.probing:
                return False
            self.probing, self.last_probe_start = True, time.time()
        try:
            data = self.prober()
        except Exception as e:
            data = {"probes": [], "gateways": {}, "checked_at": time.time(), "error": type(e).__name__}
        with self.lock:
            self.data, self.probing = data, False
        return True

    def loop(self):
        while True:
            self.probe_once()
            self.wake.wait(DASH_PROBE_EVERY)
            self.wake.clear()

    def recheck(self):
        with self.lock:
            if self.probing:
                return "already checking"
            if time.time() - self.last_probe_start < DASH_RECHECK_MIN:
                return "checked moments ago"
        self.wake.set()
        return "started"

    def snapshot(self):
        with self.lock:
            return self.data, self.probing

    def views(self):
        data, probing = self.snapshot()
        if data is None:
            return None, {}, probing, None
        return ([_dash_account_view(p) for p in data.get("probes") or [] if isinstance(p, dict)],
                data.get("gateways") or {}, probing, data.get("checked_at"))

    def setup(self):
        data, _ = self.snapshot()
        return (data or {}).get("setup")

    def health(self):
        inst = self.installed_version()
        return {"ok": True, "app": DASH_APP, "version": self.version, "build": self.build,
                "installed_version": inst, "stale": bool(inst) and inst != self.version,
                "pid": os.getpid(), "port": self.port, "started": int(self.started),
                "panel": {"present": bool(self.panel), "version": self.panel_version, "sha256": self.panel_sha}}

    def status(self):
        views, gws, probing, checked = self.views()
        facets = _dash_facets(views, gws, probing, self.version, self.installed_version(), bool(self.panel),
                              setup=self.setup())
        return {"app": DASH_APP, "state": _dash_rollup(facets), "version": self.version,
                "installed_version": self.installed_version(), "facets": facets, "checking": probing,
                "checked_at": int(checked) if checked else None,
                "age_s": int(time.time() - checked) if checked else None}

    def accounts(self):
        views, gws, probing, checked = self.views()
        return {"version": self.version, "checking": probing, "checked_at": int(checked) if checked else None,
                "accounts": views,
                "first_run": _dash_first_run(views, gws, self.setup()),
                "gateways": [{"host": urllib.parse.urlparse(u).netloc, "ok": bool(h.get("ok")),
                              "apps": h.get("apps") or [], "error": h.get("error")} for u, h in gws.items()]}


def _dash_first_run(views, gateways, setup):
    """The page's "Get started" panel while no account is signed in (issue #13); None otherwise."""
    if views is None or any(v.get("authorized") for v in views):
        return None
    st = setup or {}
    ready = [v for v in views if v.get("has_provider")]
    if ready or gateways or st.get("found"):
        who = (ready or views or [{"account": None}])[0]["account"]
        org = (st.get("found") or [None])[0]
        return {"title": "Sign in to Google",
                "text": (f"Your organization ({org}) provides Google sign-in. " if org else "")
                        + "One step: run this, then click Allow once in the browser that opens.",
                "steps": [f"adom-google{_dash_acct_flag(who)} auth"]}
    if st.get("checked"):
        return {"title": "Your organization has not set up Google sign-in yet",
                "text": "Nothing is broken. Pick one: Adom's hosted Connector works today with zero setup for a "
                        "personal Gmail or any organization; or set Google sign-in up once for your whole organization.",
                "steps": ["adom-google connect-personal", "adom-google --account personal auth",
                          "adom-google onboard --org <your-org>"]}
    return {"title": "Sign in to Google",
            "text": "If your organization has set up Google sign-in, this finds it. Otherwise use Adom's hosted "
                    "Connector (second and third commands).",
            "steps": ["adom-google auth", "adom-google connect-personal", "adom-google --account personal auth"]}


def _dash_allowed_hosts(port):
    """Loopback names only. The container's public VS Code proxy host is deliberately NOT here."""
    return {f"127.0.0.1:{port}", f"localhost:{port}", f"[::1]:{port}"}


# A request relayed from off this machine (the VS Code proxy, Cloudflare, any reverse proxy) carries
# one of these. A direct loopback request (the dock, its webview, curl) never does.
_DASH_FORWARDED = ("x-forwarded-for", "x-forwarded-host", "x-real-ip", "forwarded", "cf-connecting-ip", "cf-ray")


def _dash_make_server(port, prober=None, start_threads=True):
    """Build (not start) the ThreadingHTTPServer bound to 127.0.0.1:<port>. Port 0 picks a free one."""
    import http.server
    state = _DashState(port, prober)

    class Handler(http.server.BaseHTTPRequestHandler):
        server_version, sys_version, protocol_version = "adom-google-dashboard", "", "HTTP/1.1"

        def log_message(self, *_a):        # no request log: nothing about the user lands on disk
            pass

        def _send(self, code, body, ctype="application/json; charset=utf-8", cors=False, extra=None):
            if isinstance(body, (dict, list)):
                body = json.dumps(body).encode()
            elif isinstance(body, str):
                body = body.encode()
            self.send_response(code)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store, must-revalidate")
            self.send_header("X-Content-Type-Options", "nosniff")
            if cors:
                self.send_header("Access-Control-Allow-Origin", "*")
                self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
                self.send_header("Access-Control-Allow-Headers", "Content-Type")
            for k, val in (extra or {}).items():
                self.send_header(k, val)
            if code >= 400:
                self.send_header("Connection", "close")
                self.close_connection = True
            self.end_headers()
            if self.command != "HEAD":
                self.wfile.write(body)

        def _host_ok(self):
            if any(self.headers.get(h) for h in _DASH_FORWARDED):
                self._send(403, {"ok": False, "error": "relayed requests are refused",
                                 "_hint": f"this page only answers on this machine: http://127.0.0.1:{state.port}/ "
                                          "(the container's public proxy path has no login, so it is never served)"})
                return False
            host = (self.headers.get("Host") or "").strip().lower()
            if host and host not in _dash_allowed_hosts(state.port):
                self._send(403, {"ok": False, "error": "host not allowed",
                                 "_hint": f"open the dashboard at http://127.0.0.1:{state.port}/"})
                return False
            return True

        def _origin_ok(self):
            origin = (self.headers.get("Origin") or "").strip().lower()
            if not origin:
                return True                 # not a browser cross-site request
            if urllib.parse.urlparse(origin).netloc in _dash_allowed_hosts(state.port):
                return True
            self._send(403, {"ok": False, "error": "cross-origin request refused"})
            return False

        def _body(self, limit=1 << 20):
            n = int(self.headers.get("Content-Length") or 0)
            return self.rfile.read(min(n, limit)) if n > 0 else b""

        def do_OPTIONS(self):
            if not self._host_ok():
                return
            path = self.path.split("?", 1)[0]
            if path in ("/health", "/api/status"):
                return self._send(204, b"", cors=True)
            if path in ("/updater/status", "/ai-threads/run-prompt", "/ai-threads/run-prompt/status",
                        "/api/accounts", "/api/recheck"):
                return self._send(204, b"")   # same-origin probe answer; NO cross-origin grant
            return self._send(404, {"ok": False, "error": "not found"})

        def do_HEAD(self):
            self.do_GET()

        def do_GET(self):
            if not self._host_ok():
                return
            path, _, query = self.path.partition("?")
            if path in ("/", "/index.html"):
                return self._send(200, _dash_page(state), "text/html; charset=utf-8")
            if path == "/health":
                return self._send(200, state.health(), cors=True)
            if path == "/api/status":
                return self._send(200, state.status(), cors=True)
            if path == "/api/accounts":
                return self._send(200, state.accounts())
            if path in ("/icon.svg", "/favicon.svg", "/favicon.ico"):
                return self._send(200, DASH_ICON_SVG, "image/svg+xml", extra={"Cache-Control": "max-age=3600"})
            if path == "/newbie-panel.js":
                if not state.panel:
                    return self._send(404, {"ok": False, "error": "newbie-panel.js is not installed",
                                            "_hint": "adom-wiki pkg install adom/adom-google"})
                with open(state.panel, "rb") as f:
                    return self._send(200, f.read(), "application/javascript; charset=utf-8")
            if path in ("/updater/status", "/ai-threads/run-prompt/status"):
                if not self._origin_ok():
                    return
                return self._proxy("GET", self.path, b"")
            return self._send(404, {"ok": False, "error": "not found", "path": path[:200]})

        def do_POST(self):
            body = self._body()
            if not self._host_ok() or not self._origin_ok():
                return
            path = self.path.split("?", 1)[0]
            if path == "/ai-threads/run-prompt":
                return self._proxy("POST", self.path, body)
            if path == "/api/recheck":
                return self._send(200, {"ok": True, "recheck": state.recheck()})
            if path == "/api/shutdown":
                sent = self.headers.get("X-Dashboard-Token") or ""
                if not hmac.compare_digest(sent, state.token):
                    return self._send(403, {"ok": False, "error": "bad or missing shutdown token"})
                self._send(200, {"ok": True, "bye": state.version, "pid": os.getpid()})
                threading.Thread(target=self.server.shutdown, daemon=True).start()
                return
            return self._send(404, {"ok": False, "error": "not found", "path": path[:200]})

        def _proxy(self, method, path_qs, body):
            """Raw pass-through to the Hydrogen control API (control-api-proxy skill): status,
            content type and body BYTES unchanged, query string intact. 503 + hint when absent."""
            import http.client
            base = _dash_control_url()
            u = urllib.parse.urlparse(base)
            try:
                cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
                conn = cls(u.hostname, u.port, timeout=120 if method == "POST" else 10)
                headers = {"Content-Type": "application/json"} if method == "POST" else {}
                conn.request(method, (u.path or "") + path_qs, body=body if method == "POST" else None, headers=headers)
                r = conn.getresponse()
                data, ctype = r.read(), r.getheader("Content-Type") or "application/json"
                conn.close()
                return self._send(r.status, data, ctype)
            except Exception as e:
                return self._send(503, {"ok": False, "error": "control API unreachable", "why": type(e).__name__,
                                        "_hint": f"This dashboard proxies {path_qs.split('?')[0]} to the Hydrogen control "
                                                 "API (~/.adom/hydrogen-control-url, read per request). 503 means the route "
                                                 "is wired but no Hydrogen answered here; a 404 would mean it is missing."})

    import http.server as _hs
    srv = _hs.ThreadingHTTPServer(("127.0.0.1", port), Handler)
    srv.daemon_threads = True
    state.port = srv.server_address[1]
    if start_threads:
        threading.Thread(target=state.loop, daemon=True).start()
    return srv, state


def _dash_page(state):
    """The page, with the boot data injected at serve time so the panel mounts synchronously."""
    boot = json.dumps({"version": state.version, "say": DASH_SAY, "demo": DASH_DEMO_PROMPT, "slug": DASH_SLUG,
                       "noun": DASH_NOUN, "name": DASH_NAME, "minShell": list(DASH_MIN_SHELL),
                       "panelVersion": state.panel_version, "port": state.port}).replace("</", "<\\/")
    page = _DASH_HTML
    for key, val in (("__DASH_BOOT__", boot), ("__DASH_MARK__", DASH_ICON_PATHS), ("__DASH_TAB__", DASH_TAB)):
        assert page.count(key) == 1, f"dashboard template: placeholder {key} must appear exactly once"
        page = page.replace(key, val)
    return page


def _dash_state_path(port):
    return os.path.join(DASH_STATE_DIR, f"dashboard-{port}.json")


def _dash_write_state(state):
    os.makedirs(DASH_STATE_DIR, mode=0o700, exist_ok=True)
    p = _dash_state_path(state.port)
    fd = os.open(p + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump({"pid": os.getpid(), "port": state.port, "version": state.version, "build": state.build,
                   "started": int(state.started), "token": state.token, "script": state.script}, f)
    os.replace(p + ".tmp", p)


def _dash_read_state(port):
    try:
        with open(_dash_state_path(port)) as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def _dash_log(msg):
    try:
        os.makedirs(DASH_STATE_DIR, mode=0o700, exist_ok=True)
        fd = os.open(os.path.join(DASH_STATE_DIR, "dashboard.log"), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
        with os.fdopen(fd, "a") as f:
            f.write(time.strftime("%Y-%m-%dT%H:%M:%S ") + msg + "\n")
    except OSError:
        pass


def _dash_claim_webview(url, wait=False):
    """Take over the dock's tab. Only when the DOCK launched us (ADOM_DOCK_WEBVIEW set): that variable
    exists only on the user's own workspace, so a hand-run serve, or one in a cloud container, never
    drives anybody's Hydrogen (dock-dashboard skill)."""
    tab = os.environ.get("ADOM_DOCK_WEBVIEW", "").strip()
    if not tab or not shutil.which("adom-cli"):
        return
    try:
        p = subprocess.Popen(["adom-cli", "hydrogen", "webview", "open-or-refresh", "--name", tab, "--url", url],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                             start_new_session=True)
        if wait:
            p.wait(timeout=20)
    except Exception as e:
        _dash_log(f"webview claim failed ({type(e).__name__})")


def _dash_watch_binary(srv, state):
    """Converge after an update without a re-click: when the file we were started from now carries a
    different version AND that build answers --version, hand the port to it (same pid, via exec)."""
    while True:
        time.sleep(60)
        inst = state.installed_version()
        if not inst or inst == state.version:
            continue
        try:
            r = subprocess.run([sys.executable, state.script, "--version"], capture_output=True, text=True, timeout=20)
        except Exception:
            continue
        if r.returncode != 0 or not r.stdout.strip().endswith(inst):
            continue
        _dash_log(f"v{state.version} handing port {state.port} to installed v{inst}")
        try:
            srv.server_close()
        finally:
            os.execv(sys.executable, [sys.executable, state.script, "dashboard", "--foreground", "--port", str(state.port)])


def _dash_serve_foreground(port):
    """Run the server in THIS process (what the detached child runs; also for debugging)."""
    import signal
    try:
        srv, state = _dash_make_server(port)
    except OSError as e:
        _dash_log(f"bind 127.0.0.1:{port} failed ({e.errno})")
        sys.exit(f"ERROR: could not bind 127.0.0.1:{port} ({os.strerror(e.errno) if e.errno else e}).\n"
                 f"Hint: another program holds it; pick another port: adom-google dashboard --port {port + 1}")
    _dash_write_state(state)
    _dash_log(f"v{state.version} serving http://127.0.0.1:{state.port}/ pid {os.getpid()}")
    url = f"http://127.0.0.1:{state.port}/"
    threading.Thread(target=_dash_claim_webview, args=(url, True), daemon=True).start()
    threading.Thread(target=_dash_watch_binary, args=(srv, state), daemon=True).start()
    signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=srv.shutdown, daemon=True).start())
    try:
        srv.serve_forever(poll_interval=0.5)
    except KeyboardInterrupt:
        pass
    finally:
        cur = _dash_read_state(state.port)
        if cur and cur.get("pid") == os.getpid():
            try:
                os.remove(_dash_state_path(state.port))
            except OSError:
                pass
        _dash_log(f"v{state.version} stopped (pid {os.getpid()})")


def _dash_port_open(port):
    """'In use' means a completed TCP connect; refused AND timed out both mean free (WSL2 mirrored
    networking can time out on a free loopback port, adom-lbr-dockbar skill)."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1.0)
    try:
        s.connect(("127.0.0.1", port))
        return True
    except OSError:
        return False
    finally:
        s.close()


def _dash_get_health(port):
    """(kind, health): kind None = nothing listening, 'ours', or 'foreign'."""
    if not _dash_port_open(port):
        return None, None
    try:
        import urllib.request
        with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2) as r:
            d = json.loads(r.read() or b"{}")
        return ("ours" if isinstance(d, dict) and d.get("app") == DASH_APP else "foreign"), d
    except Exception:
        return "foreign", None


def _dash_listen_pids(port):
    """Who holds the LISTEN socket on <port>: /proc/net/tcp{,6} inode -> /proc/*/fd (never argv)."""
    inodes = set()
    for tbl in ("/proc/net/tcp", "/proc/net/tcp6"):
        try:
            with open(tbl) as f:
                next(f, None)
                for line in f:
                    cols = line.split()
                    if len(cols) > 9 and cols[3] == "0A" and int(cols[1].rsplit(":", 1)[1], 16) == port:
                        inodes.add(cols[9])
        except OSError:
            pass
    pids = set()
    if not inodes:
        return pids
    for pid in os.listdir("/proc"):
        if not pid.isdigit():
            continue
        try:
            for fd in os.listdir(f"/proc/{pid}/fd"):
                link = os.readlink(f"/proc/{pid}/fd/{fd}")
                if link.startswith("socket:[") and link[8:-1] in inodes:
                    pids.add(int(pid))
                    break
        except OSError:
            continue
    return pids


def _dash_is_our_server(pid):
    """argv is only a SAFETY FILTER on a pid we already found by port ownership."""
    if pid in (os.getpid(), os.getppid()):
        return False
    try:
        with open(f"/proc/{pid}/cmdline", "rb") as f:
            argv = [x.decode(errors="replace") for x in f.read().split(b"\0") if x]
    except OSError:
        return False
    return (any(os.path.basename(x).startswith("adom-google") for x in argv[:2])
            and "dashboard" in argv and "--foreground" in argv)


def _dash_retire(port, health):
    """Stand down the instance on <port>: politely (its own shutdown token), then SIGTERM to the
    verified port owner. Returns '' when the port is free, else the reason it is not."""
    import signal
    st = _dash_read_state(port)
    if st and health and st.get("pid") == health.get("pid") and st.get("token"):
        try:
            import urllib.request
            req = urllib.request.Request(f"http://127.0.0.1:{port}/api/shutdown", data=b"{}", method="POST",
                                         headers={"X-Dashboard-Token": st["token"], "Content-Type": "application/json"})
            urllib.request.urlopen(req, timeout=3).read()
        except Exception:
            pass
        for _ in range(50):
            if not _dash_port_open(port):
                return ""
            time.sleep(0.1)
    owners = _dash_listen_pids(port)
    ours = [p for p in owners if _dash_is_our_server(p)]
    if not ours:
        return (f"the port is held by pid {', '.join(map(str, sorted(owners)))}, which is not an adom-google dashboard"
                if owners else "could not identify the process holding the port")
    for sig in (signal.SIGTERM, signal.SIGKILL):
        for p in ours:
            try:
                os.kill(p, sig)
            except OSError:
                pass
        for _ in range(50):
            if not _dash_port_open(port):
                return ""
            time.sleep(0.1)
    return "the old dashboard did not exit"


def _dash_say(ok, url, port, pid, reused, as_json, print_url):
    if print_url:
        print(url)                    # EXACTLY the URL on stdout: the dock awaits it
    elif as_json:
        print(json.dumps({"ok": ok, "url": url, "port": port, "pid": pid,
                          "version": ADOM_GOOGLE_VERSION, "reused": reused}))
    else:
        print(f"OK: Adom Google dashboard {'already running' if reused else 'started'} at {url} "
              f"(v{ADOM_GOOGLE_VERSION}, pid {pid})")
        print("Hint: it is the Adom Google card on the Hydrogen Dock Bar; this URL is the same page.")
        print("Hint: it answers on 127.0.0.1 only; a cloud container's public /proxy/<port>/ URL is refused on purpose.")
        print("Hint: stop it with: adom-google dashboard --stop" + ("" if port == DASH_PORT else f" --port {port}"))


def _dash_fail(msg, hints, as_json):
    if as_json:
        print(json.dumps({"ok": False, "error": msg, "hints": hints}))
    else:
        sys.stderr.write(f"ERROR: {msg}\n" + "".join(f"Hint: {h}\n" for h in hints))
    sys.exit(1)


def _dash_launch(port, print_url, as_json, argv_tail):
    """Idempotent, version-aware, self-backgrounding serve (the dock's three rules)."""
    script = _dash_script()
    # 0. Am I the installed build? The dock can update the package while this step runs, so this
    #    process may be the OLD code; hand off to the file on disk once (guarded against loops).
    disk = _dash_file_version(script)
    if disk and disk != ADOM_GOOGLE_VERSION and not os.environ.get("ADOM_GOOGLE_DASH_HANDOFF"):
        os.execve(sys.executable, [sys.executable, script, "dashboard", *argv_tail],
                  dict(os.environ, ADOM_GOOGLE_DASH_HANDOFF="1"))
    url = f"http://127.0.0.1:{port}/"
    build = _dash_build_id(script)
    kind, h = _dash_get_health(port)
    if kind == "ours" and h.get("version") == ADOM_GOOGLE_VERSION and h.get("build") == build:
        _dash_claim_webview(url)
        return _dash_say(True, url, port, h.get("pid"), True, as_json, print_url)
    if kind == "ours":
        sys.stderr.write(f"WARN: the running dashboard is v{h.get('version')} (build {h.get('build')}); "
                         f"this is v{ADOM_GOOGLE_VERSION} (build {build}). Restarting it.\n")
        why = _dash_retire(port, h)
        if why:
            _dash_fail(f"could not retire the old dashboard on port {port}: {why}",
                       [f"stop it by hand, then retry: adom-google dashboard --stop --port {port}",
                        f"or use another port: adom-google dashboard --port {port + 1}"], as_json)
    elif kind == "foreign":
        owners = sorted(_dash_listen_pids(port))
        _dash_fail(f"port {port} is held by something that is not the adom-google dashboard"
                   + (f" (pid {', '.join(map(str, owners))})" if owners else ""),
                   [f"use another port: adom-google dashboard --port {port + 1}"], as_json)
    env = dict(os.environ)
    env.pop("ADOM_GOOGLE_DASH_HANDOFF", None)
    subprocess.Popen([sys.executable, script, "dashboard", "--foreground", "--port", str(port)],
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                     start_new_session=True, close_fds=True, env=env, cwd="/")
    deadline = time.time() + 15
    while time.time() < deadline:
        time.sleep(0.2)
        kind, h = _dash_get_health(port)
        if kind == "ours" and h.get("version") == ADOM_GOOGLE_VERSION:
            return _dash_say(True, url, port, h.get("pid"), False, as_json, print_url)
    _dash_fail(f"the dashboard did not answer on {url} within 15s",
               ["run it in the foreground to see why: adom-google dashboard --foreground",
                f"its log: {os.path.join(DASH_STATE_DIR, 'dashboard.log')}"], as_json)


def _dash_stop(port, as_json):
    kind, h = _dash_get_health(port)
    if kind is None:
        if as_json:
            print(json.dumps({"ok": True, "stopped": False, "port": port}))
        else:
            print(f"OK: no dashboard is running on port {port}.")
        return
    if kind != "ours":
        _dash_fail(f"port {port} is held by something that is not the adom-google dashboard; leaving it alone",
                   [f"check what it is: ss -ltnp 'sport = :{port}'"], as_json)
    why = _dash_retire(port, h)
    if why:
        _dash_fail(f"could not stop the dashboard on port {port}: {why}", [f"its pid is {h.get('pid')}"], as_json)
    if as_json:
        print(json.dumps({"ok": True, "stopped": True, "port": port, "pid": h.get("pid")}))
    else:
        print(f"OK: stopped the dashboard on port {port} (pid {h.get('pid')}).")


def cmd_dashboard(a):
    if a.probe_account:
        return _dash_probe_account()
    port = a.port or DASH_PORT
    if not 1 <= port <= 65535:
        sys.exit("ERROR: --port must be 1-65535")
    if a.foreground:
        return _dash_serve_foreground(port)
    if a.stop:
        return _dash_stop(port, a.json)
    tail = (["--print-url"] if a.print_url else []) + (["--json"] if a.json else []) + \
           (["--port", str(a.port)] if a.port else [])
    return _dash_launch(port, a.print_url, a.json, tail)

# The page. A RAW string on purpose: in a normal Python string `\b` in a JS regex would become a
# backspace before the browser ever saw it (the dockbar guide's template-literal trap). The test
# suite asserts the served page holds no \x08 and that its script parses.
_DASH_HTML = r"""<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__DASH_TAB__</title>
<link rel="icon" href="icon.svg" type="image/svg+xml">
<style>
:root{--bg:#0d1117;--surface:#161b22;--surface2:#1c232c;--line:#262d36;--text:#e6edf3;--muted:#8b949e;
 --teal:#00b8b1;--led-green:#3fb950;--led-amber:#d29922;--led-red:#f85149;--led-gray:#6e7681;
 --sans:"Familjen Grotesk",system-ui,sans-serif;--body:system-ui,-apple-system,"Segoe UI",sans-serif;
 --mono:"JetBrains Mono",ui-monospace,Consolas,monospace;color-scheme:dark}
*{box-sizing:border-box}
html,body{margin:0;background:var(--bg);color:var(--text);font:400 14px/1.5 var(--body)}
a{color:var(--teal)}
code{font:400 12px/1.5 var(--mono)}
.hdr{height:44px;display:flex;align-items:center;gap:12px;padding:0 16px;background:var(--surface);
 border-bottom:1px solid var(--line);position:sticky;top:0;z-index:20}
.brand{position:relative;display:flex;align-items:baseline;gap:8px;min-width:0;outline:none}
.brand .mark{width:18px;height:18px;align-self:center;flex:none;color:var(--text)}
.brand .name{font:600 15px/1 var(--sans);letter-spacing:-.01em;color:var(--text);white-space:nowrap}
.brand .sub{font-size:13px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pop{position:absolute;top:34px;left:0;min-width:260px;background:var(--surface2);border:1px solid var(--line);
 border-radius:10px;padding:10px 12px;box-shadow:0 12px 32px rgba(0,0,0,.45);visibility:hidden;opacity:0;
 transition:opacity .12s ease 0s,visibility 0s linear .12s;z-index:30;font-size:12.5px}
.brand:hover .pop,.brand:focus-within .pop{visibility:visible;opacity:1;transition:opacity .12s ease .6s,visibility 0s linear .6s}
.pop .row{display:flex;justify-content:space-between;gap:16px;color:var(--muted);padding:2px 0}
.pop .row b{font:400 12px var(--mono);color:var(--text)}
.hctl{margin-left:auto;display:flex;gap:6px;align-items:center}
.ib{width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:none;border:0;
 border-radius:6px;color:var(--muted);cursor:pointer;padding:0}
.ib svg{width:18px;height:18px}
.ib:hover{color:var(--teal);background:rgba(0,184,177,.08)}
.ib:focus-visible{outline:2px solid var(--teal);outline-offset:1px}
.ib[aria-pressed=true]{color:var(--teal);background:rgba(0,184,177,.12);box-shadow:inset 0 0 0 1px rgba(0,184,177,.35)}
.content{padding:4px 16px 24px}
.leds{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px}
.led-pill{display:inline-flex;align-items:center;gap:7px;background:var(--surface);border:1px solid var(--line);
 border-radius:999px;padding:4px 12px;font:400 12.5px/1.4 var(--body);color:var(--text);cursor:pointer}
.led-pill .lbl{color:var(--muted)}
.led-pill[aria-expanded=true]{border-color:var(--teal)}
.dot{width:8px;height:8px;border-radius:50%;background:var(--led-gray);flex:none;display:inline-block}
[data-state=ok] .dot,.dot[data-state=ok]{background:var(--led-green)}
[data-state=busy] .dot,.dot[data-state=busy]{background:var(--led-amber)}
[data-state=bad] .dot,.dot[data-state=bad]{background:var(--led-red)}
.led-detail{margin-top:10px;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:12px 14px;font-size:13.5px}
.led-detail p{margin:6px 0 0;color:var(--muted);max-width:80ch}
.fix{display:flex;flex-wrap:wrap;align-items:center;gap:8px;color:var(--text)}
.cmd{display:inline-flex;align-items:center;gap:4px;background:var(--bg);border:1px solid var(--line);border-radius:8px;
 padding:2px 2px 2px 10px;max-width:100%}
.cmd code{color:var(--text)}
.cmd code .w{white-space:nowrap}
.cmd .ib{width:26px;height:26px}
.cmd .ib svg{width:15px;height:15px}
.sec{margin-top:24px}
.sec-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:10px}
.sec-head h2{margin:0;font:600 15px/1.3 var(--sans);letter-spacing:-.01em}
.sec-head .meta{color:var(--muted);font-size:12.5px}
.btn{font:500 12.5px var(--body);background:none;color:var(--muted);border:1px solid var(--line);border-radius:999px;
 padding:4px 12px;cursor:pointer;margin-left:auto}
.btn:hover{color:var(--teal);border-color:var(--teal)}
.btn:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
.explain{color:var(--muted);font-size:13.5px;margin:6px 0 14px;max-width:80ch}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,400px),1fr));gap:14px}
.card{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:14px 16px 10px;min-width:0}
.card.empty{color:var(--muted)}
.ac-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
.ac-name{font:600 15px/1.3 var(--sans)}
.tier{font-size:11.5px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:1px 8px}
.ac-email{margin-top:2px;font-size:13.5px;overflow-wrap:anywhere}
.muted{color:var(--muted)}
.ac-meta{color:var(--muted);font-size:12.5px;margin-top:4px}
.ac-meta code{color:var(--text)}
.svcs{margin-top:10px;border-top:1px solid var(--line)}
.svc{display:grid;grid-template-columns:14px minmax(0,1fr) auto;column-gap:8px;row-gap:4px;align-items:center;
 padding:8px 0;border-bottom:1px solid var(--line)}
.svc:last-child{border-bottom:0}
.svc .lbl{font-weight:500}
.svc .st{font-size:12.5px;color:var(--muted);text-align:right}
.svc .sub{grid-column:2/4;font-size:12.5px;color:var(--muted);overflow-wrap:anywhere}
.svc .sub code{color:var(--muted)}
.svc .widen{grid-column:2/4}
.drift{margin:8px 0 2px;font-size:12.5px;color:var(--led-amber)}
.more{margin-top:4px;border-top:1px solid var(--line)}
.more summary{cursor:pointer;padding:8px 0;font-size:12.5px;color:var(--muted);list-style-position:inside}
.more summary:hover{color:var(--teal)}
.more summary:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
.more .svcs{margin-top:0;border-top:0}
.notice{margin-top:16px;border:1px solid var(--line);border-left:3px solid var(--led-amber);border-radius:10px;
 background:var(--surface);padding:10px 14px;font-size:13.5px}
.modal{position:fixed;inset:0;background:rgba(1,4,9,.28);display:flex;align-items:flex-start;justify-content:center;
 padding:60px 16px 16px;z-index:300}
.modal[hidden]{display:none}
.dlg{width:min(560px,100%);max-height:calc(100vh - 80px);overflow:auto;background:var(--surface);border:1px solid var(--line);
 border-radius:12px;box-shadow:0 24px 60px rgba(0,0,0,.5)}
.dlg-head{display:flex;align-items:center;padding:12px 14px 12px 18px;border-bottom:1px solid var(--line)}
.dlg-head h2{margin:0;font:600 15px var(--sans)}
.dlg-head .ib{margin-left:auto}
.dlg-body{padding:14px 18px 18px;display:grid;gap:12px}
.scard{border:1px solid var(--line);border-left:3px solid var(--teal);border-radius:10px;padding:12px 14px;background:var(--surface2)}
.scard h3{margin:0 0 4px;font:600 14px var(--sans)}
.scard p{margin:0;color:var(--muted);font-size:13px}
.scard .btn{margin:10px 0 0}
.scard .row{display:flex;justify-content:space-between;gap:12px;font-size:12.5px;color:var(--muted);padding:2px 0}
.scard .row b{font:400 12px var(--mono);color:var(--text);overflow-wrap:anywhere;text-align:right}
#toasts{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;flex-direction:column-reverse;gap:10px;z-index:400}
.toast{min-width:280px;max-width:min(520px,calc(100vw - 32px));background:var(--surface);border:1px solid #30363d;
 border-left:3px solid var(--teal);border-radius:12px;padding:12px 16px;box-shadow:0 18px 50px rgba(0,0,0,.5);font-size:13.5px}
.toast.ok{border-left-color:var(--led-green)}.toast.err{border-left-color:var(--led-red)}
@media (max-width:720px){.brand .sub{display:none}}
</style></head>
<body>
<header class="hdr">
  <div class="brand" tabindex="0">
    <svg class="mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
         stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">__DASH_MARK__</svg>
    <span class="name">Adom Google</span><span class="sub">Google Workspace access</span>
    <div class="pop" role="tooltip" id="pop">
      <div class="row"><span>adom-google</span><b id="pop-ver"></b></div>
      <div class="row"><span>installed</span><b id="pop-inst"></b></div>
      <div class="row"><span>prompts panel module</span><b id="pop-panel"></b></div>
      <div class="row"><span>served at</span><b id="pop-at"></b></div>
      <div class="row"><span>wiki</span><a href="https://wiki.adom.inc/adom/adom-google" target="_blank" rel="noopener">adom/adom-google</a></div>
    </div>
  </div>
  <div class="hctl">
    <button id="help" class="ib" type="button"></button>
    <button id="gear" class="ib" type="button" aria-label="Settings" title="Settings">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
    </button>
  </div>
</header>
<main class="content">
  <div id="newbie"></div>
  <div id="panel-missing" class="notice" hidden>The Say it panel did not load: its module is not installed next to adom-google.
    Fix: <span class="cmd"><code>adom-wiki pkg install adom/adom-google</code></span></div>
  <section class="leds" id="leds" aria-label="Status"></section>
  <div class="led-detail" id="led-detail" hidden></div>
  <section class="sec" aria-labelledby="acct-h">
    <div class="sec-head"><h2 id="acct-h">Accounts and permissions</h2><span class="meta" id="checked">checking</span>
      <button class="btn" id="recheck" type="button" title="Check every account again now">Recheck</button></div>
    <p class="explain">What each Google account signed in on this container lets your AI do, read live from Google.
      This page only reads: it never signs you in, never widens access, and never shows mail, files, events or people.
      To widen a service, copy its command and run it yourself; Google shows one Allow page and keeps what you already granted.</p>
    <div class="grid" id="accounts"><div class="card empty">Checking your accounts...</div></div>
  </section>
</main>
<div class="modal" id="settings" hidden>
  <div class="dlg" role="dialog" aria-modal="true" aria-labelledby="set-h">
    <div class="dlg-head"><h2 id="set-h">Settings</h2>
      <button class="ib" id="set-x" type="button" aria-label="Close settings" title="Close settings">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg></button></div>
    <div class="dlg-body">
      <div class="scard"><h3>How the check works</h3>
        <p>Every 10 minutes, and when you press Recheck, each account is checked by its own short-lived
          adom-google process. It reads that account's config, asks Google's tokeninfo which scopes the token
          really holds, refreshes the access token once in memory to prove the refresh token still works, and
          reports the account's email. It writes nothing to disk, and no token, secret or mail ever reaches this page.</p>
        <button class="btn" id="set-recheck" type="button">Recheck now</button></div>
      <div class="scard"><h3>What this page never does</h3>
        <p>It never signs you in, never widens or revokes access, and never reads mail, files, events, contacts
          or the directory. A widen command is only text: copy it, run it in a terminal (or ask your AI to), and
          approve the one Google page it opens.</p></div>
      <div class="scard"><h3>About</h3>
        <div class="row"><span>adom-google</span><b id="ab-ver"></b></div>
        <div class="row"><span>installed on disk</span><b id="ab-inst"></b></div>
        <div class="row"><span>prompts panel module</span><b id="ab-panel"></b></div>
        <div class="row"><span>served at</span><b id="ab-at"></b></div>
        <div class="row"><span>accounts live in</span><b>~/.config/adom-google</b></div></div>
    </div>
  </div>
</div>
<div id="toasts" aria-live="polite"></div>
<script>window.__DASH__ = __DASH_BOOT__;</script>
<script src="newbie-panel.js"></script>
<script>
(function () {
  'use strict';
  var BOOT = window.__DASH__ || {};
  // the directory the page was served from ('' at http://127.0.0.1:<port>/), so every call is relative
  var BASE = location.pathname.replace(/\/[^\/]*$/, '');
  var boot = window.__agBoot = { complete: false, failed: [], version: BOOT.version, panelMounted: false };
  var COPY_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V6a2 2 0 0 1 2-2h9"/></svg>';
  var PILL = { ok: 'ok', warn: 'busy', fail: 'bad' };
  var ROW = { usable: 'ok', limited: 'busy', missing: 'bad' };
  var facets = [], openPill = null, lastAccounts = null;

  function $(s) { return document.querySelector(s); }
  function esc(s) {
    return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
      return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
    });
  }
  function guard(name, fn) { try { fn(); } catch (e) { boot.failed.push(name + ': ' + (e && e.message)); if (window.console) console.error(e); } }
  function api(path, opts) {
    return fetch(BASE + '/' + path, Object.assign({ cache: 'no-store' }, opts || {})).then(function (r) { return r.json(); });
  }
  function toast(msg, kind, ms) {
    if (window.AdomNewbiePanel && AdomNewbiePanel.toast) return AdomNewbiePanel.toast(msg, kind || 'info', ms);
    var t = document.createElement('div');
    t.className = 'toast ' + (kind || 'info');
    t.setAttribute('role', kind === 'err' ? 'alert' : 'status');
    t.textContent = msg;
    $('#toasts').appendChild(t);
    setTimeout(function () { t.remove(); }, ms || 4000);
    return t;
  }
  function legacyCopy(text) {
    var ta = document.createElement('textarea');
    ta.value = text; ta.setAttribute('readonly', '');
    ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0';
    document.body.appendChild(ta); ta.select();
    var ok = false;
    try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
    ta.remove();
    return ok;
  }
  function copy(text, done) {
    var ok = function () { toast(done || 'Copied to clipboard. Paste it into any AI thread.', 'ok'); };
    var bad = function () { toast('Could not reach the clipboard. Select the text and copy it.', 'err'); };
    if (window.AdomNewbiePanel && AdomNewbiePanel.copyText) return AdomNewbiePanel.copyText(text).then(ok, bad);
    if (legacyCopy(text)) ok(); else bad();
  }
  function cmdHtml(cmd) {
    // one unbreakable span per token, so a command wraps only at spaces, never inside --auto-widen
    var words = String(cmd).split(' ').map(function (w) { return '<span class="w">' + esc(w) + '</span>'; }).join(' ');
    return '<span class="cmd"><code>' + words + '</code><button type="button" class="ib" data-copy="' + esc(cmd) +
      '" aria-label="Copy this command" title="Copy this command">' + COPY_SVG + '</button></span>';
  }
  function ago(ts) {
    var s = Math.max(0, Math.round(Date.now() / 1000 - ts));
    if (s < 45) return 'just now';
    if (s < 5400) return Math.round(s / 60) + ' min ago';
    return Math.round(s / 3600) + ' h ago';
  }
  function verNum(s) { var p = String(s || '').split('.').map(function (x) { return parseInt(x, 10) || 0; }); return [p[0] || 0, p[1] || 0, p[2] || 0]; }
  function verGte(a, b) { for (var i = 0; i < 3; i++) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return true; }

  // ---- the say strip and demo: the SHARED module (newbie-panel skill), mounted, never rebuilt ----
  var demoBusy = false;
  function demoSend() {
    // The demo is a read-only tour run by the AI (this app has nothing to click): it is STAGED in a
    // new thread (submit:false), so nothing runs until the person reads it and presses Enter.
    if (demoBusy) { toast('The demo was just sent. Check your AI threads first.', 'info'); return; }
    demoBusy = true;
    var pending = toast('Opening a new AI thread for the guided demo...', 'info', 120000);
    function done() { if (pending && pending.remove) pending.remove(); setTimeout(function () { demoBusy = false; }, 15000); }
    function fallback(why) {
      done();
      copy(BOOT.demo, 'Copied the demo prompt. Paste it into any AI thread.');
      toast((why ? why + ' ' : '') + 'The demo prompt is on your clipboard instead.', 'err', 9000);
    }
    fetch(BASE + '/updater/status', { cache: 'no-store' })
      .then(function (r) { return r.json(); })
      .then(function (j) { var v = j && j.updater && j.updater.current_version; return (v && !verGte(verNum(v), BOOT.minShell)) ? v : null; },
            function () { return null; })            // fail OPEN: the call itself is the probe
      .then(function (old) {
        if (old) throw new Error('Send to AI needs Hydrogen 1.0.142 or newer (found ' + old + ').');
        var ctl = new AbortController(), timer = setTimeout(function () { ctl.abort(); }, 120000);
        return fetch(BASE + '/ai-threads/run-prompt', {
          method: 'POST', signal: ctl.signal, headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ 'new': true, prompt: BOOT.demo, submit: false, name: BOOT.name + ' - demo', tags: ['dock:' + BOOT.slug] })
        }).then(function (r) {
          clearTimeout(timer);
          return r.json().then(function (j) { return { status: r.status, j: j || {} }; }, function () { return { status: r.status, j: {} }; });
        });
      })
      .then(function (res) {
        if (res.status >= 200 && res.status < 300 && res.j.ok !== false) {
          done();
          toast('Opening a new AI thread with the guided demo staged. Read it, then press Enter there to start.', 'ok', 7000);
        } else {
          fallback((res.j._hints && res.j._hints.note) || res.j.why || res.j.error || ('The AI panel answered ' + res.status + '.'));
        }
      })
      .catch(function (e) {
        fallback(e && e.name === 'AbortError' ? 'No answer from the AI panel within 120s; check your AI threads before trying again.' : (e && e.message));
      });
  }
  function mountPanel(tries) {
    if (!window.AdomNewbiePanel) {
      if (tries < 40) { setTimeout(function () { mountPanel(tries + 1); }, 100); return; }
      $('#panel-missing').hidden = false;
      boot.failed.push('panel: newbie-panel.js did not load');
      return;
    }
    try {
      AdomNewbiePanel.mount({
        mount: '#newbie', app: BOOT.noun, appName: BOOT.name, slug: BOOT.slug, apiBase: BASE,
        toggleButton: '#help', phrases: BOOT.say || [],
        demo: { label: 'Play the demo', meta: 'a read-only tour your AI runs', onPlay: demoSend }
      });
      boot.panelMounted = true;
    } catch (e) {
      boot.failed.push('panel: ' + (e && e.message));
      $('#panel-missing').hidden = false;
    }
  }

  // ---- status pill row (status-leds skill): pills at rest, prose on tap, red carries its fix ----
  function renderLeds(st) {
    facets = (st && st.facets) || [];
    $('#leds').innerHTML = facets.map(function (f) {
      return '<button type="button" class="led-pill" data-id="' + esc(f.id) + '" data-state="' + (PILL[f.state] || 'unknown') +
        '" aria-expanded="' + (openPill === f.id) + '" title="' + esc(f.label) + ': tap for details"><span class="dot"></span><span class="lbl">' +
        esc(f.label) + '</span><span>' + esc(f.short) + '</span></button>';
    }).join('');
    renderDetail();
    $('#pop-inst').textContent = $('#ab-inst').textContent = st && st.installed_version ? 'v' + st.installed_version : 'unknown';
  }
  function renderDetail() {
    var box = $('#led-detail');
    var f = facets.filter(function (x) { return x.id === openPill; })[0];
    if (!f) { box.hidden = true; box.innerHTML = ''; return; }
    box.hidden = false;
    box.innerHTML = (f._hint ? '<div class="fix"><span>' + (f.state === 'ok' ? 'To widen:' : 'Fix:') + '</span>' + cmdHtml(f._hint) + '</div>' : '') +
      '<p>' + esc(f.detail) + '</p>';
  }

  // ---- the app's own content: accounts and permissions ----
  function svcRow(s) {
    var granted = s.granted && s.granted.length ? 'granted: <code>' + s.granted.map(esc).join(' ') + '</code>' : '';
    var sub = [s.note ? esc(s.note) : '', granted].filter(Boolean).join(' · ');
    return '<div class="svc" data-svc="' + esc(s.key) + '" data-state="' + esc(s.state) + '"><span class="dot" data-state="' + (ROW[s.state] || 'unknown') +
      '"></span><span class="lbl">' + esc(s.label) + '</span><span class="st">' + esc(s.state) + '</span>' +
      (sub ? '<div class="sub">' + sub + '</div>' : '') +
      (s.widen ? '<div class="widen">' + cmdHtml(s.widen) + '</div>' : '') + '</div>';
  }
  function card(a) {
    var email = a.email ? esc(a.email) : '<span class="muted">' + (a.authorized ? 'email not readable with these scopes' : 'not signed in') + '</span>';
    var meta = a.app ? 'OAuth app <code>' + esc(a.app) + '</code>' + (a.auth_path === 'broker' ? ', refreshed through the gateway' : (a.auth_path === 'local' ? ', refreshed directly with Google' : '')) : '';
    var tok = a.refresh || { state: 'unknown', text: 'not checked' };
    var html = '<article class="card" data-account="' + esc(a.account) + '"><div class="ac-head"><span class="ac-name">' + esc(a.account) + '</span>' +
      (a.tier ? '<span class="tier">' + esc(a.tier) + '</span>' : '') + '</div><div class="ac-email">' + email + '</div>' +
      (meta ? '<div class="ac-meta">' + meta + '</div>' : '') + '<div class="svcs">' +
      '<div class="svc" data-svc="token"><span class="dot" data-state="' + (PILL[tok.state] || 'unknown') + '"></span><span class="lbl">Token</span><span class="st">' +
      esc(tok.state === 'ok' ? 'refreshes' : (tok.state === 'fail' ? 'failing' : 'unknown')) + '</span><div class="sub">' + esc(tok.text) + '</div>' +
      (tok.fix ? '<div class="widen">' + cmdHtml(tok.fix) + '</div>' : '') + '</div>';
    var shown = (a.services || []).filter(function (s) { return s.state !== 'missing' && s.state !== 'opt-in'; });
    var folded = (a.services || []).filter(function (s) { return s.state === 'missing' || s.state === 'opt-in'; });
    html += shown.map(svcRow).join('') + '</div>';
    if (folded.length) {
      var open = a.account === 'default' && folded.length <= 2;
      html += '<details class="more"' + (open ? ' open' : '') + '><summary>Not granted (' + folded.length + '): ' +
        folded.map(function (s) { return esc(s.label); }).join(', ') + '</summary><div class="svcs">' + folded.map(svcRow).join('') + '</div></details>';
    }
    if (a.drift && a.drift.length) html += '<div class="drift">Requested at sign-in but not granted by Google: <code>' + a.drift.map(esc).join(' ') + '</code></div>';
    if (a.error && a.authorized) html += '<div class="drift">' + esc(a.error) + '</div>';
    return html + '</article>';
  }
  function renderAccounts(d) {
    lastAccounts = d;
    $('#checked').textContent = d.checking ? 'checking now' : (d.checked_at ? 'checked ' + ago(d.checked_at) : 'checking');
    if (!d.accounts) { $('#accounts').innerHTML = '<div class="card empty">Checking your accounts...</div>'; return; }
    var fr = d.first_run ? '<article class="card first-run" data-first-run="1"><div class="ac-head"><span class="ac-name">' + esc(d.first_run.title) +
      '</span></div><p>' + esc(d.first_run.text) + '</p><div class="svcs">' +
      (d.first_run.steps || []).map(function (c) { return '<div class="widen">' + cmdHtml(c) + '</div>'; }).join('') + '</div></article>' : '';
    $('#accounts').innerHTML = fr + (d.accounts.length ? d.accounts.map(card).join('') : '<div class="card empty">No accounts configured.</div>');
  }

  var accTimer = null;
  function pollStatus() { api('api/status').then(function (st) { guard('leds', function () { renderLeds(st); }); }, function () {}); }
  function pollAccounts() {
    clearTimeout(accTimer);
    api('api/accounts').then(function (d) {
      guard('accounts', function () { renderAccounts(d); });
      accTimer = setTimeout(pollAccounts, (d.checking || !d.accounts) ? 2000 : 20000);
    }, function () { accTimer = setTimeout(pollAccounts, 5000); });
  }
  function recheck() {
    api('api/recheck', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }).then(function (r) {
      toast(r.recheck === 'started' ? 'Checking every account again.' : ('Not rechecking: ' + r.recheck + '.'), 'info');
      setTimeout(function () { pollAccounts(); pollStatus(); }, 400);
    }, function () { toast('Could not reach the dashboard server.', 'err'); });
  }

  guard('header', function () {
    var at = location.host + BASE + '/';
    $('#pop-ver').textContent = $('#ab-ver').textContent = 'v' + BOOT.version;
    $('#pop-panel').textContent = $('#ab-panel').textContent = BOOT.panelVersion ? 'v' + BOOT.panelVersion : 'missing';
    $('#pop-at').textContent = $('#ab-at').textContent = at;
  });
  guard('events', function () {
    document.addEventListener('click', function (e) {
      var c = e.target.closest && e.target.closest('[data-copy]');
      if (c) { e.stopPropagation(); copy(c.getAttribute('data-copy'), 'Copied the command. Run it in a terminal, or paste it to your AI.'); return; }
      var p = e.target.closest && e.target.closest('.led-pill');
      if (p) {
        openPill = openPill === p.getAttribute('data-id') ? null : p.getAttribute('data-id');
        Array.prototype.forEach.call(document.querySelectorAll('.led-pill'), function (b) { b.setAttribute('aria-expanded', String(b.getAttribute('data-id') === openPill)); });
        renderDetail();
      }
    });
    var modal = $('#settings');
    function closeSettings() { modal.hidden = true; $('#gear').focus(); }
    $('#gear').addEventListener('click', function () { modal.hidden = false; $('#set-x').focus(); });
    $('#set-x').addEventListener('click', closeSettings);
    modal.addEventListener('click', function (e) { if (e.target === modal) closeSettings(); });
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !modal.hidden) closeSettings(); });
    $('#recheck').addEventListener('click', recheck);
    $('#set-recheck').addEventListener('click', recheck);
  });
  guard('panel', function () { mountPanel(0); });
  guard('poll', function () { pollStatus(); pollAccounts(); setInterval(pollStatus, 15000); });
  boot.complete = true;
})();
</script>
</body></html>
"""


CHAT_API = "https://chat.googleapis.com/v1"


def _chat(cfg, path, method="GET", body=None, params=None, allow_404=False):
    url = path if path.startswith("http") else f"{CHAT_API}/{path.lstrip('/')}"
    headers = {"Authorization": f"Bearer {_access_token(cfg)}"}
    data = None
    if body is not None:
        data = json.dumps(body)
        headers["Content-Type"] = "application/json"
    r = requests.request(method, url, headers=headers, params=params, data=data, timeout=60)
    if r.status_code in (400, 404) and allow_404:
        return {}                                    # caller prints a friendly "no DM/space" hint
    if r.status_code >= 400:
        sys.exit(f"Chat API error ({r.status_code}) {method} {url}:\n{r.text}")
    return r.json() if r.content else {}


def _find_dm(cfg, email):
    """Resolve the 1:1 DM space with a person by email → the Space dict (name, spaceUri)."""
    return _chat(cfg, "spaces:findDirectMessage", params={"name": f"users/{email}"}, allow_404=True)


def _space_name(v):
    """Normalize a space id to a 'spaces/XXX' resource name (caller handles emails)."""
    return v if v.startswith("spaces/") else f"spaces/{v}"


def _msg_text(text):
    """Message body source: '-' (stdin), '@file', or a literal string."""
    if text == "-":
        return sys.stdin.read()
    if text.startswith("@"):
        return open(text[1:], encoding="utf-8").read()
    return text


def _chat_upload(cfg, space, path):
    """Upload a local file as a Chat attachment → the attachmentDataRef to attach to a message.

    Two-step, per the Chat API: POST the bytes to the /upload endpoint (multipart: a small JSON
    metadata part naming the file, then the raw bytes), then reference the returned
    attachmentDataRef on messages.create. Covers images, video, PDFs, anything Chat accepts.
    Uses the SAME chat.messages scope as a text post (verified 2026-07-21), so no re-consent."""
    if not os.path.isfile(path):
        sys.exit(f"attachment not found: {path}")
    import mimetypes
    filename = os.path.basename(path)
    ctype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
    with open(path, "rb") as f:
        blob = f.read()

    boundary = "adomgoogle" + secrets.token_hex(12)
    meta = json.dumps({"filename": filename}).encode()
    body = b"".join([
        f"--{boundary}\r\n".encode(),
        b"Content-Type: application/json; charset=UTF-8\r\n\r\n", meta, b"\r\n",
        f"--{boundary}\r\n".encode(),
        f"Content-Type: {ctype}\r\n\r\n".encode(), blob, b"\r\n",
        f"--{boundary}--\r\n".encode(),
    ])
    # NOTE: the endpoint is attachments:upload. messages:upload returns a bare 503 from the
    # upload frontend (no JSON), which reads like an outage rather than a bad path.
    r = requests.post(
        f"https://chat.googleapis.com/upload/v1/{space}/attachments:upload",
        headers={"Authorization": f"Bearer {_access_token(cfg)}",
                 "Content-Type": f"multipart/related; boundary={boundary}"},
        params={"uploadType": "multipart"}, data=body, timeout=300)
    if r.status_code >= 400:
        hint = ""
        if r.status_code == 403 and "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in r.text:
            hint = "\nMissing scope — run: adom-google scopes --require chat.messages --auto-widen"
        sys.exit(f"Chat upload failed ({r.status_code}) for {filename}:\n{r.text[:400]}{hint}")
    ref = (r.json() or {}).get("attachmentDataRef")
    if not ref:
        sys.exit(f"Chat upload returned no attachmentDataRef for {filename}: {r.text[:300]}")
    sys.stderr.write(f"(uploaded {filename}, {len(blob)/1024:.0f} KB, {ctype})\n")
    return ref


def cmd_chat_spaces(a):
    cfg = _load()
    spaces, page = [], None
    while True:
        params = {"pageSize": 1000}
        if page:
            params["pageToken"] = page
        j = _chat(cfg, "spaces", params=params)
        spaces += j.get("spaces", [])
        page = j.get("nextPageToken")
        if not page:
            break
    if a.json:
        print(json.dumps(spaces, indent=2, ensure_ascii=False))
        return
    for s in spaces:
        print(f"{s.get('name')}  ·  {s.get('spaceType','?')}  ·  {s.get('displayName') or '(direct message)'}")
    sys.stderr.write(f"({len(spaces)} spaces — pass a spaces/XXX id OR an email to chat send/read)\n")


def cmd_chat_dm(a):
    cfg = _load()
    target, person = a.email.strip(), None
    if not target:
        _people_fail(a.json, "empty target", ["pass an email or a name, e.g. adom-google chat dm Kale"])
    if "@" not in target and not target.isdigit() and not target.startswith("users/"):
        # A NAME: resolve through the Workspace DOMAIN directory only (exactly one match, or ERROR).
        # An explicit email keeps its original behaviour below, unchanged.
        person = _resolve_name_to_email(cfg, target, a.json)
        target = person["email"]
        sys.stderr.write(f"(resolved \"{a.email}\" -> {person['name']} <{target}> via the domain directory)\n")
    if target.startswith("users/"):
        target = target[len("users/"):]
    sp = _find_dm(cfg, target)
    name = sp.get("name")
    if not name:
        if person:
            _people_fail(a.json, f"{person['name']} <{target}> is in the directory but you have no 1:1 DM "
                         "with them yet; findDirectMessage only finds an existing conversation.",
                         ["start the conversation in Google Chat once, then re-run this command"],
                         data={"person": person})
        sys.exit(f"no DM/space found for {a.email} — run 'adom-google chat spaces', or check the email")
    if a.json:
        if person:
            sp = dict(sp, resolvedPerson={"name": person["name"], "email": target})
        print(json.dumps(sp, indent=2, ensure_ascii=False))
        return
    print(name + (f"  ·  {sp.get('spaceUri')}" if sp.get("spaceUri") else "")
          + (f"  ·  {person['name']} <{target}>" if person else ""))


def cmd_chat_send(a):
    cfg = _load()
    if not a.text and not getattr(a, "attach", None):
        sys.exit("nothing to send — pass message text and/or --attach <path>")
    if "@" in a.to:
        sp = _find_dm(cfg, a.to)
        space = sp.get("name")
        if not space:
            sys.exit(f"no DM/space found for {a.to} — run 'adom-google chat spaces', or check the email")
        sys.stderr.write(f"(auto-resolved DM {space} for {a.to})\n")
        label = a.to
    else:
        space = _space_name(a.to)
        sp = _chat(cfg, space)                       # validate + fetch spaceUri / displayName
        label = sp.get("displayName") or space
    body = {"text": _msg_text(a.text)}
    # --attach is repeatable: upload each file first, then reference them on the message.
    attachments = [_chat_upload(cfg, space, p) for p in (getattr(a, "attach", None) or [])]
    if attachments:
        body["attachment"] = [{"attachmentDataRef": ref} for ref in attachments]
    params = {}
    if a.thread:
        body["thread"] = {"threadKey": a.thread}
        params["messageReplyOption"] = "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
    # Stamp agent-sent messages so the RECEIVING side can detect them exactly.
    # Google Chat renders an app-attribution badge ("Adom Google") in the UI for
    # anything posted through the API with user credentials, but exposes that
    # attribution NOWHERE in the REST API. A custom clientAssignedMessageId is
    # the only durable, machine-readable signal, and it is invisible in the UI.
    # Opt out with --no-agent-marker.
    if not getattr(a, "no_agent_marker", False):
        params["messageId"] = "client-agent-" + secrets.token_hex(10)
    msg = _chat(cfg, f"{space}/messages", method="POST", body=body, params=params or None)
    uri = sp.get("spaceUri", "")
    who = (msg.get("sender") or {}).get("displayName") or "you"
    if getattr(a, "json", False):
        # Machine-readable envelope: the message as Chat returned it, plus the resolved
        # space/label/uri. (An agent piping `--json` into json.load got the human line
        # and a JSONDecodeError, then could not tell whether the post landed — 2026-10-19.)
        out = dict(msg)
        out.update({"space": space, "label": label, "spaceUri": uri, "posted": True})
        print(json.dumps(out, indent=2, ensure_ascii=False))
        return
    print(msg.get("name", "") + (f"  ·  {uri}" if uri else ""))
    sys.stderr.write(f"→ posted to {label} as {who}" + (f" · {uri}" if uri else "") + "\n")


def cmd_chat_read(a):
    cfg = _load()
    if "@" in a.frm:
        sp = _find_dm(cfg, a.frm)
        space = sp.get("name")
        if not space:
            sys.exit(f"no DM/space found for {a.frm} — run 'adom-google chat spaces', or check the email")
    else:
        space = _space_name(a.frm)
    j = _chat(cfg, f"{space}/messages", params={"pageSize": a.limit, "orderBy": "createTime desc"})
    msgs = j.get("messages", [])
    if a.json:
        print(json.dumps(msgs, indent=2, ensure_ascii=False))
        return
    for m in reversed(msgs):                         # show oldest → newest of the recent batch
        who = (m.get("sender") or {}).get("displayName") or (m.get("sender") or {}).get("name", "?")
        print(f"{who}: {m.get('text','')}")


# ---------------------------------------------------------------- generic API passthrough
# Hosts whose scopes adom-google deliberately does NOT request, at any tier. Hitting these is a
# policy decision, not a missing feature, so say so instead of suggesting a re-auth that won't help.
_EXCLUDED_HOSTS = {
    "admin.googleapis.com": "Admin SDK (Directory: users, groups/distribution lists, org units)",
    "cloudidentity.googleapis.com": "Cloud Identity (groups/memberships)",
}
# Best-effort host → the scope tail most likely missing, for the actionable hint.
_HOST_SCOPE = {
    "www.googleapis.com/youtube": "youtube.upload youtube",
    "gmail.googleapis.com": "gmail.modify", "chat.googleapis.com": "chat.messages",
    "sheets.googleapis.com": "spreadsheets", "docs.googleapis.com": "documents",
    "slides.googleapis.com": "presentations", "www.googleapis.com": "drive",
    "drive.googleapis.com": "drive", "calendar-json.googleapis.com": "calendar",
    "tasks.googleapis.com": "tasks", "people.googleapis.com": "contacts",
}


def _scope_wall_hint(url, resp):
    """On a 403 scope failure, tell the caller what to DO next.

    Google's 403 body names the reason but never the fix, so an agent hitting a scope wall through
    the generic `api` passthrough just saw raw JSON and stalled (wiki-notify-gchat tried to create
    a contact@adom.inc distribution list, 2026-07-21). Print the exact next command, or say plainly
    that the scope is excluded by policy so nobody burns a re-auth chasing it."""
    if resp.status_code != 403:
        return
    text = resp.text or ""
    host = urllib.parse.urlparse(url).netloc
    e = sys.stderr

    # THREE different 403s that look identical in raw JSON but need opposite actions:
    #   SERVICE_DISABLED               -> the API is off in the GCP project (re-auth won't help)
    #   ACCESS_TOKEN_SCOPE_INSUFFICIENT-> missing scope (re-auth WILL help)
    #   not-an-admin                   -> the human lacks Workspace admin rights (nothing helps)
    # Keep them apart: one the user can fix in a console, one in a consent screen, one not at all.
    if "SERVICE_DISABLED" in text or "accessNotConfigured" in text:
        proj = ""
        try:
            for d in resp.json().get("error", {}).get("details", []):
                c = (d.get("metadata") or {}).get("consumer") or ""
                if c.startswith("projects/"):
                    proj = c.split("/", 1)[1]
        except Exception:
            pass
        e.write("\n── API not enabled (NOT a scope problem) ───────────────────\n")
        e.write(f"{host} is switched OFF in the OAuth client's Google Cloud project"
                + (f" ({proj})" if proj else "") + ".\n")
        e.write("Your token is fine — re-running `auth` will NOT fix this. Someone with access to\n"
                "that project must enable the API once:\n")
        if proj:
            e.write(f"  https://console.developers.google.com/apis/api/{host}/overview?project={proj}\n")
        # WHOSE project is it? The fix lands on a different person depending on the answer, and
        # guessing wrong sends someone to a console they cannot open (issue #11).
        pr = _provider()
        src = ""
        try:
            src = json.load(open(PROVIDER_PATH)).get("_source", "") if os.path.exists(PROVIDER_PATH) else ""
        except Exception:
            pass
        if pr.get("app") == ADOM_PERSONAL_APP:
            # The Connector (personal Gmail + other orgs) is Adom's project too. Before this branch
            # it fell through to "your own OAuth client", sending an outside user to a console
            # they can never open (issue #12: YouTube Data API v3 off on the Connector project).
            e.write("This is ADOM'S GOOGLE CONNECTOR client (the one personal Gmail and other-org\n"
                    "accounts sign in through). Only Adom can enable the API, once, for every Connector\n"
                    "user; you cannot fix it from your side. Report it at\n"
                    "  https://wiki.adom.inc/adom/adom-google/issues  (or support@adom.inc).\n"
                    "Adom employees: use your work account (no --account personal) instead.\n")
        elif pr.get("app") == DEFAULT_APP and not src.startswith("org-settings:"):
            e.write("This is ADOM'S SHARED OAuth client, so an Adom admin enables it ONCE and every\n"
                    "adom-google user is fixed. Ask in #kel rather than making your own client.\n")
        elif src.startswith("org-settings:"):
            org = src.split(":", 1)[1]
            e.write(f"This is {org}'s OWN OAuth client (from {org}/org-settings), so {org}'s Google Cloud\n"
                    f"admin enables it once and every {org} member is fixed.\n")
        else:
            e.write("This is your own OAuth client, so whoever owns that Cloud project enables it.\n")
        e.write("Then wait a minute for it to propagate and retry.\n")
        e.write("────────────────────────────────────────────────────────────\n")
        return
    if "Not Authorized to access this resource" in text or "authError" in text:
        e.write("\n── not a Workspace admin ───────────────────────────────────\n")
        e.write("The API is reachable and the token has the scope, but this Google account is not a\n"
                "Workspace ADMIN, so it cannot manage the domain. Nothing you can change here — a\n"
                "Workspace super-admin must either grant admin rights or run this themselves.\n")
        e.write("────────────────────────────────────────────────────────────\n")
        return
    if "ACCESS_TOKEN_SCOPE_INSUFFICIENT" not in text and "insufficientPermissions" not in text:
        return
    e.write("\n── scope wall ──────────────────────────────────────────────\n")
    if host in _EXCLUDED_HOSTS:
        e.write(f"{host} needs {_EXCLUDED_HOSTS[host]} scopes. These are NOT in safe/full/personal\n"
                "by design (org-wide admin surface), so a bare `auth` will never unlock them.\n"
                "Opt in explicitly — one consent, and only a Workspace ADMIN can grant it:\n"
                "  adom-google auth --admin\n"
                "That covers Groups/distribution lists end to end, including apps.groups.settings,\n"
                "without which a new group silently rejects external mail.\n")
    else:
        guess = _HOST_SCOPE.get(host)
        if host == "people.googleapis.com" and "Directory" in urllib.parse.urlparse(url).path:
            guess = "directory.readonly"              # searchDirectoryPeople / listDirectoryPeople
        e.write("The token is missing a scope for this API. Check what you actually hold:\n"
                "  adom-google scopes\n")
        if guess:
            e.write(f"and widen it (one Allow click, existing access is preserved):\n"
                    f"  adom-google scopes --require {guess} --auto-widen\n")
        else:
            e.write("and widen it with the scope this method needs:\n"
                    "  adom-google scopes --require <scope> --auto-widen\n")
        e.write("NOTE: a granted scope is not enough on its own — the API must also be ENABLED in\n"
                "the OAuth client's GCP project.\n")
    e.write("────────────────────────────────────────────────────────────\n")


def cmd_api(a):
    """Sign ANY Google REST/Discovery call with the stored token — the 'whole board'.
    Reach of this command == the scopes the stored token holds (see `status`); add scopes
    in SCOPES + re-`auth` to widen it, and enable the API in the GCP project.

    Examples:
      adom-google api https://sheets.googleapis.com/v4/spreadsheets/<id>/values/A1:D10
      adom-google api -X POST https://sheets.googleapis.com/v4/spreadsheets -d '{"properties":{"title":"BOM"}}'
      adom-google api -X POST https://docs.googleapis.com/v1/documents/<id>:batchUpdate -d @reqs.json
    """
    cfg = _load()
    url = a.url if a.url.startswith("http") else "https://" + a.url.lstrip("/")
    headers = {"Authorization": f"Bearer {_token_for(cfg, url)}"}
    body = None
    if getattr(a, "upload_file", None):
        body = open(a.upload_file, "rb").read()  # raw bytes: Drive media, YouTube resumable PUT, etc.
        headers["Content-Type"] = a.content_type or "application/octet-stream"
    elif a.data is not None:
        body = open(a.data[1:], "rb").read() if a.data.startswith("@") else a.data
        headers["Content-Type"] = a.content_type or "application/json"
    # A LIST of pairs, not a dict: repeated keys are how several Google APIs take lists
    # (metadataHeaders, fields, orderBy...). dict() kept only the LAST value, so
    #   -q metadataHeaders=From -q metadataHeaders=To
    # silently requested only To — a truncated REQUEST returning a valid 200, which reads as
    # complete-but-empty data. That cost a sibling thread an entire email-harvesting pass across
    # 19 people before they worked out the tool was wrong, not the mailbox (2026-07-21).
    params = [tuple(q.split("=", 1)) for q in (a.query or [])]
    r = requests.request(a.method.upper(), url, headers=headers,
                         params=params or None, data=body, timeout=120)
    sys.stderr.write(f"HTTP {r.status_code} {a.method.upper()} {url}\n")
    ct = r.headers.get("content-type", "")
    if a.raw or "application/json" not in ct:
        sys.stdout.buffer.write(r.content)
    else:
        print(json.dumps(r.json(), indent=2, ensure_ascii=False))
    _scope_wall_hint(url, r)
    sys.exit(0 if r.status_code < 400 else 1)


# ---------------------------------------------------------------- auth: gateway flow
def _ws_wait_with_reconnect(ws_url, send_msgs, want_types, timeout=3600, state=None,
                            gateway_url=None):
    """Wait for the gateway's callback, surviving dropped sockets.

    The ingress kills idle WebSockets (~120s), laptops sleep, wifi flaps. A single drop used to
    abort the whole sign-in ("gateway closed the connection") and, worse, the gateway deleted the
    pending session on disconnect so clicking Allow later showed "Session Expired". The gateway
    now keeps sessions alive and PARKS the result; this loop reconnects, re-registers the same
    state (which replays a parked result), and polls GET /result as a last resort. The user gets
    the full window to read Google's consent screen and click Allow."""
    deadline = time.time() + timeout
    attempt = 0
    while time.time() < deadline:
        remaining = max(30, int(deadline - time.time()))
        try:
            return _minimal_ws_roundtrip(ws_url, send_msgs, want_types, timeout=remaining)
        except Exception as e:
            # Before retrying, ask the gateway whether the result already landed while we were
            # disconnected — the common case when the drop happened mid-consent.
            if state and gateway_url:
                try:
                    r = requests.get(gateway_url.rstrip("/") + "/result",
                                     params={"state": state}, timeout=20)
                    j = r.json()
                    if j.get("ok") and not j.get("pending") and j.get("result"):
                        res = j["result"]
                        if res.get("type") == "error":
                            raise RuntimeError("gateway error: " + str(res.get("error") or res.get("detail")))
                        if res.get("type") in want_types:
                            return res
                except requests.RequestException:
                    pass
            if time.time() >= deadline:
                break
            attempt += 1
            time.sleep(min(5, attempt))          # brief backoff, then reconnect + re-register
    raise RuntimeError("timed out waiting for the gateway callback")


def _minimal_ws_roundtrip(ws_url, send_msgs, want_types, timeout=3600):
    """Tiny RFC6455 client (stdlib only): connect, send JSON text frames, return the first
    received JSON message whose 'type' == want_type. Used for the OAuth Gateway handshake so
    adom-google stays a single dependency-light file (no `ws`/`websockets` package).

    NOTE: this path is exercised only when the gateway is live. The `--manual` flow is the
    fallback that works without the gateway."""
    u = urllib.parse.urlparse(ws_url)
    host = u.hostname
    port = u.port or (443 if u.scheme == "wss" else 80)
    path = u.path or "/"
    key = base64.b64encode(secrets.token_bytes(16)).decode()

    raw = socket.create_connection((host, port), timeout=30)
    if u.scheme == "wss":
        raw = ssl.create_default_context().wrap_socket(raw, server_hostname=host)
    req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\n"
           f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
           f"Sec-WebSocket-Version: 13\r\n\r\n")
    raw.sendall(req.encode())

    # read handshake response headers
    buf = b""
    while b"\r\n\r\n" not in buf:
        chunk = raw.recv(4096)
        if not chunk:
            raise RuntimeError("gateway closed during handshake")
        buf += chunk
    if b" 101 " not in buf.split(b"\r\n", 1)[0]:
        raise RuntimeError("gateway did not accept websocket upgrade: " + buf[:80].decode("latin1"))
    leftover = buf.split(b"\r\n\r\n", 1)[1]

    def _send_text(s):
        payload = s.encode()
        mask = secrets.token_bytes(4)
        masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
        header = b"\x81"  # FIN + text
        n = len(payload)
        if n < 126:
            header += struct.pack("!B", 0x80 | n)
        elif n < 65536:
            header += struct.pack("!BH", 0x80 | 126, n)
        else:
            header += struct.pack("!BQ", 0x80 | 127, n)
        raw.sendall(header + mask + masked)

    inbuf = bytearray(leftover)
    deadline = time.time() + timeout

    def _fill(n):
        """Block until inbuf holds n bytes. recv() returning b"" means the peer closed the
        socket (EOF); it will keep returning b"" instantly forever, so treat it as a drop and
        raise. The old loop appended the empty bytes and spun at ~100% CPU for days (Nov 2026).
        Each recv also gets only the time left, so the overall deadline is real."""
        nonlocal inbuf
        while len(inbuf) < n:
            left = deadline - time.time()
            if left <= 0:
                raise RuntimeError("timed out waiting for the gateway callback")
            raw.settimeout(left)
            chunk = raw.recv(4096)
            if not chunk:
                raise RuntimeError("gateway closed the connection")
            inbuf += chunk

    def _recv_frame():
        nonlocal inbuf
        while True:
            _fill(2)
            b0, b1 = inbuf[0], inbuf[1]
            opcode = b0 & 0x0F
            ln = b1 & 0x7F
            idx = 2
            if ln == 126:
                _fill(4)
                ln = struct.unpack("!H", inbuf[2:4])[0]; idx = 4
            elif ln == 127:
                _fill(10)
                ln = struct.unpack("!Q", inbuf[2:10])[0]; idx = 10
            _fill(idx + ln)
            data = bytes(inbuf[idx:idx + ln])
            del inbuf[:idx + ln]
            if opcode == 0x8:  # close
                raise RuntimeError("gateway closed the connection")
            if opcode == 0x9:  # ping → pong
                raw.sendall(b"\x8a\x80" + secrets.token_bytes(4))
                continue
            if opcode in (0x1, 0x2):
                return data

    for m in send_msgs:
        _send_text(json.dumps(m))

    try:
        while time.time() < deadline:
            data = _recv_frame()
            try:
                msg = json.loads(data.decode())
            except Exception:
                continue
            if msg.get("type") == "error":
                raise RuntimeError("gateway error: " + str(msg.get("error") or msg.get("detail")))
            if msg.get("type") in want_types:
                return msg
    finally:
        try:
            raw.close()
        except Exception:
            pass
    raise RuntimeError("timed out waiting for the gateway callback")


def _exchange_code(cfg, code, redirect_uri, scopes, mode, target="main"):
    cid, csec = _client_creds(cfg)
    root = cfg
    if target != "main":
        cfg = cfg.setdefault("grants", {}).setdefault(target, {})
    else:
        _keep_youtube_main(cfg, scopes or [])
    r = requests.post(TOKEN_URL, data={
        "client_id": cid, "client_secret": csec, "code": code,
        "redirect_uri": redirect_uri, "grant_type": "authorization_code",
    }, timeout=30)
    if r.status_code != 200:
        sys.exit(f"Code exchange failed ({r.status_code}): {r.text}")
    rt = r.json().get("refresh_token")
    if not rt:
        sys.exit("No refresh_token returned (re-run auth; needs access_type=offline & prompt=consent).")
    cfg["refresh_token"] = rt
    cfg["scopes"] = scopes
    cfg["mode"] = mode
    cfg["broker"] = False
    cfg.pop("_migrated_from", None)
    cfg.pop("_pending_mode", None)
    _save(root)


def _store_broker_tokens(cfg, tokens, scopes, mode, target="main"):
    """Gateway broker returned the tokens directly — no client secret on this container.
    target="youtube" stores them as the account's YouTube grant and leaves the main grant alone."""
    if target != "main":
        root, cfg = cfg, cfg.setdefault("grants", {}).setdefault(target, {})
    else:
        root = cfg
        _keep_youtube_main(cfg, scopes or [])
    cfg["refresh_token"] = tokens["refresh_token"]
    if tokens.get("access_token"):
        cfg["access_token"] = tokens["access_token"]
        cfg["access_expires"] = time.time() + int(tokens.get("expires_in", 3600)) - 60
    cfg["scopes"] = scopes
    cfg["mode"] = mode
    cfg["broker"] = True
    cfg["app"] = _provider()["app"]
    cfg.pop("client_secret", None)   # broker mode: never keep a secret locally
    cfg.pop("_migrated_from", None)
    cfg.pop("_pending_mode", None)
    if target != "main":
        cfg["granted_at"] = int(time.time())
    _save(root)


def _print_open_url(auth_link, step="1"):
    """Present the consent URL so an AI can act on it without mangling it.

    THREE LANES, cheapest-for-the-human first (issue #9, #8):
      A. pup, hands-free: pup's durable `adom-you` profile + OS-keychain vault can sign into
         Google and click Allow with no human in the loop, once a Google login is saved there.
         On a machine where it is not, the FIRST pass is one interactive sign-in inside the pup
         window (toast the user with focus on it); every later `auth` is silent.
      B. a clickable hyperlink: Hydrogen's browser picker lets the USER choose browser/profile.
         One click, nothing for the AI to get wrong, no extension required.
      C. the Adom extension window (nbrowser_open_window), ONLY when `nbrowser_profiles` says
         extensionInstalled:true for that profile; it often is not, and the call then fails with
         "native browser extension not connected" (nbrowser_wake_profile does not fix it).

    The '&' warning matters in every lane: dropped UNQUOTED into a shell/open command the shell
    cuts the URL at the first '&', Google receives only client_id and errors
    'invalid_request: missing response_type' (issue #3)."""
    safe = json.dumps({"sessionId": "gauth", "url": auth_link})
    print(f"{step}) Get this consent URL in front of Google and get Allow clicked.\n")
    print("   " + auth_link + "\n")
    print("   ⚠ The URL contains '&'. Keep it as ONE whole value. Do NOT drop it UNQUOTED into")
    print("     a shell/open command: the shell cuts it at the first '&', Google then gets only")
    print("     client_id and shows \"Error 400: invalid_request, missing response_type\".\n")
    print("   LANE A, HANDS-FREE (try first): drive the consent page in pup. pup's durable")
    print("   `adom-you` profile keeps the Google session, so once it is signed in the user")
    print("   never clicks again. Check the vault for a Google login first:")
    print("     adom-bridge credential_list        # any accounts.google.com / google.com entry?")
    print("     adom-bridge pup_open_window '" + safe + "'")
    print("     # sign-in page appeared and the vault has a Google login? submit it (reason-gated):")
    print("     adom-bridge pup_login '{\"sessionId\":\"gauth\",\"submit\":true,\"submitReason\":\"Google consent for adom-google\"}'")
    print("     # then pick the account + click Allow via pup_eval on the classic consent page:")
    print("     adom-bridge pup_eval '{\"sessionId\":\"gauth\",\"expression\":\"[...document.querySelectorAll(\\\"button\\\")].find(b=>/^(Allow|Continue)$/.test(b.innerText.trim()))?.click()\"}'")
    print("     Caveats: a FedCM \"Sign in with Google\" chooser rejects in-page clicks (the classic")
    print("     accounts.google.com consent page does not). NO Google login in the vault yet? Then")
    print("     the first pass is one interactive sign-in INSIDE that pup window: open it as above,")
    print("     toast the user with focus on it (below), they sign in once, and every later `auth`")
    print("     on this machine is silent. Do not read \"hands-free\" as \"always\".\n")
    print("   LANE B, ONE HUMAN CLICK (always works): surface the URL to the user as a CLICKABLE")
    print("   HYPERLINK in your reply. Hydrogen's browser picker lets them choose browser/profile.")
    print("   Do NOT put it in a code fence: a fence renders as plain text, the user has to")
    print("   copy-paste it by hand, and the picker never fires.\n")
    print("   LANE C, ONLY IF the Adom extension is installed in the target profile (check with")
    print("   `adom-bridge nbrowser_profiles`, require extensionInstalled:true):")
    print("     adom-bridge nbrowser_open_window '" + safe + "'")
    print("     # extension NOT installed there? Do not fall back to nbrowser_open_os_window: it is")
    print("     # extension-free and returns ok without confirming what rendered. Use lane B.\n")
    # Foreground guidance. abe/nbrowser rightly defaults to BACKGROUND windows and the
    # foreground-etiquette skill says never steal focus. OAuth consent is the one flow whose
    # entire purpose is a human physically clicking Allow, so this is a sanctioned exception:
    # TELL THEM, with a toast that lands the click ON the consent window, AFTER it exists.
    print("   TOASTING THE USER (lanes A-first-pass and C; the foreground exception):")
    print("     Consent is the one flow where taking the foreground is justified. Fire the toast")
    print("     AFTER the window exists (a toast that points at nothing is worse than none) and")
    print("     give it `focus` so the click raises the CONSENT window, not Adom Bridge:\n")
    print("       adom-bridge notify_user '{\"id\":\"gauth\",\"title\":\"Google sign-in needed\",")
    print("         \"body\":\"Click Allow in the window I just opened. You have ~60 min.\",")
    print("         \"scenario\":\"reminder\",\"buttons\":[{\"label\":\"Done\"},{\"label\":\"Cancel\"}],")
    print("         \"focus\":{\"titleContains\":\"Sign in - Google\"}}'")
    print("       # READ THE REPLY: require clickBehavior:\"focus-window\" and focus.resolved:true;")
    print("       # if it carries _couldHaveDoneBetter, do what it says (e.g. pass the hwnd from")
    print("       # the window verb's reply instead of a title). Then learn what they did:")
    print("       adom-bridge notify_response '{\"id\":\"gauth\"}'   # or add \"wait\":true above to block\n")
    print("     GENTLER, prefer it when the user may be mid-task: leave the window in the")
    print("     background and flash the taskbar (browser_alert_window) so they come to it when")
    print("     ready. The session survives a dropped socket, so there is no rush either way.\n")
    print("   IF GOOGLE SHOWS \"Sorry, something went wrong there. Try again.\": that is Google's")
    print("   generic first-load hiccup, not a scope or client problem. Stop this listener and")
    print("   re-run `adom-google auth` for a fresh URL; an earlier approval is recovered and")
    print("   nobody clicks Allow twice. This listener prints a line the moment the callback")
    print("   lands, so \"user clicked and Google failed\" (line printed, then an error) is")
    print("   distinguishable from \"user never clicked\" (still waiting).\n")


def _auth_json_line(real_out, cfg, scopes, mode, via):
    """`auth --json`: the ONE machine-readable line an AI waits for (issue #9 §3)."""
    real_out.write(json.dumps({"ok": True, "authorized": True, "account": ACCOUNT, "mode": mode,
                               "via": via, "scopes": scopes, "config": CFG}) + "\n")
    real_out.flush()


def cmd_auth(a):
    # --json: every human-facing line (URL block, waiting notes) goes to STDERR and the ONLY
    # thing on stdout is one JSON line on success, so a waiter never has to poll `status`.
    as_json = getattr(a, "json", False)
    real_out = sys.stdout
    if as_json:
        sys.stdout = sys.stderr
    try:
        return _cmd_auth_impl(a, as_json, real_out)
    finally:
        sys.stdout = real_out


def _cmd_auth_impl(a, as_json, real_out):
    cfg = _maybe_load_raw() or {}
    # FULL is the default (no first-run mode quiz — issue #2). `--safe` is an advanced opt-in
    # for users who explicitly want the narrower create-only scopes. `--full` is a no-op kept
    # for back-compat. A PERSONAL @gmail (the global adom-personal client) uses the non-restricted
    # personal scope set automatically.
    mode = "safe" if getattr(a, "safe", False) else "full"
    if _provider().get("app") == ADOM_PERSONAL_APP:
        # Adom Google Connector (External, Production/unverified): default to the non-restricted
        # (lite) set — Calendar/Contacts/Tasks/drive.file/gmail send+compose — which works for
        # external users TODAY while Google verification + CASA are pending. `--full` requests the
        # complete set: it succeeds for whitelisted testers now, and becomes usable for everyone
        # once CASA clears (at which point this default flips to full).
        mode = "full" if getattr(a, "full", False) else "personal"
    # `--youtube` ADDS YouTube to this account (issue #12). On an account that already holds
    # Workspace scopes it widens in place, or, when the account holds drive.file (Google refuses
    # YouTube + drive.file in one consent), mints a second YouTube-only grant on the same account.
    # On a fresh account (or one that only holds YouTube) it is a YouTube-only sign-in.
    youtube = getattr(a, "youtube", False)
    target = getattr(a, "grant_target", None) or "main"
    preserve = list(getattr(a, "preserve_scopes", None) or [])
    if youtube:
        if getattr(a, "admin", False) or getattr(a, "safe", False):
            sys.exit("ERROR: --youtube adds YouTube to the account as it is; it cannot be combined\n"
                     "with --admin or --safe. Hint: run those separately, then add YouTube:\n"
                     "  adom-google auth --youtube")
        recorded = cfg.get("scopes") or []
        # What Google says the token holds wins over the recorded request: an account recorded as
        # YouTube-only that really holds more must not be overwritten by a YouTube-only sign-in.
        held = (_tokeninfo_scopes(cfg) or list(recorded)) if cfg.get("refresh_token") else []
        rebind = getattr(a, "rebind", False)
        if cfg.get("refresh_token") and [x for x in held if not _is_yt_scope(x)]:
            g = _yt_grant(cfg)
            g_live = (_tokeninfo_scopes(g, root=cfg) or []) if g else []   # live check, never the record
            yt_have = set(held) | set(g_live)
            if set(SCOPES_YOUTUBE) <= yt_have and not rebind:
                print(f"OK: account '{ACCOUNT}' already has YouTube "
                      + ("(its YouTube grant)." if g_live else "on its main grant.")
                      + f"\nHint: check the channel: adom-google{_acct_flag()} youtube channels"
                      + f"\nHint: wrong channel? adom-google{_acct_flag()} auth --youtube --rebind")
                if as_json:
                    _auth_json_line(real_out, cfg, sorted(yt_have), cfg.get("mode") or mode, "already-authorized")
                return
            if g and not g_live:
                sys.stderr.write("Note: this account's YouTube grant no longer works; minting a new one.\n")
            # --rebind always makes a separate YouTube grant: a Brand Account channel picked on the
            # MAIN grant would bind Gmail/Drive to the brand account too.
            if rebind or g or _yt_conflict(held + SCOPES_YOUTUBE):
                target = "youtube"
            else:
                preserve = held
                a.add_scopes = list(getattr(a, "add_scopes", None) or []) + SCOPES_YOUTUBE
                mode = cfg.get("mode") or mode
        else:
            mode = "youtube"
    if target == "youtube":
        if not cfg.get("refresh_token"):
            sys.exit("ERROR: this account has no sign-in yet, so there is nothing to add YouTube to.\n"
                     f"Hint: sign in first: adom-google{_acct_flag()} auth   then: adom-google{_acct_flag()} auth --youtube")
        asked = [_normalize_scope(x) for x in (getattr(a, "add_scopes", None) or [])]
        non_yt = [x for x in asked if not _is_yt_scope(x)]
        if non_yt:
            tails = " ".join(x.split("/")[-1] for x in non_yt)
            sys.exit(f"ERROR: the YouTube grant only carries YouTube scopes; add {tails} to the main grant first.\n"
                     f"Hint: adom-google{_acct_flag()} scopes --require {tails} --auto-widen   then: adom-google{_acct_flag()} auth --youtube")
        mode = "youtube"
        # Keep any extra YouTube-family scopes the old grant held (e.g. yt-analytics.readonly).
        old = (_yt_grant(cfg) or {}).get("scopes") or []
        preserve = sorted(set(SCOPES_YOUTUBE) | {x for x in asked if _is_yt_scope(x)} | {x for x in old if _is_yt_scope(x)})
        a.add_scopes = []
    # `preserve_scopes` (set by `scopes --auto-widen`) is the AUTHORITATIVE base: the scopes the
    # token actually holds. Otherwise fall back to the tier default.
    scopes = preserve or _scopes_for(mode)
    # `--admin` folds in the Directory/Groups bundle so ONE consent covers admin work too.
    if getattr(a, "admin", False):
        scopes = scopes + SCOPES_ADMIN
    # `--add-scope` (repeatable) widens the computed set — also how `scopes --auto-widen` re-auths.
    extra = [_normalize_scope(s) for s in (getattr(a, "add_scopes", None) or [])]
    scopes = list(dict.fromkeys(scopes + extra))
    # A union Google is guaranteed to refuse (YouTube + drive.file in ONE consent). When the
    # account already holds everything else in the request, the YouTube part becomes the
    # account's second grant instead; otherwise ask for the two pieces separately.
    clash = _yt_conflict(scopes) if target == "main" else []
    if clash and _main_is_youtube_only(cfg) and not _yt_grant(cfg) and [x for x in scopes if not _is_yt_scope(x)]:
        # The main grant is YouTube-only and this request brings Workspace scopes with drive.file:
        # the Workspace scopes become the main grant and the current YouTube token is kept as the
        # account's YouTube grant when the new tokens are stored (_keep_youtube_main).
        scopes = [x for x in scopes if not _is_yt_scope(x)]
        if mode == "youtube":
            mode = "personal" if _provider().get("app") == ADOM_PERSONAL_APP else "full"
        clash = []
    if clash:
        held_now = (set(preserve) or set(_tokeninfo_scopes(cfg) or [])) if cfg.get("refresh_token") else set()
        others = [x for x in scopes if not _is_yt_scope(x)]
        if cfg.get("refresh_token") and set(others) <= held_now:
            target, mode = "youtube", "youtube"
            scopes = sorted({x for x in scopes if _is_yt_scope(x)} | set(SCOPES_YOUTUBE))
        else:
            tails = ", ".join(x.split("/")[-1] for x in clash)
            sys.exit(f"ERROR: Google refuses YouTube and {tails} in one consent, and this request also adds\n"
                     "non-YouTube scopes the account does not hold yet. Nothing was requested.\n"
                     f"Hint: add the other scopes first:  adom-google{_acct_flag()} scopes --require <scope> --auto-widen\n"
                     f"Hint: then add YouTube:          adom-google{_acct_flag()} auth --youtube")

    if target == "main" and mode == "youtube" and [x for x in scopes if not _is_yt_scope(x)]:
        mode = "personal" if _provider().get("app") == ADOM_PERSONAL_APP else "full"
    keeps_yt = target == "main" and _main_is_youtube_only(cfg) and not _yt_grant(cfg) \
        and not [x for x in scopes if _is_yt_scope(x)]
    if keeps_yt:
        print(f"Note: account '{ACCOUNT}' holds a YouTube-only sign-in; it is kept as this account's YouTube\n"
              "grant when this sign-in completes, so YouTube keeps working.\n")
    if a.manual and target != "main":
        sys.exit("ERROR: the YouTube grant uses the gateway flow; --manual is not supported for it.\n"
                 f"Hint: adom-google{_acct_flag()} auth --youtube")
    # SAFETY NET for every path, not just --auto-widen: a Google consent REPLACES the grant, so
    # any currently-held scope missing from this request is silently revoked on Allow. Warn loudly
    # and offer the exact command that keeps everything. Best-effort: never block auth on it.
    # _tokeninfo_scopes() never exits: a dead or revoked refresh token is None here (it holds
    # nothing, so there is nothing to warn about). Calling _access_token() directly sys.exit()ed
    # on a failed refresh, so a dead token used to stop `auth`, the one command that fixes it.
    if not preserve and cfg.get("refresh_token") and target == "main":
        held = set(_tokeninfo_scopes(cfg) or [])
        dropping = sorted(held - set(scopes))
        if keeps_yt:
            dropping = [x for x in dropping if not _is_yt_scope(x)]
        if dropping:
            tails = ", ".join(s.split("/")[-1] for s in dropping)
            sys.stderr.write(
                "\n⚠ THIS CONSENT WOULD REVOKE SCOPES YOU CURRENTLY HOLD:\n"
                f"    {tails}\n"
                "  Approving replaces your grant with only what is requested here.\n"
                "  To ADD a capability while keeping everything, cancel and run:\n"
                f"    adom-google scopes --require <scope> --auto-widen\n"
                "  (or re-run this command with the flag that includes them, e.g. --admin)\n\n")
    if a.manual:
        return _auth_manual(cfg, scopes, mode)
    # Gateway flow — one static redirect, code routed back over WebSocket. Needs a provider.
    try:
        tag = json.load(open(PROVIDER_PATH)).get("_source", "") if os.path.exists(PROVIDER_PATH) else ""
    except Exception:
        tag = ""
    if tag.startswith("org-settings:") and not os.environ.get("ADOM_GOOGLE_NO_DISCOVER"):
        _o, _f = _discover_org_providers(only_org=tag.split(":", 1)[1])
        if _f:
            global _PROVIDER
            _write_org_provider(*_f[0]); _PROVIDER = None
    pr = _provider()
    if not pr["gateway_url"]:
        sys.exit(NO_PROVIDER_HINT)
    cid, _ = _client_creds(cfg)
    # Before minting a new sign-in, see whether an EARLIER one already completed while no CLI was
    # listening. If so the user has already clicked Allow and must not be asked to do it twice.
    if _pending_claim(cfg, scopes, mode, pr["gateway_url"], target=target):
        if as_json:
            _auth_json_line(real_out, _maybe_load_raw() or cfg, scopes, mode, "recovered-approval")
        return
    state = secrets.token_urlsafe(24)
    _pending_save(state, scopes, mode, pr["gateway_url"], target=target)
    params = {
        "client_id": cid, "redirect_uri": pr["gateway_redirect"], "response_type": "code",
        "scope": " ".join(scopes), "access_type": "offline", "prompt": "consent",
        "state": state,
    }
    # broker=False → RELAY mode: the gateway just relays the code back; THIS container exchanges
    # it locally with the org's own secret. (None/True → broker mode: gateway exchanges.)
    want_exchange = pr.get("broker") is not False
    auth_link = AUTH_URL + "?" + urllib.parse.urlencode(params)
    if getattr(a, "url_file", None):
        # Clean machine-readable copy of the consent URL (one bare line). Tools that open the
        # browser for the user should read THIS instead of scraping stdout — quote/JSON wrappers
        # in the human output have corrupted scraped URLs before (trailing "}' broke the state).
        with open(a.url_file, "w") as f:
            f.write(auth_link + "\n")
    print(f"OAuth Gateway flow — {mode.upper()} access"
          + {"full": "  (full Workspace: Gmail/Contacts/Drive/Sheets/Docs/Slides/Calendar/Tasks/Chat + delete)",
             "youtube": "  (YouTube: youtube + youtube.upload)",
             "personal": "  (Connector lite: Calendar/Contacts/Tasks/app-made Drive files/Gmail send)",
             }.get(mode, "  (safe: only files this app makes; no 'delete all')") + ".\n")
    if target == "youtube":
        print(f"   Adding YouTube to account '{ACCOUNT}' as a SECOND grant: Google will not put YouTube and\n"
              "   drive.file in one consent. Everything this account already holds stays as it is; YouTube\n"
              "   calls use the new grant automatically.\n")
    _print_open_url(auth_link)
    if target == "main" and [x for x in scopes if _is_yt_scope(x)] and [x for x in scopes if not _is_yt_scope(x)]:
        print("   IMPORTANT: this consent adds YouTube to the SAME grant as your Gmail/Drive/Chat. If Google")
        print("   asks \"Choose an account or brand account\", pick YOUR OWN account. A Brand Account here")
        print("   would bind the whole grant to it. To post to a Brand Account channel, cancel and run:")
        print(f"     adom-google{_acct_flag()} auth --youtube --rebind   (a separate YouTube grant)\n")
    elif mode == "youtube" or set(scopes) & set(SCOPES_YOUTUBE):
        # Google shows a channel chooser when the account owns Brand Account channels. Picking the
        # account row instead of the channel binds the token to the wrong (often empty) channel,
        # and every upload then lands somewhere nobody looks (issue #12).
        print("   YOUTUBE CHANNEL CHOOSER: after the account picker Google may ask \"Choose an account")
        print("   or brand account\". Pick the CHANNEL you will upload to (a Brand Account channel is")
        print("   listed by its channel name), not just your Google login. The token is bound to")
        print("   that channel. Check afterwards:  adom-google" + ("" if ACCOUNT == "default" else f" --account {ACCOUNT}")
              + " youtube channels\n")
    if pr.get("app") == ADOM_PERSONAL_APP:
        print("   Google will show \"Google hasn't verified this app\" for the Connector while its")
        print("   verification is pending: Advanced, then Go to adom.cloud (unsafe), then continue.\n")
    # The gateway keeps the sign-in session alive for the full hour and parks the result if our
    # socket drops; _ws_wait_with_reconnect reconnects and claims it. A network blip no longer
    # costs the user their sign-in.
    print("2) Waiting for your approval — you have ~60 minutes, no rush.")
    # An AI wrapping this in a `timeout` kills the listener while the human is still
    # deciding; the consent is fine but the run looks like a failed sign-in. Say so here,
    # and say that re-running recovers, because that is not guessable from the outside.
    print("   AI: do NOT wrap this in a `timeout` — it blocks until the human clicks.")
    print("   If the listener dies BEFORE the click, run `adom-google auth` again: an earlier")
    print("   approval is recovered and the user does not click twice. But if the consent page")
    print("   answered \"Session Expired\", the click was NOT recorded: re-run and click the NEW")
    print("   link. --url-file does not change this: this process IS the listener, so only hand")
    print("   the link out while it keeps running (run it in the background, never under a short")
    print("   timeout).")
    print("   Capturing stdout to a file? Run with PYTHONUNBUFFERED=1 or you will see")
    print("   nothing until the buffer flushes and will not find the URL above.")
    sys.stdout.flush()
    try:
        # Broker mode: the gateway exchanges the code and returns tokens (the client
        # secret stays on the gateway). Falls back to relayed code if it can't broker.
        msg = _ws_wait_with_reconnect(
            pr["gateway_ws"],
            send_msgs=[{"type": "register", "state": state, "provider": "google",
                        "app": pr["app"], "exchange": want_exchange}],
            want_types=("tokens", "callback"),
            timeout=3600,
            state=state,
            gateway_url=pr["gateway_url"],
        )
    except Exception as e:
        sys.exit(f"\nGateway flow failed: {e}\n"
                 f"If you saw Google's generic 'Sorry, something went wrong there. Try again.', or\n"
                 f"waited more than ~60 minutes, just re-run `adom-google auth` (a fresh URL; an\n"
                 f"earlier approval is recovered, nobody clicks twice). A 'Session Expired' page means\n"
                 f"the click was not recorded: re-run and click the NEW link, keeping this command\n"
                 f"running until Allow lands. If the gateway itself is down ({pr['gateway_url']}),\n"
                 f"fallback: `adom-google auth --manual`.")
    # The callback landed. Say so BEFORE judging it, so an AI can tell "the user clicked and
    # Google returned an error" from "the user never clicked" (issue #9 §4).
    print(f"\n↳ Callback received from the gateway ({msg.get('type')}); the user reached the end of the consent flow.")
    sys.stdout.flush()
    if msg.get("state") != state:
        sys.exit("State mismatch from gateway — aborting.")
    if msg.get("error") or (msg.get("type") == "callback" and not msg.get("code")):
        sys.exit(f"\nGoogle returned '{msg.get('error') or 'no code'}' instead of an auth code.\n"
                 f"If that's 'access_denied' you declined consent. Otherwise the sign-in session\n"
                 f"likely expired — re-run `adom-google auth` (you have ~60 minutes to click Allow).")
    if msg.get("type") == "tokens":
        _store_broker_tokens(cfg, msg["tokens"], scopes, mode, target=target)
        _pending_clear()
        print(f"\n✅ Authorized via gateway broker ({mode} mode). Token stored (0600); "
              "client secret never touched this container.")
        via = "gateway-broker"
    else:
        _exchange_code(cfg, msg["code"], pr["gateway_redirect"], scopes, mode, target=target)
        _pending_clear()
        print(f"\n✅ Authorized via gateway ({mode} mode). Refresh token stored (0600).")
        via = "gateway-relay"
    print("   Scopes: " + ", ".join(s.split("/")[-1] for s in scopes))
    if target == "youtube":
        print(f"   YouTube added to account '{ACCOUNT}' as its YouTube grant. Your other access is unchanged;\n"
              f"   YouTube calls pick this grant automatically. Check: adom-google{_acct_flag()} scopes")
    if as_json:
        _auth_json_line(real_out, cfg, scopes, mode, via)


def _pending_path():
    return os.path.join(CFG_DIR, "pending-auth.json")


def _pending_save(state, scopes, mode, gateway_url, target="main"):
    """Remember the in-flight sign-in so a LATER run can claim it.

    Each auth run mints a fresh random state, so without this a click that lands after the CLI
    exits is unrecoverable: the gateway parks the tokens under a state nobody remembers, they
    expire unclaimed, and the user consented for nothing while seeing "Authorization Complete".
    Observed in the wild — a consent link whose CLI had exited was swept at exactly 60m."""
    try:
        os.makedirs(CFG_DIR, exist_ok=True)
        fd = os.open(_pending_path(), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as f:
            json.dump({"state": state, "scopes": scopes, "mode": mode, "target": target,
                       "gateway_url": gateway_url, "created_at": time.time()}, f)
    except OSError:
        pass                                        # never block auth on bookkeeping


def _pending_clear():
    try:
        os.remove(_pending_path())
    except OSError:
        pass


def _pending_claim(cfg, scopes, mode, gateway_url, target="main"):
    """Try to finish an EARLIER sign-in whose CLI exited before the user clicked Allow.

    Returns True if it recovered a completed authorization (nothing left to do), else False.
    Only auto-claims when the parked grant matches the scopes being asked for now — claiming a
    narrower earlier grant would silently under-authorize."""
    try:
        p = json.load(open(_pending_path()))
    except Exception:
        return False
    state = p.get("state")
    if not state:
        return False
    age = time.time() - (p.get("created_at") or 0)
    if age > 3700:                                  # past the gateway's 60m sweep — nothing to get
        _pending_clear(); return False
    try:
        r = requests.get((p.get("gateway_url") or gateway_url).rstrip("/") + "/result",
                         params={"state": state}, timeout=20)
        j = r.json()
    except Exception:
        return False
    if not j.get("ok"):
        _pending_clear(); return False              # unknown/expired state
    if j.get("pending"):
        mins = int(age // 60)
        sys.stderr.write(
            f"\nNote: an earlier consent link from {mins}m ago is still open and unclicked.\n"
            "  Approving THAT tab still works — this run mints a new link, and clicking either\n"
            "  finishes the job. (Nothing is lost either way.)\n")
        return False
    result = j.get("result") or {}
    if result.get("type") == "error":
        _pending_clear(); return False
    if sorted(p.get("scopes") or []) != sorted(scopes) or (p.get("target") or "main") != target:
        sys.stderr.write(
            "\nNote: a COMPLETED earlier approval is waiting, but it granted a different scope\n"
            "  set than this run is requesting, so it was not claimed automatically.\n")
        return False
    if result.get("type") == "tokens":
        _store_broker_tokens(cfg, result["tokens"], p.get("scopes"), p.get("mode") or mode, target=target)
    elif result.get("code"):
        _exchange_code(cfg, result["code"], _provider()["gateway_redirect"],
                       p.get("scopes"), p.get("mode") or mode, target=target)
    else:
        return False
    _pending_clear()
    print("✅ Recovered your earlier approval — you already clicked Allow, so no need to do it "
          "again.\n   Token stored (0600).")
    print("   Scopes: " + ", ".join(s.split("/")[-1] for s in (p.get("scopes") or [])))
    return True


def _auth_manual(cfg, scopes, mode):
    cid, _ = _client_creds(cfg)
    if not cfg.get("client_id"):
        print("Manual flow uses the configured OAuth client, but its redirect must allow")
        print(f"`{MANUAL_REDIRECT}`. If you hit redirect_uri_mismatch, run:")
        print("   adom-google init <your_desktop_client_id> <your_desktop_client_secret>\n")
    cfg["_pending_mode"] = mode       # so auth-code knows which scope profile was requested
    _save(cfg)
    params = {
        "client_id": cid, "redirect_uri": MANUAL_REDIRECT, "response_type": "code",
        "scope": " ".join(scopes), "access_type": "offline", "prompt": "consent",
    }
    manual_link = AUTH_URL + "?" + urllib.parse.urlencode(params)
    print(f"Manual (desktop-client) flow — {mode.upper()} mode.\n")
    print("1) Open this URL and approve. ⚠ It contains '&' — SINGLE-QUOTE the whole URL if you use")
    print("   any shell/open command, or the shell truncates it at the first '&' and Google shows")
    print("   \"Error 400: invalid_request — missing response_type\":\n")
    print("   " + manual_link)
    print("\n2) The page will fail to load (expected). Copy the `code` value from the address")
    print("   bar, then run:\n\n   adom-google auth-code '<paste-code-here>'")


def cmd_auth_code(a):
    cfg = _maybe_load_raw() or {}
    mode = cfg.get("_pending_mode", "full")
    scopes = _scopes_for(mode)
    _exchange_code(cfg, a.code, MANUAL_REDIRECT, scopes, mode)
    print(f"✅ Authorized ({mode} mode). Refresh token stored (0600).")
    print("   Scopes: " + ", ".join(s.split("/")[-1] for s in scopes))


def cmd_init(a):
    cfg = _maybe_load_raw() or {}
    cfg["client_id"] = a.client_id
    cfg["client_secret"] = a.client_secret
    _save(cfg)
    print(f"Saved client credentials to {CFG}. Next: `adom-google auth --manual`")


def cmd_provider_set(a):
    """Write the OAuth provider (gateway + client) to ~/.config/adom-google/provider.json.
    This is what the private `adom-google-adom` package drops for Adom employees; self-hosters
    point it at their own gateway + client."""
    prov = {}
    if os.path.exists(PROVIDER_PATH):
        try:
            with open(PROVIDER_PATH) as f:
                prov = json.load(f)
        except Exception:
            prov = {}
    if a.gateway:       prov["gateway_url"] = a.gateway.rstrip("/")
    if a.ws:            prov["gateway_ws"] = a.ws
    if a.client_id:     prov["client_id"] = a.client_id
    if a.client_secret: prov["client_secret"] = a.client_secret
    if a.app:           prov["app"] = a.app
    os.makedirs(CFG_DIR, exist_ok=True)
    fd = os.open(PROVIDER_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(prov, f, indent=2)
    os.chmod(PROVIDER_PATH, 0o600)
    print(f"Saved provider → {PROVIDER_PATH} (0600).")
    print("Next: ask the user safe vs full, then `adom-google auth`.")


def cmd_provider_discover(a):
    """Fetch the provider from the user's wiki org settings and cache it (0600)."""
    orgs, found = _discover_org_providers(only_org=getattr(a, "org", None))
    res = {"orgs_checked": orgs, "found": [o for o, _ in found]}
    if len(found) == 1:
        org, data = found[0]
        prov = _write_org_provider(org, data)
        res.update(ok=True, org=org, app=prov["app"], gateway_url=prov["gateway_url"],
                   mode="broker" if prov["broker"] else "relay", provider_path=PROVIDER_PATH)
        if a.json:
            print(json.dumps(res)); return
        print(f"OK: provider from {org}/org-settings → {PROVIDER_PATH} (0600)")
        print(f"   app={prov['app']}  gateway={prov['gateway_url']}  mode={res['mode']}")
        print("Next: adom-google auth   (one Allow click)")
        return
    res["ok"] = False
    if a.json:
        print(json.dumps(res)); sys.exit(1)
    if not orgs:
        sys.exit("ERROR: could not read your wiki orgs (is adom-wiki installed and signed in? try: adom-wiki whoami).")
    if not found:
        sys.exit(f"ERROR: none of your orgs ({', '.join(orgs)}) has set adom-google up in its org settings.\n"
                 "Hint: first person in the org? adom-google onboard --org <org>\n"
                 "Hint: personal or zero-setup: adom-google connect-personal")
    sys.exit(f"ERROR: several of your orgs have adom-google set up ({', '.join(res['found'])}); pick one:\n"
             + "".join(f"  adom-google provider discover --org {o}\n" for o in res["found"]))


def cmd_provider_show(a):
    pr = _provider()
    if os.path.exists(PROVIDER_PATH):       src = PROVIDER_PATH
    elif os.path.exists(BASE_PROVIDER_PATH): src = BASE_PROVIDER_PATH + " (inherited from default account)"
    elif os.path.exists(BUNDLED_PROVIDER):  src = BUNDLED_PROVIDER + " (bundled)"
    elif os.path.exists(LEGACY_CREDS) and "clientId" in open(LEGACY_CREDS).read():
        src = LEGACY_CREDS + " (legacy)"
    elif os.environ.get("OAUTH_GATEWAY_URL"): src = "environment"
    else:                                   src = "(none: run `provider discover`, or `provider set`)"
    try:
        tag = json.load(open(PROVIDER_PATH)).get("_source", "") if os.path.exists(PROVIDER_PATH) else ""
        if tag.startswith("org-settings:"):
            src += f"  [from {tag.split(':',1)[1]}/org-settings, `provider discover` refreshes it]"
    except Exception:
        pass
    print(f"app:           {pr['app']}")
    print(f"gateway_url:   {pr['gateway_url'] or '(UNSET)'}")
    print(f"gateway_ws:    {pr['gateway_ws'] or '(derived from gateway_url)'}")
    print(f"client_id:     {(pr['client_id'][:22] + '…') if pr['client_id'] else '(UNSET)'}")
    print(f"client_secret: {'present' if pr.get('client_secret') else '(none — broker mode)'}")
    print(f"source:        {src}")


def cmd_onboard(a):
    """Guided org onboarding. Prints the exact plan + canonical values (or --json for the
    skill that drives the browser). The actual Cloud-Console clicking is done by the
    `adom-google-onboarding` skill via the native browser; this command supplies the truth."""
    org = getattr(a, "org", None)
    cfg = _onboard_config(org)
    if getattr(a, "json", False):
        print(json.dumps(cfg, indent=2))
        return
    R = cfg["redirect_uri"]
    print("┌─ adom-google · onboard your org to Google Workspace ─────────────────────────┐")
    print("│  One-time setup: your team gets its OWN Google OAuth client so the AI can     │")
    print("│  read mail, post Chat on your behalf, build Slides/Sheets/Docs, search Drive, │")
    print("│  and upload to YouTube.                                                       │")
    print("│  Done ONCE by one person: Adom's gateway verifies you are in the org, checks  │")
    print("│  the client with Google and holds the secret, so every member just signs in. │")
    print("└──────────────────────────────────────────────────────────────────────────────┘\n")
    print("The AI can drive your real browser through every step below and auto-fill the")
    print("fields (recommended) — or you can do it by hand. Either way, the exact values:\n")
    print("1) Create / pick a Google Cloud project:")
    print("     " + cfg["console"]["project_create"])
    print("\n2) Enable all the APIs in ONE click:")
    print("     " + cfg["enable_apis_url"])
    for ap in cfg["apis"]:
        print(f"        • {ap['label']}")
    print("\n3) OAuth consent screen  →  User type = Internal")
    print("     " + cfg["console"]["consent_screen"])
    print(f"        App name:  {cfg['consent']['app_name']}")
    print("\n4) Create an OAuth client  →  Application type = Web application")
    print("     " + cfg["console"]["create_client"])
    print("     ⚠ Authorized redirect URI — paste EXACTLY (this is the gateway callback):")
    print("        " + R)
    print("\n5) Copy the Client ID + Client secret it shows, then register it for the WHOLE org")
    print("   (secret on stdin, so it stays out of shell history):")
    print("     printf '%s\\n' \"$SECRET\" | adom-google org register --org <your-wiki-org> --client-id <client-id>")
    print("   Teammates then just run `adom-google auth`: the non-secret half is on <org>/org-settings.")
    print("\n6) Authorize (full Workspace access by default):")
    print("     adom-google auth          # one Allow click with your Workspace account (you have ~60 min)")
    print("\n(Chat also needs a one-time Chat-app config: " + cfg["console"]["chat_config"] + ")")
    print("\n" + ONBOARD_HINT)


def _wiki_token():
    """The caller's wiki token, resolved the same way adom-wiki does: env, config, container key.
    Sent ONLY to the OAuth gateway, which uses it once to ask the wiki which orgs you belong to."""
    for k in ("ADOM_WIKI_TOKEN", "ADOMPKG_TOKEN"):
        if os.environ.get(k):
            return os.environ[k].strip()
    for path in (os.path.expanduser("~/.config/adom-wiki/config.json"),):
        try:
            t = (json.load(open(path)) or {}).get("token")
            if t:
                return t.strip()
        except Exception:
            pass
    try:
        return open("/var/run/adom/api-key").read().strip() or None
    except Exception:
        return None


def _gateway_org_call(method, path, gw, body=None, params=None):
    tok = _wiki_token()
    if not tok:
        sys.exit("ERROR: no wiki token found (adom-wiki is not signed in on this box).\n"
                 "Hint: check with `adom-wiki whoami`; the gateway uses your wiki login to confirm org membership.")
    try:
        r = requests.request(method, gw.rstrip("/") + path, json=body, params=params, timeout=60,
                             headers={"Authorization": "Bearer " + tok})
    except requests.RequestException as e:
        sys.exit(f"ERROR: could not reach the OAuth gateway at {gw}: {e}")
    try:
        return r.status_code, r.json()
    except ValueError:
        return r.status_code, {"error": f"http_{r.status_code}", "detail": r.text[:200]}


def _org_settings_record(org, client_id, gw, domain=None):
    """The NON-secret half, for <org>/org-settings integrations/google-oauth.json."""
    rec = {"schema": "adom.org-integration/1", "integration": ORG_INTEGRATION, "owner": org,
           "kind": "oauth-gateway-provider", "secret": False, "app": f"org-{org}",
           "client_id": client_id, "gateway_url": gw.rstrip("/"), "mode": "broker",
           "set_up_by": (_wiki_json(["whoami"]) or {}).get("data", {}).get("user", {}).get("username"),
           "note": ("Google OAuth client for adom-google. Public client_id only: the client secret is "
                    "held by the OAuth gateway, which does the token exchange, so no member's box ever "
                    "holds it. Members just run `adom-google auth`."),
           "updated": time.strftime("%Y-%m-%d")}
    if domain:
        rec["workspace_domains"] = [d.strip() for d in domain.split(",") if d.strip()]
    return rec


def cmd_org_register(a):
    """Register THIS org's own Google OAuth client with the gateway, once, for every member."""
    org = a.org.strip().lower()
    gw = (a.gateway or ADOM_SHARED_GATEWAY).rstrip("/")
    secret = a.client_secret
    if not secret or secret == "-":
        secret = sys.stdin.readline().strip()          # keeps it out of shell history / ps
    print(f"1) Registering {org}'s Google OAuth client with the gateway ({gw}) ...")
    print("   The gateway checks: you are a member of this org (your wiki login), the client id +")
    print("   secret are real (asks Google), and its /callback is an authorized redirect URI.")
    code, d = _gateway_org_call("POST", "/apps/register", gw,
                                body={"org": org, "client_id": a.client_id, "client_secret": secret})
    secret = None
    if code != 200 or not d.get("ok"):
        msg = d.get("hint") or d.get("detail") or ""
        sys.exit(f"ERROR: gateway refused the registration: {d.get('error')} {('(' + d['google'] + ')') if d.get('google') else ''}\n"
                 + (f"Hint: {msg}\n" if msg else "")
                 + ("Hint: redirect URI to add on the OAuth client: " + d["redirect_uri"] + "\n" if d.get("redirect_uri") else ""))
    print(f"   OK: {d['app']} registered by {d['checks']['membership']}; client valid, redirect registered"
          + ("  (replaced the previous client)" if d.get("replaced") else ""))
    print(f"2) Publishing the non-secret half to {org}/org-settings so every member picks it up ...")
    rec = _org_settings_record(org, a.client_id, gw, a.domain)
    tmp = os.path.join(CFG_DIR, f".org-settings-{org}.json")
    os.makedirs(CFG_DIR, exist_ok=True)
    with open(tmp, "w") as f:
        json.dump(rec, f, indent=2)
    r = subprocess.run(["adom-wiki", "settings", "set", org, ORG_INTEGRATION, "--file", tmp, "-m",
                        f"google-oauth: {org}'s adom-google provider (secret held by the gateway)"],
                       capture_output=True, text=True, timeout=60)
    os.unlink(tmp)
    if r.returncode != 0 or "SETTINGS_WRITTEN" not in (r.stdout + r.stderr):
        out = (r.stdout + r.stderr).strip().splitlines()
        print("   WARN: could not write org settings; members would not auto-discover yet:", file=sys.stderr)
        print("   " + "\n   ".join(out[-4:]), file=sys.stderr)
        print(f"   Hint: if {org}/org-settings does not exist yet, the error above prints the one-time create command.", file=sys.stderr)
    else:
        print(f"   OK: {org}/org-settings integrations/{ORG_INTEGRATION}.json written (members only, no secret)")
    print("3) Wiring this box ...")
    global _PROVIDER
    _PROVIDER = None
    orgs, found = _discover_org_providers(only_org=org)
    if found:
        _write_org_provider(*found[0])
    else:
        _write_org_provider(org, rec)
    print(f"   OK: provider → {PROVIDER_PATH} (0600, broker mode, no secret here)")
    print(f"\n✅ {org} is set up. You and every other member of {org}: `adom-google auth` (one Allow click).")


def cmd_org_status(a):
    org = a.org.strip().lower()
    gw = (a.gateway or ADOM_SHARED_GATEWAY).rstrip("/")
    code, d = _gateway_org_call("GET", "/apps/status", gw, params={"org": org})
    st = _wiki_json(["settings", "get", org, ORG_INTEGRATION]) or {}
    d["org_settings"] = "present" if st.get("status") == "ok" else ((st.get("hints") or [{}])[0].get("code") or "unreadable")
    if a.json:
        print(json.dumps(d)); return
    if code != 200:
        sys.exit(f"ERROR: {d.get('error')}: {d.get('hint') or d.get('detail') or ''}")
    print(f"org:            {org}  (gateway app {d.get('app')})")
    print(f"gateway:        {'registered by ' + str(d.get('registered_by')) + ' at ' + str(d.get('registered_at')) if d.get('registered') else 'NOT registered'}")
    print(f"client_id:      {d.get('client_id') or '-'}")
    print(f"org settings:   {d['org_settings']}")
    print(f"redirect_uri:   {d.get('redirect_uri')}")


def cmd_org_unregister(a):
    org = a.org.strip().lower()
    gw = (a.gateway or ADOM_SHARED_GATEWAY).rstrip("/")
    code, d = _gateway_org_call("POST", "/apps/unregister", gw, body={"org": org})
    if code != 200:
        sys.exit(f"ERROR: {d.get('error')}: {d.get('hint') or d.get('detail') or ''}")
    print(f"OK: gateway entry for {org} {'removed' if d.get('removed') else 'was not present'}. "
          f"Members' existing tokens stop refreshing. The {org}/org-settings entry is left as is; "
          f"remove it with the wiki if the org is done with adom-google.")


def cmd_onboard_finish(a):
    """Record the org's freshly-created OAuth client.

    DEFAULT (0.8.26+): register it with the gateway for the WHOLE org (`org register`): the
    gateway holds the secret and brokers, and the non-secret half goes on <org>/org-settings, so
    every member just runs `adom-google auth`. `--relay` keeps the old single-box mode where the
    secret stays 0600 on this box only and teammates cannot use it."""
    if not getattr(a, "relay", False):
        a.domain = getattr(a, "domain", None)
        return cmd_org_register(a)
    gw = (a.gateway or ADOM_SHARED_GATEWAY).rstrip("/")
    prov = {}
    if os.path.exists(PROVIDER_PATH):
        try:
            with open(PROVIDER_PATH) as f:
                prov = json.load(f)
        except Exception:
            prov = {}
    prov["gateway_url"] = gw
    prov["client_id"] = a.client_id
    prov["client_secret"] = a.client_secret or sys.stdin.readline().strip()   # the org's OWN secret, on the org's OWN box
    prov["app"] = a.org
    prov["broker"] = False                         # relay mode: gateway relays, we exchange locally
    os.makedirs(CFG_DIR, exist_ok=True)
    fd = os.open(PROVIDER_PATH, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(prov, f, indent=2)
    os.chmod(PROVIDER_PATH, 0o600)
    print(f"✅ Saved provider → {PROVIDER_PATH} (0600, RELAY mode).")
    print(f"   org/app:      {a.org}")
    print(f"   gateway:      {gw}  (shared callback; your secret never leaves this box)")
    print(f"   redirect_uri: {gw}/callback  (must match your OAuth client)")
    print("\nNext: ask the user safe vs full, then `adom-google auth`.")


def cmd_accounts(a):
    """List every configured account: the default plus each dir under accounts/."""
    rows = []
    def probe(name, cfg_dir):
        cfg_path = os.path.join(cfg_dir, "config.json")
        cfg = {}
        if os.path.exists(cfg_path):
            try:
                cfg = json.load(open(cfg_path))
            except Exception:
                pass
        prov_path = os.path.join(cfg_dir, "provider.json")
        app = None
        if os.path.exists(prov_path):
            try:
                app = json.load(open(prov_path)).get("app")
            except Exception:
                pass
        rows.append({"account": name, "authorized": bool(cfg.get("refresh_token")),
                     "mode": cfg.get("mode"), "app": app, "config": cfg_path})
    probe("default", BASE_CFG_DIR)
    acct_root = os.path.join(BASE_CFG_DIR, "accounts")
    if os.path.isdir(acct_root):
        for name in sorted(os.listdir(acct_root)):
            if os.path.isdir(os.path.join(acct_root, name)):
                probe(name, os.path.join(acct_root, name))
    if getattr(a, "json", False):
        print(json.dumps(rows, indent=2))
        return
    for r in rows:
        star = "*" if r["account"] == ACCOUNT else " "
        auth = f"authorized ({r['mode'] or 'mode unset'})" if r["authorized"] else "NOT authorized"
        app = f"  app={r['app']}" if r["app"] else ""
        print(f"{star} {r['account']:<12} {auth}{app}")
    print("\nSelect one per-command with `--account <name>` or export ADOM_GOOGLE_ACCOUNT=<name>.")


def cmd_connect_personal(a):
    """Connect a non-adom.inc Google account (personal @gmail, or another org's Workspace) via
    Adom's global 'Adom Google Connector' OAuth client — no manual Google-Cloud setup. Writes the
    built-in provider to the `personal` account (or `--as <name>`), then the user runs
    `adom-google --account personal auth`."""
    if not ADOM_PERSONAL_CLIENT_ID:
        sys.exit("Connector sign-in is still being provisioned (Adom is standing up the shared\n"
                 "'Adom Google Connector' client). Not available yet — check back soon or email\n"
                 "support@adom.inc. Your work account (`adom-google auth`) is unaffected.")
    # `--as <name>` makes another Connector profile (e.g. a second personal Google account).
    # YouTube does NOT need one: `--account <name> auth --youtube` adds it to the same profile.
    name = (getattr(a, "as_name", None) or "personal").strip()
    if not re.fullmatch(r"[A-Za-z0-9._-]+", name) or name in (".", "..", "default"):
        sys.exit(f"ERROR: bad profile name {name!r}. Hint: letters, digits, . _ - only, e.g. --as youtube")
    acct_dir = os.path.join(BASE_CFG_DIR, "accounts", name)
    os.makedirs(acct_dir, exist_ok=True)
    prov = {"gateway_url": ADOM_SHARED_GATEWAY, "client_id": ADOM_PERSONAL_CLIENT_ID,
            "app": ADOM_PERSONAL_APP, "broker": True}
    ppath = os.path.join(acct_dir, "provider.json")
    fd = os.open(ppath, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(prov, f, indent=2)
    os.chmod(ppath, 0o600)
    yt = name.lower().startswith("youtube")
    print(f"✅ Connector profile '{name}' ready (uses Adom's shared Google Connector client — no setup needed).")
    print("   Authorize your account now:\n")
    print(f"      adom-google --account {name} auth" + ("  --youtube" if yt else "") + "\n")
    if yt:
        print("   Grants ONLY youtube + youtube.upload. (Not needed for YouTube on an existing profile:")
        print(f"   `adom-google --account <profile> auth --youtube` adds it there.)")
    else:
        print("   Grants Calendar, Contacts, Tasks, Drive (files it creates), and Gmail send/compose today.")
        print("   (Full Gmail read + all Drive/Docs/Sheets/Slides unlock automatically once Adom's Google")
        print("   verification + CASA clear — no action needed. Testers can add `--full` now.)")
        print(f"   Add YouTube later, same profile:  adom-google --account {name} auth --youtube")
    print("   Google will show an 'unverified app' notice while verification is pending — choose")
    print("   Advanced → Continue to proceed.")
    print(f"   Use this profile any time:  adom-google --account {name} <command>")


def cmd_setup(a):
    # Canonical first-run entry point. Always prints the ask-the-user hint (even mid-config),
    # so the installing AI is reminded to ask the safe/full question before authorizing.
    print(SETUP_HINT)


def _normalize_scope(s):
    """Accept either a full scope URL or the short tail ('chat.spaces')."""
    return s if s.startswith("http") else "https://www.googleapis.com/auth/" + s


def cmd_scopes(a):
    """GRANTED scopes (authoritative, from Google's tokeninfo) vs REQUESTED (what auth asked for).

    `status` prints cfg['scopes'], which is only a record of what was REQUESTED at auth
    time — it says nothing about what Google actually granted, and agents have made wrong
    architectural calls trusting it (wiki-notify-gchat, 2026-07-21). This command refreshes
    the access token and asks tokeninfo for the truth.

    NOTE: tokeninfo reports granted SCOPES but not whether an API is enabled in the GCP
    project. To probe real capability without creating anything, send a deliberately
    invalid body to the target method: missing scope → 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT
    (fails before body validation); scope present → 400 INVALID_ARGUMENT.
    """
    cfg = _maybe_load_raw()
    if not cfg or not cfg.get("refresh_token"):
        sys.exit(SETUP_HINT)
    tok = _access_token(cfg)
    r = requests.get("https://oauth2.googleapis.com/tokeninfo",
                     params={"access_token": tok}, timeout=30)
    if r.status_code != 200:
        sys.exit(f"tokeninfo failed ({r.status_code}): {r.text[:200]}")
    granted = sorted(r.json().get("scope", "").split())
    requested = sorted(cfg.get("scopes") or [])
    missing = [s for s in requested if s not in granted]      # asked for, NOT granted
    extra = [s for s in granted if s not in requested]        # granted, never recorded
    # The account's YouTube grant (issue #12), if any: its own token, checked the same way.
    ytg = _yt_grant(cfg)
    yt_granted = (_tokeninfo_scopes(ytg, root=cfg) or []) if ytg else []
    have = set(granted) | {x for x in yt_granted if _is_yt_scope(x)}
    required = [_normalize_scope(s) for s in (getattr(a, "require", None) or [])]
    short = [s for s in required if s not in have]

    if getattr(a, "json", False):
        print(json.dumps({"granted": granted, "requested": requested,
                          "drift": {"requested_not_granted": missing, "granted_not_requested": extra},
                          "require": {"required": required, "missing": short} if required else None,
                          "grants": {"youtube": {"granted": yt_granted, "used_for": "YouTube API calls"}} if ytg else {},
                          "account": ACCOUNT, "mode": cfg.get("mode")}, indent=2))
    else:
        tail = lambda s: s.split("/")[-1]
        print(f"GRANTED   ({len(granted)}, authoritative via tokeninfo):")
        for s in granted: print(f"  ✓ {tail(s)}")
        if missing:
            print(f"DRIFT — requested at auth but NOT granted:")
            for s in missing: print(f"  ✗ {tail(s)}")
        if extra:
            print(f"DRIFT — granted but not in the recorded request:")
            for s in extra: print(f"  + {tail(s)}")
        if not missing and not extra:
            print("No drift: granted matches the recorded request.")
        if ytg:
            print(f"YOUTUBE GRANT ({len(yt_granted)}, a second grant on this account, used for YouTube calls):")
            for s in yt_granted: print(f"  ✓ {tail(s)}")
            if not yt_granted:
                print(f"  ✗ could not be checked (refresh failed?). Re-add it: adom-google{_acct_flag()} auth --youtube --rebind")
        if required:
            print(f"REQUIRE check: {'ALL PRESENT' if not short else 'MISSING → ' + ', '.join(tail(s) for s in short)}")

    if short:
        # YouTube on an account that holds drive.file: Google refuses that union in ONE consent
        # (issue #12), so the YouTube part becomes the account's second grant. Nothing the account
        # holds changes, and the user still has one account.
        yt_short = [x for x in short if _is_yt_scope(x)]
        # A YouTube grant that exists (even a broken one) owns YouTube calls, so it is the thing to
        # re-mint; otherwise only a drive.file clash forces a separate grant.
        if yt_short and (ytg or _yt_conflict(granted + yt_short)):
            other_short = [x for x in short if not _is_yt_scope(x)]
            if other_short:
                tails = " ".join(x.split("/")[-1] for x in other_short)
                print(f"\nFix (two steps; Google will not take YouTube and drive.file in one consent):\n"
                      f"  adom-google{_acct_flag()} scopes --require {tails} --auto-widen\n"
                      f"  adom-google{_acct_flag()} auth --youtube", file=sys.stderr)
                sys.exit(2)
            if getattr(a, "auto_widen", False):
                print("\n--auto-widen: this account holds drive.file, which Google will not grant in one consent")
                print("with YouTube, so YouTube is added as a SECOND grant on the same account. Nothing you")
                print("hold changes.")
                import types
                na = types.SimpleNamespace(manual=False, safe=False, full=False, admin=False, youtube=False,
                                           grant_target="youtube", url_file=getattr(a, "url_file", None),
                                           add_scopes=yt_short, preserve_scopes=[])
                return cmd_auth(na)
            print(f"\nFix (one consent, keeps everything): adom-google{_acct_flag()} scopes --require "
                  + " ".join(x.split("/")[-1] for x in yt_short) + " --auto-widen", file=sys.stderr)
            sys.exit(2)
        widen_flags = " ".join(f"--add-scope {s.split('/')[-1]}" for s in short)
        acct = "" if ACCOUNT == "default" else f" --account {ACCOUNT}"
        fix = f"adom-google{acct} auth{' --safe' if cfg.get('mode') == 'safe' else ''} {widen_flags}"
        if getattr(a, "auto_widen", False):
            print(f"\n--auto-widen: re-running auth with the union of GRANTED + required…")
            import types
            # Union against what is actually GRANTED, never the tier default. Unioning against
            # the tier silently dropped everything held beyond it — after `auth --admin` this
            # built an 18-scope URL (17 tier + 1 new) instead of 22, so approving it would have
            # REVOKED domain group admin while appearing to add a capability. The help text
            # promises --auto-widen "preserves what you already hold", so it must actually do
            # that. (Reported 2026-07-22.)
            na = types.SimpleNamespace(manual=False, safe=cfg.get("mode") == "safe",
                                       full=cfg.get("mode") == "full", admin=False,
                                       youtube=False,
                                       url_file=getattr(a, "url_file", None),
                                       add_scopes=short, preserve_scopes=granted)
            return cmd_auth(na)
        print(f"\nFix: {fix}", file=sys.stderr)
        sys.exit(2)


def cmd_status(a):
    cfg = _maybe_load_raw()
    authorized = bool(cfg and cfg.get("refresh_token"))
    if getattr(a, "json", False):
        # One object, one boolean, and the exit code agrees with it: a waiter can use either.
        try:
            pr = _provider()
        except SystemExit:
            pr = {}
        print(json.dumps({"authorized": authorized, "account": ACCOUNT, "config": CFG,
                          "mode": (cfg or {}).get("mode"), "scopes": (cfg or {}).get("scopes") or [],
                          "gateway": pr.get("gateway_url"), "app": pr.get("app"),
                          "hint": None if authorized else "not authorized: run `adom-google auth` (or `auth --json` to block until Allow is clicked)"}))
        sys.exit(0 if authorized else 1)
    if not authorized:
        # Failure text goes to STDERR and the exit code is 1. Before, `status` exited 0 and its
        # setup hint contained the words "authorized"/"FULL"/"access", so a naive
        # `until adom-google status | grep -qi authorized` fired instantly on the FAILURE
        # message (issue #9 §3). Waiters should use `auth --json` or `status --json` instead.
        sys.stderr.write(SETUP_HINT + "\n")
        sys.exit(1)
    pr = _provider()
    cid = cfg.get("client_id") or pr["client_id"] or "(none)"
    src = "config" if cfg.get("client_id") else ("provider" if pr["client_id"] else "UNSET")
    print(f"Account:     {ACCOUNT}" + ("" if ACCOUNT == "default" else "  (select with --account or ADOM_GOOGLE_ACCOUNT)"))
    print(f"Config:      {CFG}")
    print(f"Provider:    gateway={pr['gateway_url'] or '(UNSET — run `provider set`)'}  app={pr['app']}")
    print(f"OAuth client: {(cid[:18] + '…') if cid != '(none)' else cid} (from {src})")
    print(f"Refresh token: {'present' if cfg.get('refresh_token') else 'MISSING — run auth'}")
    print(f"Access:       {cfg.get('mode', '(unset)')}  (full = whole Workspace incl. delete [default]; safe = create-only)")
    relay = pr.get("broker") is False
    print(f"Auth:         {'broker (secret on gateway, none here)' if cfg.get('broker') else ('relay (your secret 0600 here; Adom lends only its callback)' if relay else 'local (client secret in config)')}")
    print(f"Scopes:       {', '.join(s.split('/')[-1] for s in (cfg.get('scopes') or [])) or '(none)'}")
    if cfg.get("_migrated_from"):
        print(f"Migrated from: {cfg['_migrated_from']} (gmail.readonly only — run `auth` to add contacts)")
    # never print client_secret / refresh_token values


HELP = """adom-google — Google Workspace from your Adom container (Gmail, Contacts, …)

AUTH (one time; one consent → long-lived refresh token, stored 0600):
  adom-google auth              Authorize (FULL Workspace access — the default; no mode quiz).
                                Prints a consent URL; user clicks Allow ONCE (they have ~60 min,
                                no rush).
  adom-google auth --safe       Advanced: narrower create-only scopes (no "delete all"). Only
                                if the user explicitly wants to minimize scopes.
  adom-google auth --manual     fallback: desktop-client paste flow
  adom-google auth-code '<code>'   finish the --manual flow
  adom-google init <id> <secret>   set an explicit desktop OAuth client (for --manual)
  adom-google auth --json       tooling: guidance on stderr, ONE JSON line on stdout when authorized
  adom-google youtube upload <file> [--privacy unlisted|private|public] [--playlist id]
                                resumable upload; prints the watch URL + the privacy YouTube really
                                applied. Needs YouTube on the account; add it once (one Allow click,
                                everything the account holds is kept):
                                  adom-google auth --youtube
                                Google will not take YouTube and drive.file in one consent, so on an
                                account holding drive.file YouTube becomes a second grant on the SAME
                                account; YouTube calls use it automatically.
  adom-google youtube channels | list | delete <id> --yes
  adom-google status [--json]   show access + what was REQUESTED at auth (never prints secrets).
                                Exit 1 when NOT authorized; --json gives authorized:true|false.
  adom-google scopes [--json]   authoritative GRANTED scopes (live tokeninfo) + drift vs requested
  adom-google scopes --require chat.spaces [--auto-widen]
                                gate for other tools: exit 2 + exact fix when a scope is missing;
                                --auto-widen re-runs auth with the union

ONBOARD A NEW ORG (give your team its OWN Google OAuth client — the AI hand-holds you):
  adom-google onboard [--org <slug>]   print the step-by-step plan + exact values to use
  adom-google onboard --json           same, machine-readable (the onboarding skill reads this)
  adom-google onboard finish --org <slug> --client-id <id> --client-secret <secret>
                                       record your new client (RELAY mode: secret stays 0600
                                       on THIS box; rides Adom's shared callback URL)
  → The `adom-google-onboarding` skill drives your real browser through Google Cloud Console
    and auto-fills the fields. Then: pick safe/full, `adom-google auth`, done.

GMAIL (read-only; migrated from adom-gmail):
  adom-google gmail attachments <messageId>            list attachments + ids
  adom-google gmail read <messageId> <attId> [-o f]    dump attachment bytes
  adom-google gmail ics  <messageId>                   parse .ics invite(s)

CONTACTS (Google People API; read + write):
  adom-google contacts create --name "First Last" [--org O] [--title T] \\
      [--email a@b.com ...] [--phone +1... ...] [--notes "..."] [--json]
  adom-google contacts list [--limit N] [--json]
  adom-google contacts search <query> [-v] [--json]

PEOPLE (your Workspace DOMAIN directory; read-only `directory.readonly`, NOT an admin scope):
  adom-google people find <name|email> [--dm] [--limit N] [--json]
                                who is <name>: email, title, department; exact first-name /
                                email matches first; several matches are ALL listed, never
                                picked for you. --dm also shows each existing 1:1 Chat DM space.
  adom-google people list [--limit N] [--json]   everyone in the domain directory
  Domain-only: results are only accounts in YOUR OWN Workspace domain (no personal contacts,
  no shared external contacts). Older tokens lack the scope; widen once (one Allow click):
    adom-google scopes --require directory.readonly --auto-widen

CHAT (Google Chat — posts as YOU, your own identity, no attribution prefix;
      adom-gchat is the other one — it posts via an org webhook with "(on behalf of)"):
  adom-google chat spaces [--json]                     list your spaces (id · type · name)
  adom-google chat dm <email|name> [--json]            resolve the 1:1 DM space with a person;
                                                       a name resolves via the domain directory
                                                       (one unique exact match, else ERROR listing them)
  adom-google chat send --to <space-id|email> "<text>" post a message (email auto-resolves DM)
      "<text>" may be '-' (stdin) or '@file'; --thread <key> replies in a thread
  adom-google chat read --from <space-id|email> [--limit N] [--json]   recent messages
  adom-google chat send --to <space-id|email> "text" [--thread K] [--attach P]... [--json]

API (generic passthrough — hit ANY Google API with your token; the "whole board"):
  adom-google api <url> [-X METHOD] [-d '<json>'|@file] [-q k=v ...] [--raw]
    e.g. adom-google api https://sheets.googleapis.com/v4/spreadsheets/<id>/values/A1:C5
         adom-google api -X POST https://docs.googleapis.com/v1/documents -d '{"title":"Report"}'
  Reach == the scopes the token holds (see `status`). Widen via SCOPES + re-`auth`
  + enabling that API in the GCP project.

DRIVE / CALENDAR / SHEETS / DOCS / SLIDES: either use `api` above, or add a typed
subcommand. Add the scope in SCOPES (top of this file) and re-run `auth`.

ACCOUNTS (multiple Google accounts, fully isolated — e.g. work + personal):
  adom-google accounts [--json]        list configured accounts (token presence, mode, app)
  adom-google --account <name> <cmd>   run ANY command against a named account
  ADOM_GOOGLE_ACCOUNT=<name>           same, via env (flag wins)
  The default (unnamed) account keeps the original paths; a named account lives at
  ~/.config/adom-google/accounts/<name>/ with its OWN config.json + provider.json.
  Its provider inherits from the default account's provider.json unless overridden —
  set a different OAuth client/app with:  adom-google --account <name> provider set …
  First-time auth for a new account:      adom-google --account <name> auth [--full]

DASHBOARD (the Adom Google card on the Hydrogen Dock Bar; read only, loopback only):
  adom-google dashboard [--port N]     start it in the background (or reuse the running one of the
                                       same version), print its URL: http://127.0.0.1:8861/
  adom-google dashboard --print-url    print EXACTLY the URL on stdout (what the dock awaits)
  adom-google dashboard --json | --stop | --foreground
  Shows every signed-in account: email, tier, whether the token refreshes, and the GRANTED scopes
  grouped by service (Gmail, Drive, Docs/Sheets/Slides, Calendar, Tasks, Contacts, Chat, directory,
  YouTube) with the exact `scopes --require ... --auto-widen` command for anything missing. It never
  signs in, never widens, writes nothing to your config, and never shows mail, files or people.

SECURITY: config is 0600; secrets are never echoed to stdout/stderr or logs.
"""


# ---------------------------------------------------------------- typed subcommands
# Thin, guided wrappers over the Google REST APIs (issue #662): Calendar, Drive, Sheets,
# Docs, Slides, and Tasks were named in the brief and discovery triggers but only reachable
# through the raw `api` passthrough. These give first-class, discoverable commands for the
# common flows; anything deeper still drops to `adom-google api <url>`.

def cmd_calendar_list(a):
    cfg = _load()
    params = {"maxResults": str(a.max), "singleEvents": "true", "orderBy": "startTime",
              "timeMin": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).isoformat()}
    res = _request(cfg, "GET", f"{CAL_API}/calendars/{urllib.parse.quote(a.cal)}/events?{urllib.parse.urlencode(params)}")
    events = res.get("items", [])
    if a.json:
        print(json.dumps(events, indent=2, ensure_ascii=False)); return
    if not events:
        print("(no upcoming events)"); return
    for e in events:
        start = (e.get("start") or {}).get("dateTime") or (e.get("start") or {}).get("date") or "?"
        print(f"{start}  {e.get('summary','(no title)')}  [{e.get('id','')}]")


def cmd_calendar_create(a):
    cfg = _load()
    if not a.start or not a.end:
        sys.exit("calendar create needs --start and --end (RFC3339, e.g. 2026-08-20T14:00:00-05:00)")
    body = {"summary": a.summary,
            "start": {"dateTime": a.start}, "end": {"dateTime": a.end}}
    if a.location: body["location"] = a.location
    if a.description: body["description"] = a.description
    if a.attendees:
        body["attendees"] = [{"email": e.strip()} for e in a.attendees.split(",") if e.strip()]
    params = {"sendUpdates": "all" if a.send else "none"}
    res = _request(cfg, "POST", f"{CAL_API}/calendars/{urllib.parse.quote(a.cal)}/events?{urllib.parse.urlencode(params)}",
                   json=body)
    if a.json:
        print(json.dumps(res, indent=2, ensure_ascii=False)); return
    print(res.get("htmlLink") or res.get("id", ""))
    sys.stderr.write(f"→ created '{a.summary}'" + (" (invites sent)" if a.send else "") + "\n")


def cmd_calendar_calendars(a):
    cfg = _load()
    res = _request(cfg, "GET", f"{CAL_API}/users/me/calendarList")
    cals = res.get("items", [])
    if a.json:
        print(json.dumps(cals, indent=2, ensure_ascii=False)); return
    for c in cals:
        print(f"{c.get('id')}  ·  {c.get('summary','')}" + ("  (primary)" if c.get("primary") else ""))


def cmd_drive_list(a):
    cfg = _load()
    params = {"pageSize": str(a.limit), "fields": "files(id,name,mimeType,modifiedTime,size)",
              "orderBy": "modifiedTime desc"}
    if a.query: params["q"] = a.query
    res = _request(cfg, "GET", f"{DRIVE_API}/files?{urllib.parse.urlencode(params)}")
    files = res.get("files", [])
    if a.json:
        print(json.dumps(files, indent=2, ensure_ascii=False)); return
    if not files:
        print("(no files)"); return
    for f in files:
        print(f"{f.get('id')}  {f.get('name','')}  ({f.get('mimeType','')})")


def cmd_drive_upload(a):
    cfg = _load()
    if not os.path.isfile(a.path):
        sys.exit(f"file not found: {a.path}")
    import mimetypes
    name = a.name or os.path.basename(a.path)
    mime = a.mime or mimetypes.guess_type(name)[0] or "application/octet-stream"
    with open(a.path, "rb") as f:
        blob = f.read()
    up = _request(cfg, "POST", f"{DRIVE_UPLOAD}/files?uploadType=media",
                  headers={"Content-Type": mime}, data=blob)
    fid = up.get("id")
    if fid and name:
        up = _request(cfg, "PATCH", f"{DRIVE_API}/files/{fid}?fields=id,name,webViewLink",
                      json={"name": name})
    if a.json:
        print(json.dumps(up, indent=2, ensure_ascii=False)); return
    print(up.get("webViewLink") or up.get("id", ""))
    sys.stderr.write(f"→ uploaded {name} ({len(blob)//1024} KB, {mime})\n")


def _created_link(res, kind):
    fid = res.get("spreadsheetId") or res.get("documentId") or res.get("presentationId") or res.get("id", "")
    urls = {"sheet": f"https://docs.google.com/spreadsheets/d/{fid}/edit",
            "doc": f"https://docs.google.com/document/d/{fid}/edit",
            "slides": f"https://docs.google.com/presentation/d/{fid}/edit"}
    return urls.get(kind, fid), fid


def cmd_sheets_create(a):
    cfg = _load()
    res = _request(cfg, "POST", f"{SHEETS_API}/spreadsheets", json={"properties": {"title": a.title}})
    if a.json:
        print(json.dumps(res, indent=2, ensure_ascii=False)); return
    link, _ = _created_link(res, "sheet"); print(link)
    sys.stderr.write(f"→ created spreadsheet '{a.title}'\n")


def cmd_docs_create(a):
    cfg = _load()
    res = _request(cfg, "POST", f"{DOCS_API}/documents", json={"title": a.title})
    if a.json:
        print(json.dumps(res, indent=2, ensure_ascii=False)); return
    link, _ = _created_link(res, "doc"); print(link)
    sys.stderr.write(f"→ created doc '{a.title}'\n")


def cmd_slides_create(a):
    cfg = _load()
    res = _request(cfg, "POST", f"{SLIDES_API}/presentations", json={"title": a.title})
    if a.json:
        print(json.dumps(res, indent=2, ensure_ascii=False)); return
    link, _ = _created_link(res, "slides"); print(link)
    sys.stderr.write(f"→ created presentation '{a.title}'\n")


def cmd_tasks_list(a):
    cfg = _load()
    res = _request(cfg, "GET", f"{TASKS_API}/lists/{a.list}/tasks?showCompleted=false&maxResults=100")
    items = res.get("items", [])
    if a.json:
        print(json.dumps(items, indent=2, ensure_ascii=False)); return
    if not items:
        print("(no tasks)"); return
    for t in items:
        print(f"[{'x' if t.get('status')=='completed' else ' '}] {t.get('title','')}  ({t.get('id','')})")


def cmd_tasks_add(a):
    cfg = _load()
    body = {"title": a.title}
    if a.notes: body["notes"] = a.notes
    res = _request(cfg, "POST", f"{TASKS_API}/lists/{a.list}/tasks", json=body)
    if a.json:
        print(json.dumps(res, indent=2, ensure_ascii=False)); return
    print(res.get("id", ""))
    sys.stderr.write(f"→ added task '{a.title}'\n")



# ---------------------------------------------------------------- youtube
def _yt_privacy_warn(requested, actual, vid):
    """Say plainly when YouTube overrode the requested privacy.

    An API project that has not passed YouTube's API compliance audit has videos.insert LOCKED TO
    PRIVATE: the request succeeds, the response says private, and nothing explains why. Silently
    returning "uploaded" there is how a video meant to be shared sits invisible (issue #11)."""
    if actual == requested:
        return
    sys.stderr.write(
        f"\n⚠ YouTube applied privacyStatus={actual}, NOT the {requested} you asked for.\n"
        "  Almost always this project has not passed YouTube's API compliance audit: uploads from an\n"
        "  unaudited project are forced to private, whatever you send. The upload itself is fine.\n"
        "  Fix it either way:\n"
        f"    • flip it by hand now:  https://studio.youtube.com/video/{vid}/edit\n"
        "    • or submit the project for the YouTube API audit (one time, then the API honours it):\n"
        "      https://support.google.com/youtube/contact/yt_api_form\n")


def cmd_youtube_upload(a):
    path = os.path.expanduser(a.file)
    if not os.path.isfile(path):
        sys.exit(f"ERROR: no such file: {path}")
    size = os.path.getsize(path)
    if size == 0:
        sys.exit(f"ERROR: {path} is empty")
    cfg = _load()
    title = a.title or os.path.splitext(os.path.basename(path))[0]
    body = {"snippet": {"title": title, "description": a.description or "",
                        "categoryId": a.category or "22"},
            "status": {"privacyStatus": a.privacy, "selfDeclaredMadeForKids": False}}
    if a.tags:
        body["snippet"]["tags"] = [t.strip() for t in a.tags.split(",") if t.strip()]
    mime = "video/mp4"
    ext = os.path.splitext(path)[1].lower()
    if ext in (".mov", ".qt"): mime = "video/quicktime"
    elif ext == ".webm":       mime = "video/webm"
    elif ext in (".mkv",):     mime = "video/x-matroska"
    elif ext in (".avi",):     mime = "video/x-msvideo"

    # 1. Start a RESUMABLE session. The video bytes cannot ride the JSON passthrough: YouTube wants
    #    a resumable (or multipart) upload, and resumable is the only sane option for large files
    #    because a dropped connection can be continued instead of restarted.
    r = _request_raw(cfg, "POST", YT_UPLOAD, params=[("uploadType", "resumable"), ("part", "snippet,status")],
                 json=body, headers={"X-Upload-Content-Length": str(size),
                                     "X-Upload-Content-Type": mime})
    if r.status_code not in (200, 201):
        _scope_wall_hint(YT_UPLOAD, r)
        sys.exit(f"ERROR: could not start the upload: HTTP {r.status_code} {r.text[:400]}")
    session = r.headers.get("Location")
    if not session:
        sys.exit("ERROR: YouTube did not return a resumable session URL.")

    # 2. Send the bytes in chunks, resuming on a dropped connection rather than starting over.
    chunk = max(256 * 1024, (a.chunk_mb or 8) * 1024 * 1024)
    chunk -= chunk % (256 * 1024)            # YouTube requires a multiple of 256 KiB
    tok = _token_for(cfg, YT_UPLOAD)
    sent, tries, video = 0, 0, None
    t0 = time.time()
    with open(path, "rb") as f:
        while sent < size:
            f.seek(sent)
            data = f.read(chunk)
            end = sent + len(data) - 1
            try:
                pr = requests.put(session, data=data, timeout=600, headers={
                    "Authorization": "Bearer " + tok, "Content-Type": mime,
                    "Content-Length": str(len(data)),
                    "Content-Range": f"bytes {sent}-{end}/{size}"})
            except requests.RequestException as e:
                tries += 1
                if tries > 5:
                    sys.exit(f"ERROR: upload failed after {tries} attempts: {e}\n"
                             f"Hint: rerun the same command; YouTube keeps the session briefly and it resumes.")
                time.sleep(min(30, 2 ** tries))
                sent = _yt_resume_offset(session, tok, size, sent)
                continue
            if pr.status_code in (200, 201):
                video = pr.json()
                sent = size
                break
            if pr.status_code == 308:                       # chunk accepted, keep going
                tries = 0
                rng = pr.headers.get("Range")                # e.g. bytes=0-8388607
                sent = int(rng.split("-")[-1]) + 1 if rng else sent + len(data)
            elif pr.status_code in (500, 502, 503, 504):
                tries += 1
                if tries > 5:
                    sys.exit(f"ERROR: YouTube kept failing ({pr.status_code}). Rerun to resume.")
                time.sleep(min(30, 2 ** tries))
                sent = _yt_resume_offset(session, tok, size, sent)
            else:
                _scope_wall_hint(YT_UPLOAD, pr)
                sys.exit(f"ERROR: upload rejected: HTTP {pr.status_code} {pr.text[:400]}")
            if not a.quiet:
                pct = 100.0 * sent / size
                sys.stderr.write(f"\r   uploading {pct:5.1f}%  ({sent // 1048576}/{size // 1048576} MiB)")
                sys.stderr.flush()
    if not a.quiet:
        sys.stderr.write(f"\r   uploaded {size // 1048576} MiB in {int(time.time() - t0)}s\n")
    if not video:
        sys.exit("ERROR: upload finished but YouTube returned no video resource.")

    vid = video["id"]
    # 3. Read the privacy YouTube ACTUALLY applied, from a fresh GET rather than trusting the insert
    #    response, and say so.
    actual = (video.get("status") or {}).get("privacyStatus")
    g = _request_raw(cfg, "GET", f"{YT_API}/videos", params=[("part", "status,snippet,processingDetails"), ("id", vid)])
    if g.status_code == 200 and (g.json().get("items") or []):
        it = g.json()["items"][0]
        actual = (it.get("status") or {}).get("privacyStatus", actual)
    watch = f"https://www.youtube.com/watch?v={vid}"
    if a.thumbnail:
        tp = os.path.expanduser(a.thumbnail)
        if os.path.isfile(tp):
            with open(tp, "rb") as tf:
                tr = _request_raw(cfg, "POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
                              params=[("videoId", vid)], data=tf.read(),
                              headers={"Content-Type": "image/png" if tp.lower().endswith(".png") else "image/jpeg"})
            print(f"   thumbnail: {'set' if tr.status_code in (200, 201) else 'FAILED ' + str(tr.status_code)}")
        else:
            print(f"   thumbnail: SKIPPED (no such file: {tp})", file=sys.stderr)
    if a.playlist:
        pr2 = _request_raw(cfg, "POST", f"{YT_API}/playlistItems", params=[("part", "snippet")],
                       json={"snippet": {"playlistId": a.playlist,
                                         "resourceId": {"kind": "youtube#video", "videoId": vid}}})
        print(f"   playlist:  {'added' if pr2.status_code in (200, 201) else 'FAILED ' + str(pr2.status_code) + ' ' + pr2.text[:120]}")
    if a.json:
        print(json.dumps({"id": vid, "watch_url": watch, "title": title,
                          "privacy_requested": a.privacy, "privacy_applied": actual,
                          "privacy_honored": actual == a.privacy, "bytes": size,
                          "studio_url": f"https://studio.youtube.com/video/{vid}/edit"}))
    else:
        print(f"✅ uploaded: {title}")
        print(f"   video id:  {vid}")
        print(f"   watch:     {watch}")
        print(f"   privacy:   {actual}" + ("" if actual == a.privacy else f"  (you asked for {a.privacy})"))
        print(f"   studio:    https://studio.youtube.com/video/{vid}/edit")
    _yt_privacy_warn(a.privacy, actual, vid)


def _yt_resume_offset(session, tok, size, fallback):
    """Ask YouTube how much it already has, so a retry continues instead of re-sending."""
    try:
        q = requests.put(session, timeout=60, headers={
            "Authorization": "Bearer " + tok, "Content-Length": "0",
            "Content-Range": f"bytes */{size}"})
        if q.status_code == 308:
            rng = q.headers.get("Range")
            return int(rng.split("-")[-1]) + 1 if rng else 0
        if q.status_code in (200, 201):
            return size
    except requests.RequestException:
        pass
    return fallback


def cmd_youtube_channels(a):
    cfg = _load()
    r = _request_raw(cfg, "GET", f"{YT_API}/channels", params=[("part", "snippet,contentDetails,statistics"), ("mine", "true")])
    if r.status_code != 200:
        _scope_wall_hint(f"{YT_API}/channels", r)
        sys.exit(f"ERROR: HTTP {r.status_code} {r.text[:300]}")
    items = r.json().get("items") or []
    if a.json:
        print(json.dumps(items)); return
    if not items:
        print("No YouTube channel on this Google account."); return
    for it in items:
        up = (it.get("contentDetails") or {}).get("relatedPlaylists", {}).get("uploads")
        st = it.get("statistics") or {}
        print(f"{it['snippet']['title']}  ·  {it['id']}")
        print(f"   uploads playlist: {up}   videos: {st.get('videoCount', '?')}   subscribers: {st.get('subscriberCount', '?')}")
    acct = "" if ACCOUNT == "default" else f" --account {ACCOUNT}"
    print(f"\nUploads from this account land on the channel above. Wrong channel? Run\n"
          f"`adom-google{acct} auth --youtube --rebind` and pick the CHANNEL (Brand Account) in Google's chooser.")


def cmd_youtube_list(a):
    cfg = _load()
    r = _request_raw(cfg, "GET", f"{YT_API}/search", params=[("part", "snippet"), ("forMine", "true"),
                                                        ("type", "video"), ("order", "date"),
                                                        ("maxResults", str(a.max))])
    if r.status_code != 200:
        _scope_wall_hint(f"{YT_API}/search", r)
        sys.exit(f"ERROR: HTTP {r.status_code} {r.text[:300]}")
    items = r.json().get("items") or []
    ids = [i["id"]["videoId"] for i in items]
    priv = {}
    if ids:
        g = _request_raw(cfg, "GET", f"{YT_API}/videos", params=[("part", "status"), ("id", ",".join(ids))])
        if g.status_code == 200:
            priv = {i["id"]: (i.get("status") or {}).get("privacyStatus") for i in g.json().get("items", [])}
    if a.json:
        print(json.dumps([{"id": i["id"]["videoId"], "title": i["snippet"]["title"],
                           "published": i["snippet"]["publishedAt"],
                           "privacy": priv.get(i["id"]["videoId"])} for i in items])); return
    for i in items:
        v = i["id"]["videoId"]
        print(f"{i['snippet']['publishedAt'][:10]}  {priv.get(v, '?'):8}  {v}  {i['snippet']['title'][:60]}")


def cmd_youtube_delete(a):
    """Delete ONE video by id. Deliberately single-id only: no query, no bulk."""
    cfg = _load()
    g = _request_raw(cfg, "GET", f"{YT_API}/videos", params=[("part", "snippet"), ("id", a.video_id)])
    title = "(unknown)"
    if g.status_code == 200 and (g.json().get("items") or []):
        title = g.json()["items"][0]["snippet"]["title"]
    elif g.status_code == 200:
        sys.exit(f"ERROR: no video with id {a.video_id} on this account.")
    if not a.yes:
        sys.exit(f"Refusing to delete {a.video_id} ({title}) without --yes.")
    r = _request_raw(cfg, "DELETE", f"{YT_API}/videos", params=[("id", a.video_id)])
    if r.status_code not in (200, 204):
        _scope_wall_hint(f"{YT_API}/videos", r)
        sys.exit(f"ERROR: HTTP {r.status_code} {r.text[:300]}")
    print(f"Deleted {a.video_id} ({title}).")


def main():
    p = argparse.ArgumentParser(add_help=False)
    sub = p.add_subparsers(dest="cmd")

    s = sub.add_parser("auth", description=(
        "Authorize this container against Google. Default = FULL Workspace access (Gmail, Drive, "
        "Sheets, Docs, Slides, Calendar, Tasks, Chat incl. spaces/memberships/delete). "
        "Admin SDK scopes (admin.directory.*) are NOT in any tier by default; add them with --admin (one "
        "consent, no second browser trip) to manage Google Groups / distribution lists. "
        "Already authorized and just missing one capability? Do NOT re-run a bare `auth` -- use "
        "`adom-google scopes --require <scope> --auto-widen`, which preserves what you already "
        "hold. See granted-vs-requested with `adom-google scopes`."))
    s.add_argument("--manual", action="store_true", help="fallback when the gateway is unreachable: desktop-client copy/paste flow (finish with `auth-code '<code>'`)"); s.add_argument("--safe", action="store_true", help="advanced: request the NARROW create-only scope set (no delete-all); default is FULL"); s.add_argument("--full", action="store_true", help="Connector: request the FULL set incl. Gmail-read + all Drive (works for whitelisted testers now, everyone once CASA clears). No-op for the work client (already full)."); s.add_argument("--url-file", dest="url_file", help="also write the consent URL to this file (one clean line, for tooling). This process is still the listener: keep it running until Allow is clicked, or the link answers 'Session Expired'"); s.add_argument("--youtube", action="store_true", help="ADD YouTube (youtube + youtube.upload) to this account, keeping everything it holds: widened in place, or a second YouTube grant on the same account when it holds drive.file"); s.add_argument("--rebind", action="store_true", help="with --youtube: (re)make this account's separate YouTube grant, e.g. to pick a different channel or Brand Account; nothing else changes"); s.add_argument("--admin", action="store_true", help="ALSO request the Workspace ADMIN bundle (admin.directory.group + .group.member + .user.readonly + apps.groups.settings) so ONE consent covers Google Groups / distribution lists. Only a Workspace admin can grant it."); s.add_argument("--add-scope", dest="add_scopes", action="append", help="widen the scope set (repeatable; full URL or short tail like chat.spaces)"); s.add_argument("--json", action="store_true", help="AI/tooling mode: all guidance (consent URL, waiting notes) goes to STDERR; stdout carries exactly ONE JSON line on success ({\"ok\":true,\"authorized\":true,\"scopes\":[...]}) and the exit code is 0. auth already blocks until Allow is clicked, so this replaces polling `status`."); s.add_argument("--wait", action="store_true", help="accepted no-op: auth ALWAYS waits for the click (up to ~60 min); here so `auth --wait --json` reads naturally"); s.set_defaults(fn=cmd_auth)
    s = sub.add_parser("scopes"); s.add_argument("--json", action="store_true"); s.add_argument("--require", nargs="+", help="scopes that MUST be granted (full URL or short tail); exit 2 + print the fix when short"); s.add_argument("--auto-widen", dest="auto_widen", action="store_true", help="with --require: re-run auth with the union instead of exiting"); s.add_argument("--url-file", dest="url_file", help="with --auto-widen: also write the consent URL here"); s.set_defaults(fn=cmd_scopes)
    s = sub.add_parser("auth-code"); s.add_argument("code"); s.set_defaults(fn=cmd_auth_code)
    s = sub.add_parser("init"); s.add_argument("client_id"); s.add_argument("client_secret"); s.set_defaults(fn=cmd_init)
    pv = sub.add_parser("provider"); pvs = pv.add_subparsers(dest="sub")
    x = pvs.add_parser("set")
    x.add_argument("--gateway"); x.add_argument("--ws")
    x.add_argument("--client-id", dest="client_id"); x.add_argument("--client-secret", dest="client_secret")
    x.add_argument("--app"); x.set_defaults(fn=cmd_provider_set)
    x = pvs.add_parser("show"); x.set_defaults(fn=cmd_provider_show)
    x = pvs.add_parser("discover", help="load the provider from your wiki org's settings (adom-wiki settings get <org> google-oauth)"); x.add_argument("--org", help="pick this org when you belong to several"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_provider_discover)
    s = sub.add_parser("status"); s.add_argument("--json", action="store_true", help="one JSON object with authorized:true|false (+ account, mode, scopes, gateway); exit 1 when NOT authorized"); s.set_defaults(fn=cmd_status)
    s = sub.add_parser("accounts"); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_accounts)
    s = sub.add_parser("setup"); s.set_defaults(fn=cmd_setup)
    s = sub.add_parser("connect-personal"); s.add_argument("--as", dest="as_name", default="personal", help="profile name to create (default: personal), e.g. a second personal Google account. YouTube does not need one: `--account <profile> auth --youtube` adds it"); s.set_defaults(fn=cmd_connect_personal)

    ob = sub.add_parser("onboard"); ob.add_argument("--org"); ob.add_argument("--json", action="store_true")
    ob.set_defaults(fn=cmd_onboard)
    obx = ob.add_subparsers(dest="sub")
    y = obx.add_parser("finish")
    y.add_argument("--org", required=True)
    y.add_argument("--client-id", dest="client_id", required=True)
    y.add_argument("--client-secret", dest="client_secret", help="omit or '-' to read from stdin")
    y.add_argument("--gateway", help="override the shared callback gateway (advanced)")
    y.add_argument("--domain", help="your Google Workspace domain(s), comma separated (recorded in org settings)")
    y.add_argument("--relay", action="store_true", help="old single-box mode: keep the secret 0600 on THIS box only (teammates cannot use it)")
    y.set_defaults(fn=cmd_onboard_finish)

    yt = sub.add_parser("youtube", help="YouTube: upload a video (resumable), list, channels")
    yts = yt.add_subparsers(dest="sub")
    u = yts.add_parser("upload", help="resumable upload; prints the watch URL and the privacy YouTube actually applied")
    u.add_argument("file"); u.add_argument("--title"); u.add_argument("--description", default="")
    u.add_argument("--privacy", choices=["private", "unlisted", "public"], default="unlisted")
    u.add_argument("--tags", help="comma separated"); u.add_argument("--category", help="YouTube categoryId (default 22, People & Blogs)")
    u.add_argument("--playlist", metavar="PLAYLIST_ID"); u.add_argument("--thumbnail", metavar="PATH")
    u.add_argument("--chunk-mb", dest="chunk_mb", type=int, default=8)
    u.add_argument("--quiet", action="store_true", help="no progress line"); u.add_argument("--json", action="store_true")
    u.set_defaults(fn=cmd_youtube_upload)
    u = yts.add_parser("channels"); u.add_argument("--json", action="store_true"); u.set_defaults(fn=cmd_youtube_channels)
    u = yts.add_parser("list"); u.add_argument("--max", type=int, default=10); u.add_argument("--json", action="store_true"); u.set_defaults(fn=cmd_youtube_list)
    u = yts.add_parser("delete"); u.add_argument("video_id"); u.add_argument("--yes", action="store_true"); u.set_defaults(fn=cmd_youtube_delete)

    og = sub.add_parser("org", help="set adom-google up ONCE for a whole wiki org (gateway holds the secret; members auto-discover)")
    ogs = og.add_subparsers(dest="sub")
    z = ogs.add_parser("register", help="hand your org's Google OAuth client to the gateway + publish the non-secret half to <org>/org-settings")
    z.add_argument("--org", required=True); z.add_argument("--client-id", dest="client_id", required=True)
    z.add_argument("--client-secret", dest="client_secret", help="omit or '-' to read it from stdin (keeps it out of shell history)")
    z.add_argument("--domain", help="Google Workspace domain(s), comma separated"); z.add_argument("--gateway")
    z.set_defaults(fn=cmd_org_register)
    z = ogs.add_parser("status"); z.add_argument("--org", required=True); z.add_argument("--gateway"); z.add_argument("--json", action="store_true"); z.set_defaults(fn=cmd_org_status)
    z = ogs.add_parser("unregister"); z.add_argument("--org", required=True); z.add_argument("--gateway"); z.set_defaults(fn=cmd_org_unregister)

    g = sub.add_parser("gmail"); gs = g.add_subparsers(dest="sub")
    x = gs.add_parser("attachments"); x.add_argument("message_id"); x.set_defaults(fn=cmd_gmail_attachments)
    x = gs.add_parser("read"); x.add_argument("message_id"); x.add_argument("attachment_id"); x.add_argument("-o", "--out"); x.set_defaults(fn=cmd_gmail_read)
    x = gs.add_parser("ics"); x.add_argument("message_id"); x.set_defaults(fn=cmd_gmail_ics)

    c = sub.add_parser("contacts"); cs = c.add_subparsers(dest="sub")
    x = cs.add_parser("create")
    x.add_argument("--name"); x.add_argument("--org"); x.add_argument("--title")
    x.add_argument("--email", action="append"); x.add_argument("--phone", action="append")
    x.add_argument("--notes"); x.add_argument("--json", action="store_true")
    x.add_argument("--dry-run", dest="dry_run", action="store_true", help="print the People API payload without sending")
    x.set_defaults(fn=cmd_contacts_create)
    x = cs.add_parser("list"); x.add_argument("--limit", type=int, default=50); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_contacts_list)
    x = cs.add_parser("search"); x.add_argument("query"); x.add_argument("-v", "--verbose", action="store_true"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_contacts_search)

    ch = sub.add_parser("chat"); chx = ch.add_subparsers(dest="sub")
    x = chx.add_parser("spaces"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_spaces)
    x = chx.add_parser("dm", help="resolve the 1:1 DM space with a person (email, or a name looked up in your Workspace domain directory)"); x.add_argument("email", metavar="email|name", help="an email, or a name resolved ONLY through your own Workspace domain directory: a unique exact first-name / full-name / email-local-part match; partial or ambiguous matches are an ERROR listing the candidates"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_dm)
    x = chx.add_parser("send"); x.add_argument("--to", required=True, help="spaces/XXX id OR an email (auto-resolves the DM)"); x.add_argument("text", nargs="?", default="", help="message text, or '-' for stdin, or '@file' (optional when --attach is used)"); x.add_argument("--thread", help="threadKey for a threaded reply"); x.add_argument("--attach", action="append", metavar="PATH", help="attach a local file (image/video/PDF/any); repeatable"); x.add_argument("--no-agent-marker", action="store_true", help="don't stamp clientAssignedMessageId=client-agent-*"); x.add_argument("--json", action="store_true", help="print the created message as JSON (name, createTime, text, space, spaceUri, posted)"); x.set_defaults(fn=cmd_chat_send)
    x = chx.add_parser("read"); x.add_argument("--from", dest="frm", required=True, help="spaces/XXX id OR an email"); x.add_argument("--limit", type=int, default=20); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_chat_read)

    # Calendar (issue #662)
    pp = sub.add_parser("people", help="Workspace domain directory: who is <name>, their email, title, Chat DM space"); ppx = pp.add_subparsers(dest="sub")
    x = ppx.add_parser("find", help="search YOUR Workspace domain directory by name or email (domain accounts only)"); x.add_argument("query", help="a first/last/full name, email local part, or email"); x.add_argument("--dm", action="store_true", help="also resolve each match's existing 1:1 Chat DM space (first 10 matches)"); x.add_argument("--limit", type=_limit_arg(1), default=50, help="max matches to show (default 50)"); x.add_argument("--json", action="store_true", help="{status, data:{query, domain, count, exact, people[]}, hints[]} envelope"); x.set_defaults(fn=cmd_people_find)
    x = ppx.add_parser("list", help="every account in YOUR Workspace domain directory (paginated)"); x.add_argument("--limit", type=_limit_arg(0), default=0, help="max people to show (default 0 = all)"); x.add_argument("--json", action="store_true", help="{status, data:{domain, count, people[]}, hints[]} envelope"); x.set_defaults(fn=cmd_people_list)

    cal = sub.add_parser("calendar", help="Google Calendar: list/create events, list calendars"); cax = cal.add_subparsers(dest="sub")
    x = cax.add_parser("list", help="upcoming events"); x.add_argument("--cal", default="primary"); x.add_argument("--max", type=int, default=10); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_calendar_list)
    x = cax.add_parser("create", help="create an event"); x.add_argument("--summary", required=True); x.add_argument("--start", help="RFC3339, e.g. 2026-08-20T14:00:00-05:00"); x.add_argument("--end", help="RFC3339"); x.add_argument("--location"); x.add_argument("--description"); x.add_argument("--attendees", help="comma-separated emails"); x.add_argument("--cal", default="primary"); x.add_argument("--send", action="store_true", help="email invites to attendees"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_calendar_create)
    x = cax.add_parser("calendars", help="list your calendars"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_calendar_calendars)

    # Drive
    dr = sub.add_parser("drive", help="Google Drive: list/search + upload files"); drx = dr.add_subparsers(dest="sub")
    x = drx.add_parser("list", help="list/search files"); x.add_argument("--query", help="Drive query, e.g. \"name contains 'invoice'\""); x.add_argument("--limit", type=int, default=20); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_drive_list)
    x = drx.add_parser("upload", help="upload a local file"); x.add_argument("path"); x.add_argument("--name"); x.add_argument("--mime"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_drive_upload)

    # Sheets / Docs / Slides (create the file, then edit via `api` batchUpdate)
    sh = sub.add_parser("sheets", help="Google Sheets"); shx = sh.add_subparsers(dest="sub")
    x = shx.add_parser("create", help="create a spreadsheet"); x.add_argument("--title", required=True); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_sheets_create)
    dc = sub.add_parser("docs", help="Google Docs"); dcx = dc.add_subparsers(dest="sub")
    x = dcx.add_parser("create", help="create a document"); x.add_argument("--title", required=True); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_docs_create)
    sl = sub.add_parser("slides", help="Google Slides"); slx = sl.add_subparsers(dest="sub")
    x = slx.add_parser("create", help="create a presentation"); x.add_argument("--title", required=True); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_slides_create)

    # Tasks
    tk = sub.add_parser("tasks", help="Google Tasks: list/add"); tkx = tk.add_subparsers(dest="sub")
    x = tkx.add_parser("list", help="list tasks"); x.add_argument("--list", default="@default"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_tasks_list)
    x = tkx.add_parser("add", help="add a task"); x.add_argument("--title", required=True); x.add_argument("--notes"); x.add_argument("--list", default="@default"); x.add_argument("--json", action="store_true"); x.set_defaults(fn=cmd_tasks_add)

    # Generic passthrough — hit ANY Google API with the stored token.
    x = sub.add_parser("api")
    x.add_argument("url", help="full URL or host/path (https:// assumed)")
    x.add_argument("-X", "--method", default="GET")
    x.add_argument("-d", "--data", help="JSON body string, or @file")
    x.add_argument("-q", "--query", action="append", help="key=value query param (repeatable)")
    x.add_argument("--raw", action="store_true", help="print raw bytes (don't pretty-print JSON)")
    x.add_argument("--upload-file", dest="upload_file", help="send a file's raw bytes as the body (binary uploads: Drive media, YouTube resumable PUT)")
    x.add_argument("--content-type", dest="content_type", help="override Content-Type (e.g. video/mp4)")
    x.set_defaults(fn=cmd_api)

    # Dashboard: the Hydrogen Dock Bar card (issue #10). Loopback only, read only.
    x = sub.add_parser("dashboard", help="serve the Google accounts + permissions dashboard on 127.0.0.1 (the Dock Bar card)")
    x.add_argument("--print-url", dest="print_url", action="store_true", help="print EXACTLY the URL on stdout (what the dock awaits); everything else goes to stderr")
    x.add_argument("--port", type=int, help=f"loopback port (default {DASH_PORT})")
    x.add_argument("--json", action="store_true", help="one JSON object: {ok, url, port, pid, version, reused}")
    x.add_argument("--stop", action="store_true", help="stop the dashboard running on the port")
    x.add_argument("--foreground", action="store_true", help="run the server in this terminal instead of in the background (debugging)")
    x.add_argument("--probe-account", dest="probe_account", action="store_true", help=argparse.SUPPRESS)
    x.set_defaults(fn=cmd_dashboard)

    sub.add_parser("help")

    if len(sys.argv) == 1 or sys.argv[1] in ("help", "-h", "--help"):
        print(HELP); return
    args = p.parse_args()
    if not hasattr(args, "fn"):
        print(HELP); return
    args.fn(args)


if __name__ == "__main__":
    main()
