import { init_loader, loadConfig } from "../../config/loader.js";
import { loadPlaywrightCoreModule } from "../../browser/providers/playwright-doctor.js";
import { BrowserManager } from "../../browser/manager.js";
import { resolveBrowserBackendFromConfig } from "../../browser/backend-from-config.js";
import { createBrowserActionRegistry } from "../../browser/actions/registry.js";
import { runBrowserPipeline, validateBrowserPipeline } from "../../browser/pipeline/runner.js";
import { loadBrowserPipelineSource } from "../../browser/pipeline/source.js";
import "../../browser/index.js";
//#region src/cli/commands/browser-cli-helpers.ts
init_loader();
let _manager = null;
/** When set, `xopc browser open --headless` overrides config for this CLI invocation. */
let browserCliHeadlessOverride;
async function getManager() {
	if (_manager) return _manager;
	const config = await loadConfig();
	_manager = new BrowserManager({
		getHeadless: () => {
			if (typeof browserCliHeadlessOverride === "boolean") return browserCliHeadlessOverride;
			return config?.agents?.defaults?.browser?.headless === true;
		},
		getBackend: () => resolveBrowserBackendFromConfig(config)
	});
	return _manager;
}
async function getActionContext() {
	const manager = await getManager();
	await manager.ensureConnected();
	return {
		page: manager.getExtensionProvider() ? null : await manager.getPage("cli"),
		manager,
		config: await loadConfig(),
		taskId: "cli"
	};
}
async function executeBrowserCliAction(action, args) {
	const prevOverride = browserCliHeadlessOverride;
	if (typeof args.headless === "boolean") browserCliHeadlessOverride = args.headless;
	try {
		const registry = createBrowserActionRegistry();
		const ctx = await getActionContext();
		const result = await registry.execute(action, ctx, args);
		if (result.ok) {
			if (result.text) console.log(result.text);
			if (result.data && !result.text) console.log(JSON.stringify(result.data, null, 2));
		} else {
			console.error(`[${result.error?.code}] ${result.error?.message}`);
			process.exitCode = 1;
		}
		if (action === "close") {
			await _manager?.shutdown();
			_manager = null;
		}
	} finally {
		browserCliHeadlessOverride = prevOverride;
	}
}
async function validatePipelineCli(file) {
	let yamlSource;
	try {
		yamlSource = (await loadBrowserPipelineSource(file)).source;
	} catch (e) {
		const msg = e instanceof Error ? e.message : String(e);
		console.error(`Failed to read pipeline source: ${msg}`);
		process.exitCode = 1;
		return;
	}
	const registry = createBrowserActionRegistry();
	const result = validateBrowserPipeline(yamlSource, registry);
	if (result.ok) console.log(`✓ Pipeline "${result.document.name}" is valid (${result.document.pipeline.length} steps).`);
	else {
		console.error("✗ Pipeline validation failed:");
		for (const err of result.errors) console.error(`  ${err.path}: ${err.message}`);
		process.exitCode = 1;
	}
}
async function runPipelineCli(file, args) {
	let yamlSource;
	try {
		yamlSource = (await loadBrowserPipelineSource(file)).source;
	} catch (e) {
		const msg = e instanceof Error ? e.message : String(e);
		console.error(`Failed to read pipeline source: ${msg}`);
		process.exitCode = 1;
		return;
	}
	const registry = createBrowserActionRegistry();
	const ctx = await getActionContext();
	const result = await runBrowserPipeline(yamlSource, args, ctx, registry);
	if (result.ok) {
		if (result.text) console.log(result.text);
		if (result.data && !result.text) console.log(JSON.stringify(result.data, null, 2));
	} else {
		console.error(`Pipeline failed: [${result.error?.code}] ${result.error?.message}`);
		if (result.diagnostics?.snapshot) console.error(`Snapshot:\n${result.diagnostics.snapshot.slice(0, 2e3)}`);
		process.exitCode = 1;
	}
	await _manager?.shutdown();
	_manager = null;
}
async function doctorCli() {
	console.log("Browser Doctor");
	console.log("──────────────");
	try {
		const pw = await loadPlaywrightCoreModule();
		const chromium = pw.chromium ?? pw.default?.chromium;
		if (chromium) {
			console.log("✓ playwright-core installed");
			const execPath = chromium.executablePath?.();
			if (execPath) console.log(`  Chromium path: ${execPath}`);
			else console.log("  ⚠ No default Chromium path detected. Run: npx playwright install chromium");
		} else console.log("✗ playwright-core chromium not available");
	} catch {
		console.log("✗ playwright-core not installed");
	}
	try {
		const browser = (await loadConfig())?.agents?.defaults?.browser;
		console.log(`\nConfig:`);
		console.log(`  enabled: ${browser?.enabled !== false}`);
		console.log(`  headless: ${browser?.headless === true}`);
		console.log(`  backend: ${browser?.backend ?? "extension"}`);
		console.log(`  provider: ${browser?.cloudProvider ?? "local"}`);
		if (browser?.cdpUrl) console.log(`  cdp: ${browser.cdpUrl}`);
		if (browser?.backend === "extension" || browser?.extension) {
			const ext = browser?.extension;
			const port = ext?.port ?? 19820;
			const host = ext?.host ?? "127.0.0.1";
			console.log(`\nExtension Bridge:`);
			console.log(`  endpoint: ws://${host}:${port}/browser-ext`);
			try {
				const { browserExtDoctor } = await import("../../browser/providers/browser-ext-install.js");
				const artifacts = await browserExtDoctor();
				console.log(`  artifacts: ${artifacts.installed ? "✓ installed" : "✗ not installed"}`);
				if (artifacts.extensionDir) console.log(`  path: ${artifacts.extensionDir}`);
				if (artifacts.needsRefresh) console.log(`  refresh: ⚠ bundled update available`);
			} catch {
				console.log(`  artifacts: ⚠ could not check`);
			}
			try {
				const data = await (await fetch(`http://${host}:${port}/`)).json();
				if (data.ok) {
					console.log(`  server: ✓ running`);
					console.log(`  extension: ${data.connected ? "✓ connected" : "⚠ waiting for connection"}`);
				}
			} catch {
				console.log(`  server: ✗ not running (start xopc with backend: 'extension' to enable)`);
			}
		}
	} catch {
		console.log("\n⚠ Could not load config");
	}
}
//#endregion
export { doctorCli, executeBrowserCliAction, runPipelineCli, validatePipelineCli };

//# sourceMappingURL=browser-cli-helpers.js.map