import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { getPlaywrightProfileDir } from "../config/index.js";
function findChromePath() {
    if (process.platform === "darwin") {
        return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
    }
    const candidates = [
        path.join(process.env.PROGRAMFILES ?? "C:\\Program Files", "Google", "Chrome", "Application", "chrome.exe"),
        path.join(process.env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)", "Google", "Chrome", "Application", "chrome.exe"),
        path.join(process.env.LOCALAPPDATA ?? "", "Google", "Chrome", "Application", "chrome.exe"),
    ];
    for (const candidate of candidates) {
        if (fs.existsSync(candidate))
            return candidate;
    }
    return candidates[0];
}
function createBrowserLauncherScript() {
    const profileDir = getPlaywrightProfileDir();
    const tmpDir = os.tmpdir();
    const scriptPath = path.join(tmpDir, `gh-browser-${process.pid}.sh`);
    if (process.platform === "darwin") {
        const chromePath = "/Applications/Google Chrome.app";
        const lines = [
            "#!/bin/bash",
            `open -na "${chromePath}" --args --user-data-dir="${profileDir}" --profile-directory=Default "$1"`,
        ];
        fs.writeFileSync(scriptPath, lines.join("\n") + "\n", { mode: 0o755 });
    }
    else {
        const chromePath = findChromePath();
        const lines = [
            "#!/bin/bash",
            `"${chromePath}" --user-data-dir="${profileDir}" --profile-directory=Default "$1" &`,
        ];
        fs.writeFileSync(scriptPath, lines.join("\n") + "\n", { mode: 0o755 });
    }
    return scriptPath;
}
/**
 * Run `gh auth login --web` with GH_BROWSER set to a wrapper script that
 * opens Chrome using the Playwright profile directory. This ensures the
 * GitHub OAuth session ends up in the same Chrome profile that Playwright
 * MCP uses at runtime.
 */
export function spawnGhAuthLoginWithBrowser() {
    const scriptPath = createBrowserLauncherScript();
    try {
        const ghConfigDir = path.join(os.homedir(), ".config", "gh");
        fs.mkdirSync(ghConfigDir, { recursive: true });
        const result = spawnSync("gh", ["auth", "login", "--web"], {
            stdio: "inherit",
            windowsHide: true,
            env: { ...process.env, GH_BROWSER: scriptPath },
        });
        return { status: result.status };
    }
    finally {
        try {
            fs.unlinkSync(scriptPath);
        }
        catch {
            // best-effort cleanup
        }
    }
}
//# sourceMappingURL=gh-auth-browser.js.map