// Scratch for #9624 (never committed): runs T3's real sign-in env through a Windows-style BROWSER handoff.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { spawn } from "node:child_process";
import {
  buildAntigravityAcpSpawnInput,
  prepareAntigravityProfile,
  serveAntigravityAuthorizationUrlSink,
} from "./src/provider/antigravityAuthSupport.ts";

const url =
  "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=synthetic";
const python = String.raw`
import os, shlex, subprocess, sys
# CPython webbrowser.GenericBrowser on Windows: Popen(cmdline), no std handles inherited.
argv = [a.replace("%s", sys.argv[1]) for a in shlex.split(os.environ["BROWSER"])]
rc = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
print("helper exit", rc)
`;
const runPython = (env: NodeJS.ProcessEnv) =>
  new Promise<{ stdout: string; stderr: string }>((resolve) => {
    const child = spawn("python3", ["-I", "-c", python, url], { env });
    let stdout = "";
    let stderr = "";
    child.stdout.on("data", (d) => (stdout += d));
    child.stderr.on("data", (d) => (stderr += d));
    child.on("close", () => resolve({ stdout, stderr }));
  });
await Effect.runPromise(
  Effect.scoped(
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      const profile = yield* prepareAntigravityProfile({ profileDirectory: yield* fs.makeTempDirectoryScoped() });
      const received: string[] = [];
      const sink = yield* serveAntigravityAuthorizationUrlSink((u) => Effect.sync(() => void received.push(u)));
      const { env } = buildAntigravityAcpSpawnInput({
        installation: { executablePath: "/unused", harnessPath: "/unused" },
        profile, cwd: process.cwd(), authorizationUrlSink: sink,
      });
      console.log("sign-in env T3_ANTIGRAVITY_AUTH_SINK set:", typeof env.T3_ANTIGRAVITY_AUTH_SINK === "string");
      const started = Date.now();
      const run = yield* Effect.promise(() => runPython(env as NodeJS.ProcessEnv));
      console.log("python:", run.stdout.trim(), `(${Date.now() - started} ms)`, "| agent stderr bytes:", run.stderr.length);
      console.log("onAuthorizationUrl received:", received.length === 1 && received[0] === url ? "the URL" : JSON.stringify(received));
    }),
  ).pipe(Effect.provide(NodeServices.layer)),
);
