"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var program_exports = {};
__export(program_exports, {
  decorateCLICommand: () => decorateCLICommand,
  resolveCLIConfig: () => resolveCLIConfig
});
module.exports = __toCommonJS(program_exports);
var import_fs = __toESM(require("fs"));
var import_daemon = require("./daemon");
var import_watchdog = require("../../mcp/browser/watchdog");
var import_browserContextFactory = require("../../mcp/browser/browserContextFactory");
var import_extensionContextFactory = require("../../mcp/extension/extensionContextFactory");
var import_config = require("../../mcp/browser/config");
function decorateCLICommand(command, version) {
  command.version(version).option("--daemon-session <path>", "path to the daemon config.").action(async (options) => {
    options.chromiumSandbox = options.chromiumSandbox === true ? void 0 : false;
    (0, import_watchdog.setupExitWatchdog)();
    const config = await resolveCLIConfig(options.daemonSession);
    const browserContextFactory = (0, import_browserContextFactory.contextFactory)(config);
    const extensionContextFactory = new import_extensionContextFactory.ExtensionContextFactory(config.browser.launchOptions.channel || "chrome", config.browser.userDataDir, config.browser.launchOptions.executablePath);
    const cf = config.extension ? extensionContextFactory : browserContextFactory;
    try {
      const socketPath = await (0, import_daemon.startMcpDaemonServer)(config, cf);
      console.log(`### Config`);
      console.log("```json");
      console.log(JSON.stringify(config, null, 2));
      console.log("```");
      console.log(`### Success
Daemon listening on ${socketPath}`);
      console.log("<EOF>");
    } catch (error) {
      const message = process.env.PWDEBUGIMPL ? error.stack || error.message : error.message;
      console.log(`### Error
${message}`);
      console.log("<EOF>");
    }
  });
}
async function resolveCLIConfig(daemonSession) {
  const sessionConfig = await import_fs.default.promises.readFile(daemonSession, "utf-8").then((data) => JSON.parse(data));
  const daemonOverrides = (0, import_config.configFromCLIOptions)({
    config: sessionConfig.cli.config,
    browser: sessionConfig.cli.browser,
    isolated: sessionConfig.cli.persistent === true ? false : void 0,
    headless: sessionConfig.cli.headed ? false : void 0,
    extension: sessionConfig.cli.extension,
    userDataDir: sessionConfig.cli.profile,
    outputMode: "file",
    snapshotMode: "full"
  });
  const envOverrides = (0, import_config.configFromEnv)();
  const configFile = envOverrides.configFile ?? daemonOverrides.configFile;
  const configInFile = await (0, import_config.loadConfig)(configFile);
  let result = (0, import_config.mergeConfig)(import_config.defaultConfig, {
    browser: {
      launchOptions: {
        headless: true
      },
      isolated: true
    }
  });
  result = (0, import_config.mergeConfig)(result, configInFile);
  result = (0, import_config.mergeConfig)(result, daemonOverrides);
  result = (0, import_config.mergeConfig)(result, envOverrides);
  if (!result.extension && !result.browser.userDataDir && sessionConfig.userDataDirPrefix) {
    const browserToken = result.browser.launchOptions?.channel ?? result.browser?.browserName;
    const userDataDir = `${sessionConfig.userDataDirPrefix}-${browserToken}`;
    result.browser.userDataDir = userDataDir;
  }
  result.configFile = configFile;
  result.sessionConfig = sessionConfig;
  result.skillMode = true;
  if (result.sessionConfig && result.browser.launchOptions.headless !== false)
    result.browser.contextOptions.viewport ??= { width: 1280, height: 720 };
  await (0, import_config.validateConfig)(result);
  return result;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  decorateCLICommand,
  resolveCLIConfig
});
