"use strict";

// dist/entry/playwriter-relay.js
var import_playwriter = require("playwriter");
var import_node_fs = require("node:fs");
var import_node_child_process = require("node:child_process");
var import_node_os = require("node:os");
var import_node_path = require("node:path");
var EXTENSION_ID = "jfeammnjpkecdekppnclgkkffahnhfhe";
var RELAY_PROTOCOL_VERSION = 1;
function getRelayInfoPath() {
  return process.env.RELAY_INFO_PATH ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".visionclaw", "profiles", "default", ".playwriter-relay-info.json");
}
function hasExtensionConfig() {
  const systemExtDir = (0, import_node_path.join)((0, import_node_os.homedir)(), "Library", "Application Support", "Google", "Chrome", "External Extensions");
  return (0, import_node_fs.existsSync)((0, import_node_path.join)(systemExtDir, `${EXTENSION_ID}.json`));
}
function hasConflictingPolicyInstall() {
  if (process.platform !== "darwin")
    return false;
  try {
    const plistPath = "/Library/Managed Preferences/com.google.Chrome.plist";
    if (!(0, import_node_fs.existsSync)(plistPath))
      return false;
    const content = (0, import_node_child_process.execSync)(`/usr/libexec/PlistBuddy -c "Print ExtensionInstallForcelist" "${plistPath}" 2>/dev/null`, { encoding: "utf-8", timeout: 5e3 });
    return content.includes(EXTENSION_ID);
  } catch {
    return false;
  }
}
function writeRelayInfo(host, port) {
  const infoPath = getRelayInfoPath();
  (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(infoPath), { recursive: true });
  (0, import_node_fs.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: (/* @__PURE__ */ new Date()).toISOString()
  }, null, 2));
}
function removeRelayInfo() {
  try {
    (0, import_node_fs.unlinkSync)(getRelayInfoPath());
  } catch {
  }
}
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((/* @__PURE__ */ new Date()).toISOString(), "[relay]", ...args),
    error: (...args) => console.error((/* @__PURE__ */ new Date()).toISOString(), "[relay]", ...args)
  };
  const relay = await (0, import_playwriter.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);
});
