import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import { getPlaywriterProfileDir } from "../../../config/index.js";
import { logger } from "../../../logger.js";
let _dataDir = null;
function getDataDir() {
    _dataDir ??= getPlaywriterProfileDir();
    return _dataDir;
}
function findChromePath() {
    if (process.platform === "darwin") {
        return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
    }
    const candidates = [
        `${process.env.PROGRAMFILES ?? "C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,
        `${process.env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,
        `${process.env.LOCALAPPDATA ?? ""}\\Google\\Chrome\\Application\\chrome.exe`,
    ];
    for (const p of candidates) {
        if (fs.existsSync(p))
            return p;
    }
    return candidates[0];
}
let _chromePath = null;
function getChromePath() {
    _chromePath ??= findChromePath();
    return _chromePath;
}
/**
 * Kill any Chrome processes launched with `--remote-debugging-port=9222`
 * (the Playwright CDP profile). Safe to call when none are running.
 */
export function killPlaywrightProfileCdpChrome() {
    try {
        execFileSync("pkill", ["-f", "--", "--remote-debugging-port=9222"], { stdio: "ignore" });
    }
    catch {
        // pkill exits non-zero when no matching process is found — expected.
    }
}
/**
 * Kill only Chrome processes running with the dedicated Playwriter data dir.
 * Does NOT affect the user's normal Chrome windows.
 */
function killPlaywriterChrome() {
    try {
        execFileSync("pkill", ["-f", "--", `--user-data-dir=${getDataDir()}`], { stdio: "ignore" });
    }
    catch {
        // No matching process — expected.
    }
}
/**
 * Launch Chrome with a dedicated user-data-dir for Playwriter.
 * The External Extensions JSON must already be in place inside that dir.
 */
export function launchPlaywriterProfileChrome() {
    const chromePath = getChromePath();
    if (!fs.existsSync(chromePath)) {
        logger.warn(`Chrome not found at ${chromePath}`);
        return;
    }
    const flags = [
        `--user-data-dir=${getDataDir()}`,
        "--no-first-run",
        "--no-default-browser-check",
        "--profile-directory=Default",
    ];
    const child = spawn(chromePath, flags, {
        detached: true,
        stdio: "ignore",
    });
    child.on("error", (err) => {
        logger.warn(`Playwriter Chrome process error: ${err.message}`);
    });
    child.unref();
    logger.system("Playwriter: launched dedicated Chrome instance");
}
/**
 * Check whether a Chrome process with the Playwriter data dir is running.
 */
export function isPlaywriterProfileChromeRunning() {
    try {
        execFileSync("pgrep", ["-f", `--user-data-dir=${getDataDir()}`], { stdio: "ignore" });
        return true;
    }
    catch {
        return false;
    }
}
function restartChromeForPlaywriter() {
    killPlaywriterChrome();
    launchPlaywriterProfileChrome();
}
/**
 * Ensure Chrome is running (Playwriter mode). On the first Playwriter tool call
 * of each turn we force a clean restart to reset stale extension connections;
 * later calls in the same turn only ensure Chrome is up.
 *
 * Returns true when a connection reset was performed for this turn.
 */
export function ensurePlaywriterChrome(didResetConnectionsThisTurn) {
    if (!didResetConnectionsThisTurn) {
        logger.system("Resetting Playwriter Chrome before session");
        restartChromeForPlaywriter();
        return true;
    }
    if (!isPlaywriterProfileChromeRunning()) {
        logger.system("Playwriter Chrome not running — launching");
        launchPlaywriterProfileChrome();
    }
    return false;
}
//# sourceMappingURL=session-browser-policy.js.map