# Models the BROWSER handoff the Antigravity agent performs, with main's helper.
import os, shlex, subprocess, sys, webbrowser
marker = "__T3_ANTIGRAVITY_AUTH_URL__"
src = ('process.stderr.on("error",()=>process.exit(0)).write('
       f'"{marker}"+JSON.stringify(process.argv[1])+"\\n",()=>process.exit(0))')
node = sys.argv[1]
q = lambda v: "'" + v.replace("'", "'\"'\"'") + "'"
os.environ["BROWSER"] = " ".join(q(a) for a in [node, "-e", src, "--", "%s"])
url = "https://accounts.google.com/o/oauth2/v2/auth?state=s&redirect_uri=http://127.0.0.1:5555/&response_type=code"
mode = sys.argv[2]
if mode == "posix-webbrowser":
    print("webbrowser.open ->", webbrowser.open(url), file=sys.stderr)
else:
    # Windows: webbrowser runs Popen(cmdline) with close_fds=True and no std handles,
    # so the helper does not inherit the agent's stderr pipe; Node then writes to a black hole.
    argv = shlex.split(os.environ["BROWSER"]); argv = [a.replace("%s", url) for a in argv]
    rc = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
    print("helper exit", rc, "(webbrowser.open would return", rc == 0, ")", file=sys.stderr)
