"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, {
  resolveCLIConfig: () => resolveCLIConfig
});
module.exports = __toCommonJS(program_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_daemon = require("./daemon");
var import_watchdog = require("../mcp/watchdog");
var import_browserFactory = require("../mcp/browserFactory");
var configUtils = __toESM(require("../mcp/config"));
var import_registry = require("../cli-client/registry");
var import_utilsBundle = require("../../utilsBundle");
import_utilsBundle.program.argument("[session-name]", "name of the session to create or connect to", "default").option("--headed", "run in headed mode (non-headless)").option("--extension", "run with the extension").option("--browser <name>", "browser to use (chromium, chrome, firefox, webkit)").option("--persistent", "use a persistent browser context").option("--profile <path>", "path to the user data dir").option("--config <path>", "path to the config file").option("--attach <name-or-endpoint>", "attach to a running Playwright browser by name or endpoint").action(async (sessionName, options) => {
  (0, import_watchdog.setupExitWatchdog)();
  const clientInfo = (0, import_registry.createClientInfo)();
  const mcpConfig = await resolveCLIConfig(clientInfo, sessionName, options);
  const clientInfoEx = {
    cwd: process.cwd(),
    sessionName,
    workspaceDir: clientInfo.workspaceDir
  };
  try {
    const { browser, browserInfo } = await (0, import_browserFactory.createBrowserWithInfo)(mcpConfig, clientInfoEx);
    const browserContext = mcpConfig.browser.isolated ? await browser.newContext(mcpConfig.browser.contextOptions) : browser.contexts()[0];
    if (!browserContext)
      throw new Error("Error: unable to connect to a browser that does not have any contexts");
    const persistent = options.persistent || options.profile || mcpConfig.browser.userDataDir ? true : void 0;
    const socketPath = await (0, import_daemon.startCliDaemonServer)(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, { persistent, exitOnClose: true });
    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>");
  }
});
void import_utilsBundle.program.parseAsync();
function defaultConfigFile() {
  return import_path.default.resolve(".playwright", "cli.config.json");
}
async function resolveCLIConfig(clientInfo, sessionName, options) {
  const config = options.config ? import_path.default.resolve(options.config) : void 0;
  try {
    if (!config && import_fs.default.existsSync(defaultConfigFile()))
      options.config = defaultConfigFile();
  } catch {
  }
  const daemonOverrides = configUtils.configFromCLIOptions({
    config: options.config,
    browser: options.browser,
    headless: options.headed ? false : void 0,
    extension: options.extension,
    userDataDir: options.profile,
    snapshotMode: "full"
  });
  daemonOverrides.browser.remoteEndpoint = options.attach;
  const envOverrides = configUtils.configFromEnv();
  const configFile = envOverrides.configFile ?? daemonOverrides.configFile;
  const configInFile = await configUtils.loadConfig(configFile);
  let result = configUtils.mergeConfig(configUtils.defaultConfig, {
    browser: {
      launchOptions: {
        headless: true
      }
    }
  });
  result = configUtils.mergeConfig(result, configInFile);
  result = configUtils.mergeConfig(result, daemonOverrides);
  result = configUtils.mergeConfig(result, envOverrides);
  if (result.browser.isolated === void 0)
    result.browser.isolated = !options.profile && !options.persistent && !result.browser.userDataDir && !result.browser.remoteEndpoint && !result.extension;
  if (!result.extension && !result.browser.isolated && !result.browser.userDataDir && !result.browser.remoteEndpoint) {
    const browserToken = result.browser.launchOptions?.channel ?? result.browser?.browserName;
    const userDataDir = import_path.default.resolve(clientInfo.daemonProfilesDir, `ud-${sessionName}-${browserToken}`);
    result.browser.userDataDir = userDataDir;
  }
  result.configFile = configFile;
  result.skillMode = true;
  if (result.browser.launchOptions.headless !== false)
    result.browser.contextOptions.viewport ??= { width: 1280, height: 720 };
  await configUtils.validateConfig(result);
  return result;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  resolveCLIConfig
});
