import { startPlayWriterCDPRelayServer } from "playwriter";
import { existsSync, mkdirSync, writeFileSync, unlinkSync } from "node:fs";
import { execSync } from "node:child_process";
import { homedir } from "node:os";
import { join, dirname } from "node:path";
const EXTENSION_ID = "jfeammnjpkecdekppnclgkkffahnhfhe";
const RELAY_PROTOCOL_VERSION = 1;
function getRelayInfoPath() {
    return process.env.RELAY_INFO_PATH
        ?? join(homedir(), ".visionclaw", "profiles", "default", ".playwriter-relay-info.json");
}
function hasExtensionConfig() {
    const systemExtDir = join(homedir(), "Library", "Application Support", "Google", "Chrome", "External Extensions");
    return existsSync(join(systemExtDir, `${EXTENSION_ID}.json`));
}
function hasConflictingPolicyInstall() {
    if (process.platform !== "darwin")
        return false;
    try {
        const plistPath = "/Library/Managed Preferences/com.google.Chrome.plist";
        if (!existsSync(plistPath))
            return false;
        const content = execSync(`/usr/libexec/PlistBuddy -c "Print ExtensionInstallForcelist" "${plistPath}" 2>/dev/null`, { encoding: "utf-8", timeout: 5000 });
        return content.includes(EXTENSION_ID);
    }
    catch {
        return false;
    }
}
function writeRelayInfo(host, port) {
    const infoPath = getRelayInfoPath();
    mkdirSync(dirname(infoPath), { recursive: true });
    writeFileSync(infoPath, JSON.stringify({
        visionclawVersion: process.env.VISIONCLAW_VERSION ?? "unknown",
        relayProtocolVersion: RELAY_PROTOCOL_VERSION,
        relayEntryPath: process.argv[1] ?? "unknown",
        host,
        port,
        pid: process.pid,
        startedAt: new Date().toISOString(),
    }, null, 2));
}
function removeRelayInfo() {
    try {
        unlinkSync(getRelayInfoPath());
    }
    catch {
        // File may not exist
    }
}
async function main() {
    if (!hasExtensionConfig()) {
        console.error("Playwriter extension External Extensions JSON not found. Run extension install first.");
        process.exit(1);
    }
    if (hasConflictingPolicyInstall()) {
        console.error("Conflicting Playwriter enterprise policy detected. Run legacy cleanup first.");
        process.exit(1);
    }
    const host = process.env.PLAYWRITER_RELAY_HOST ?? "127.0.0.1";
    const port = Number.parseInt(process.env.PLAYWRITER_RELAY_PORT ?? "19988", 10);
    if (!Number.isInteger(port) || port < 1 || port > 65535) {
        console.error(`Invalid PLAYWRITER_RELAY_PORT: ${process.env.PLAYWRITER_RELAY_PORT}`);
        process.exit(1);
    }
    const relayLogger = {
        log: (...args) => console.log(new Date().toISOString(), "[relay]", ...args),
        error: (...args) => console.error(new Date().toISOString(), "[relay]", ...args),
    };
    const relay = await startPlayWriterCDPRelayServer({ host, port, logger: relayLogger });
    writeRelayInfo(host, port);
    console.log(`Playwriter CDP relay listening on ${host}:${port}`);
    const shutdown = () => {
        console.log("Shutting down Playwriter relay...");
        removeRelayInfo();
        relay.close();
        process.exit(0);
    };
    process.on("SIGINT", shutdown);
    process.on("SIGTERM", shutdown);
}
main().catch((err) => {
    console.error("Fatal error starting Playwriter relay:", err);
    removeRelayInfo();
    process.exit(1);
});
//# sourceMappingURL=playwriter-relay.js.map