"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getManagedBrowserSetupHint = exports.getUserFacingBrowserConfig = exports.getBrowserStatus = void 0;
const path = __importStar(require("path"));
const config_manager_1 = require("../config-manager");
const codex_detector_1 = require("../../targets/codex-detector");
const chrome_reuse_1 = require("./chrome-reuse");
const mcp_installer_1 = require("./mcp-installer");
const platform_1 = require("./platform");
const browser_settings_1 = require("./browser-settings");
const config_loader_facade_1 = require("../../config/config-loader-facade");
async function getBrowserStatus() {
    const browserConfig = getUserFacingBrowserConfig();
    return {
        claude: await buildClaudeBrowserStatus(browserConfig),
        codex: buildCodexBrowserStatus(browserConfig),
    };
}
exports.getBrowserStatus = getBrowserStatus;
function resolveSafeBrowserPolicy(policy) {
    return policy === 'auto' || policy === 'manual' ? policy : 'manual';
}
function resolveSafeBrowserEvalMode(evalMode) {
    return evalMode === 'disabled' || evalMode === 'readonly' || evalMode === 'readwrite'
        ? evalMode
        : 'readonly';
}
function getUserFacingBrowserConfig() {
    const canonical = (0, config_loader_facade_1.getBrowserConfig)();
    const persisted = (0, config_loader_facade_1.loadUnifiedConfig)()?.browser;
    if (!persisted) {
        return {
            claude: {
                ...canonical.claude,
                enabled: false,
                policy: 'manual',
                eval_mode: resolveSafeBrowserEvalMode(canonical.claude.eval_mode),
            },
            codex: {
                ...canonical.codex,
                enabled: false,
                policy: 'manual',
                eval_mode: resolveSafeBrowserEvalMode(canonical.codex.eval_mode),
            },
        };
    }
    return {
        claude: {
            ...canonical.claude,
            enabled: persisted.claude?.enabled ?? false,
            policy: resolveSafeBrowserPolicy(persisted.claude?.policy),
            eval_mode: resolveSafeBrowserEvalMode(persisted.claude?.eval_mode ?? canonical.claude.eval_mode),
        },
        codex: {
            ...canonical.codex,
            enabled: persisted.codex?.enabled ?? false,
            policy: resolveSafeBrowserPolicy(persisted.codex?.policy),
            eval_mode: resolveSafeBrowserEvalMode(persisted.codex?.eval_mode ?? canonical.codex.eval_mode),
        },
    };
}
exports.getUserFacingBrowserConfig = getUserFacingBrowserConfig;
async function buildClaudeBrowserStatus(browserConfig = getUserFacingBrowserConfig()) {
    const effective = (0, browser_settings_1.getEffectiveClaudeBrowserAttachConfig)(browserConfig);
    const launchCommands = (0, browser_settings_1.buildBrowserLaunchCommands)(effective.userDataDir, effective.devtoolsPort);
    const base = {
        enabled: effective.enabled,
        policy: browserConfig.claude.policy,
        evalMode: resolveSafeBrowserEvalMode(browserConfig.claude.eval_mode),
        source: effective.source,
        overrideActive: effective.overrideActive,
        effectiveUserDataDir: effective.userDataDir,
        recommendedUserDataDir: (0, browser_settings_1.getRecommendedBrowserUserDataDir)(),
        devtoolsPort: effective.devtoolsPort,
        managedMcpServerName: (0, mcp_installer_1.getBrowserMcpServerName)(),
        managedMcpServerPath: (0, mcp_installer_1.getBrowserMcpServerPath)(),
        launchCommands,
    };
    if (!effective.enabled) {
        return {
            ...base,
            state: 'disabled',
            title: 'Claude Browser Attach is disabled.',
            detail: 'CCS keeps Claude Browser Attach off by default and will not provision the managed browser MCP runtime until this lane is enabled.',
            nextStep: `Enable Claude Browser Attach in Settings > Browser or in ${(0, config_manager_1.getCcsPathDisplay)('config.yaml')}, then run \`ccs browser setup\` when you are ready to opt in.`,
        };
    }
    const managedBootstrap = (0, browser_settings_1.ensureManagedBrowserUserDataDir)(effective);
    if (managedBootstrap.createdProfileDir) {
        const managedMessage = (0, browser_settings_1.describeManagedBrowserAttachNotReady)(effective, `Chrome reuse metadata not found: ${path.join(effective.userDataDir, 'DevToolsActivePort')}`, {
            createdProfileDir: true,
            launchCommand: launchCommands[(0, platform_1.getNodePlatformKey)()],
        });
        if (managedMessage) {
            return {
                ...base,
                state: managedMessage.state,
                title: managedMessage.title,
                detail: managedMessage.detail,
                nextStep: managedMessage.nextStep,
            };
        }
    }
    try {
        const runtimeEnv = await (0, chrome_reuse_1.resolveBrowserRuntimeEnv)({
            profileDir: effective.userDataDir,
            devtoolsPort: effective.hasExplicitDevtoolsPort ? String(effective.devtoolsPort) : undefined,
        });
        return {
            ...base,
            state: 'ready',
            title: 'Claude Browser Attach is ready.',
            detail: browserConfig.claude.policy === 'manual'
                ? 'CCS can reach the configured Chrome DevTools endpoint, and the lane stays hidden until a launch uses `--browser`.'
                : 'CCS can reach the configured Chrome DevTools endpoint for the current attach session.',
            nextStep: browserConfig.claude.policy === 'manual'
                ? 'Launch a Claude-target CCS session with `--browser` to use the managed browser MCP runtime.'
                : 'Launch a Claude-target CCS session to use the managed browser MCP runtime.',
            runtimeEnv,
        };
    }
    catch (error) {
        const message = error.message;
        const managedMessage = (0, browser_settings_1.describeManagedBrowserAttachNotReady)(effective, message, {
            createdProfileDir: managedBootstrap.createdProfileDir,
            launchCommand: launchCommands[(0, platform_1.getNodePlatformKey)()],
        });
        if (managedMessage) {
            return {
                ...base,
                state: managedMessage.state,
                title: managedMessage.title,
                detail: managedMessage.detail,
                nextStep: managedMessage.nextStep,
            };
        }
        if (message.includes('Chrome profile directory is invalid')) {
            return {
                ...base,
                state: 'path_missing',
                title: 'Claude Browser Attach path is missing.',
                detail: message,
                nextStep: `Create or choose a Chrome user-data directory, then launch Chrome with attach mode enabled. Example: ${launchCommands[(0, platform_1.getNodePlatformKey)()]}`,
            };
        }
        if (message.includes('Chrome reuse metadata')) {
            return {
                ...base,
                state: 'browser_not_running',
                title: 'Claude Browser Attach could not find a running browser session.',
                detail: message,
                nextStep: `Start Chrome with remote debugging and the configured user-data dir. Example: ${launchCommands[(0, platform_1.getNodePlatformKey)()]}`,
            };
        }
        return {
            ...base,
            state: 'endpoint_unreachable',
            title: 'Claude Browser Attach could not reach the DevTools endpoint.',
            detail: message,
            nextStep: `Restart the attach browser session or confirm the configured port. Example: ${launchCommands[(0, platform_1.getNodePlatformKey)()]}`,
        };
    }
}
function buildCodexBrowserStatus(browserConfig = getUserFacingBrowserConfig()) {
    if (!browserConfig.codex.enabled) {
        return {
            enabled: false,
            policy: browserConfig.codex.policy,
            evalMode: resolveSafeBrowserEvalMode(browserConfig.codex.eval_mode),
            state: 'disabled',
            title: 'Codex Browser Tools are disabled.',
            detail: 'CCS keeps Codex Browser Tools off by default and will not inject Playwright MCP browser tooling until this lane is enabled.',
            nextStep: 'Enable Codex Browser Tools in Settings > Browser when you want browser access on Codex-target launches.',
            serverName: 'ccs_browser',
            supportsConfigOverrides: false,
            binaryPath: null,
        };
    }
    const binaryInfo = (0, codex_detector_1.getCodexBinaryInfo)({ includeVersion: true, includeFeatures: true });
    const supportsConfigOverrides = Boolean(binaryInfo?.features?.includes('config-overrides'));
    if (!binaryInfo || !supportsConfigOverrides) {
        return {
            enabled: true,
            policy: browserConfig.codex.policy,
            evalMode: resolveSafeBrowserEvalMode(browserConfig.codex.eval_mode),
            state: 'unsupported_build',
            title: 'Codex Browser Tools need a Codex build with --config override support.',
            detail: binaryInfo
                ? `Detected Codex at ${binaryInfo.path}, but it does not advertise --config overrides.`
                : 'No Codex binary was detected, so CCS cannot confirm managed browser override support.',
            nextStep: 'Install or upgrade Codex, then rerun browser status/doctor.',
            serverName: 'ccs_browser',
            supportsConfigOverrides,
            binaryPath: binaryInfo?.path ?? null,
            version: binaryInfo?.version,
        };
    }
    return {
        enabled: true,
        policy: browserConfig.codex.policy,
        evalMode: resolveSafeBrowserEvalMode(browserConfig.codex.eval_mode),
        state: 'enabled',
        title: 'Codex Browser Tools are enabled.',
        detail: browserConfig.codex.policy === 'manual'
            ? 'CCS can inject the managed Playwright MCP overrides when a Codex-target launch opts in with `--browser`.'
            : 'CCS can inject the managed Playwright MCP overrides into Codex-target launches.',
        nextStep: browserConfig.codex.policy === 'manual'
            ? 'Use `--browser` on a Codex-target CCS launch to access browser tools.'
            : 'Use a Codex-target CCS launch to access browser tools.',
        serverName: 'ccs_browser',
        supportsConfigOverrides,
        binaryPath: binaryInfo.path,
        version: binaryInfo.version,
    };
}
function getManagedBrowserSetupHint() {
    return (0, browser_settings_1.buildManagedBrowserAttachSetupOptions)({
        enabled: true,
        source: 'config',
        overrideActive: false,
        userDataDir: (0, browser_settings_1.getRecommendedBrowserUserDataDir)(),
        devtoolsPort: 9222,
        hasExplicitDevtoolsPort: true,
        evalMode: 'readonly',
    }).join('\n');
}
exports.getManagedBrowserSetupHint = getManagedBrowserSetupHint;
//# sourceMappingURL=browser-status.js.map