#!/usr/bin/env python3
"""session_probe.py — is the Higgsfield browser session actually logged in?

THE FAILURE THIS EXISTS FOR. A logged-out profile does not announce itself. Every
draw refuses, the refusals arrive one every few minutes across a shared single-slot
lane, and the whole thing reads as a bad run of moderation — which is a ~50%-per-draw
coin flip, so a run of refusals is exactly what moderation looks like. The two have
opposite remedies: moderation wants another draw, a dead session wants a human to log
in, and no amount of redrawing will ever fix the second one.

It is also easy to be confidently wrong about which profile is live. On this machine
BOTH candidate profiles carried unexpired Clerk cookies for higgsfield.ai — and both
were logged out. Cookie inspection cannot answer this; only asking the provider can.

HOW IT ASKS, and why it costs nothing: the engine's `wallet` action is a read-only
authenticated probe that submits no media and creates no job. It calls
`ensure_session_auth` first, which is the exact check every submit makes, so a pass
here means a submit will authenticate too. The adapter also attempts a Chrome cookie
re-seed on the way, so a session that has merely gone stale may be REPAIRED by
running this rather than merely diagnosed.

Three answers, and the third is not the second:

  0  authenticated             — the lane can render
  4  NOT authenticated         — a human must log into higgsfield.ai in Chrome
  7  could not probe           — no engine, a timeout, an unreadable reply. This
                                 proves NOTHING and must never be reported as either
                                 of the other two. A driver may proceed on a 7 (and
                                 discover the truth on its first submit); it must not
                                 proceed on a 4.

Usage:  session_probe.py [--engine <run.sh>] [--timeout 240] [--json]
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys

OK, DEAD, UNKNOWN = 0, 4, 7

# Phrases the adapter prints when it has established the session is not usable. These
# are its own words on a real dead session, not guesses:
#   [higgs-adapter] dead Higgsfield session; attempting Chrome cookie re-seed
#   [higgs-adapter] re-seed from Chrome: still unauthenticated
#   Higgsfield session not authenticated: the in-page Clerk token could not be minted
DEAD_MARKERS = (
    "session not authenticated",
    "still unauthenticated",
    "dead higgsfield session",
    "unauthenticated",
)

ADVICE = (
    "Log into higgsfield.ai in Chrome, then re-seed the automation profile "
    "(higgs-cloak: `python drive_higgsfield.py` or `higgs_auth_keepalive.py`). "
    "No amount of redrawing fixes this — a dead session refuses every draw, which is "
    "why it reads as moderation."
)


def default_engine() -> str:
    here = os.path.dirname(os.path.abspath(__file__))
    main = os.environ.get("VCLAW_MAIN") or os.path.abspath(os.path.join(here, "..", "..", ".."))
    override = os.environ.get("VCLAW_SEEDANCE_DIRECT_ADAPTER")
    if override:
        return os.path.abspath(os.path.expanduser(override))
    return os.path.join(main, "engines", "seedance-direct", "run.sh")


def probe(engine: str, timeout: int = 240) -> tuple[int, str]:
    if not os.access(engine, os.X_OK):
        return UNKNOWN, f"no engine at {engine} (run engines/seedance-direct/bootstrap.sh)"
    try:
        proc = subprocess.run([engine], input=json.dumps({"action": "wallet"}),
                              capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        return UNKNOWN, f"the wallet probe did not answer within {timeout}s"
    except OSError as exc:
        return UNKNOWN, f"could not run the engine: {exc}"

    out = proc.stdout.strip()
    if out:
        try:
            wallet = json.loads(out[out.index("{"):])
            # A parsed wallet means ensure_session_auth() passed, which is the same
            # check every submit makes.
            return OK, f"authenticated (wallet keys: {', '.join(sorted(wallet)[:6]) or 'none'})"
        except (ValueError, json.JSONDecodeError):
            pass

    blob = (proc.stdout + proc.stderr).lower()
    if any(marker in blob for marker in DEAD_MARKERS):
        return DEAD, "the browser profile is NOT logged in to higgsfield.ai"
    return UNKNOWN, f"unreadable reply from the engine: {(proc.stdout + proc.stderr).strip()[-300:]}"


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--engine", default=None)
    ap.add_argument("--timeout", type=int, default=240)
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    engine = args.engine or default_engine()
    code, detail = probe(engine, args.timeout)
    profile = os.environ.get("HIGGS_VCLAW_PROFILE") or os.path.join(
        os.path.dirname(engine), ".cloak-profile")

    if args.json:
        print(json.dumps({"authenticated": code == OK, "code": code, "detail": detail,
                          "engine": engine, "profile": profile}, indent=2))
    elif code == OK:
        print(f"session_probe: OK — {detail}")
    elif code == DEAD:
        print(f"session_probe: NOT LOGGED IN — {detail}", file=sys.stderr)
        print(f"  profile: {profile}", file=sys.stderr)
        print(f"  {ADVICE}", file=sys.stderr)
    else:
        print(f"session_probe: UNKNOWN — {detail}", file=sys.stderr)
        print("  This proves nothing either way; it is not a dead session.", file=sys.stderr)
    raise SystemExit(code)


if __name__ == "__main__":
    main()
