"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.resolveOptionalBrowserAttachRuntime = exports.getEffectiveClaudeBrowserAttachConfig = exports.getBrowserAttachOverride = exports.describeManagedBrowserAttachNotReady = exports.ensureManagedBrowserUserDataDir = exports.buildManagedBrowserAttachSetupOptions = exports.isManagedClaudeBrowserAttachConfig = exports.buildBrowserLaunchCommands = exports.resolveBrowserUserDataDir = exports.getRecommendedBrowserUserDataDir = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_manager_1 = require("../config-manager");
const helpers_1 = require("../helpers");
const chrome_reuse_1 = require("./chrome-reuse");
const platform_1 = require("./platform");
function getRecommendedBrowserUserDataDir() {
    return path.join((0, config_manager_1.getCcsDir)(), 'browser', 'chrome-user-data');
}
exports.getRecommendedBrowserUserDataDir = getRecommendedBrowserUserDataDir;
function resolveBrowserUserDataDir(value) {
    return value?.trim() ? (0, helpers_1.expandPath)(value) : undefined;
}
exports.resolveBrowserUserDataDir = resolveBrowserUserDataDir;
function buildBrowserLaunchCommands(userDataDir, devtoolsPort) {
    const quotedPath = JSON.stringify(userDataDir);
    return {
        darwin: `open -na "Google Chrome" --args --remote-debugging-port=${devtoolsPort} --user-data-dir=${quotedPath}`,
        linux: `google-chrome --remote-debugging-port=${devtoolsPort} --user-data-dir=${quotedPath}`,
        win32: `chrome.exe --remote-debugging-port=${devtoolsPort} --user-data-dir=${quotedPath}`,
    };
}
exports.buildBrowserLaunchCommands = buildBrowserLaunchCommands;
function isManagedClaudeBrowserAttachConfig(config) {
    return (config.source === 'config' &&
        path.resolve(config.userDataDir) === path.resolve(getRecommendedBrowserUserDataDir()));
}
exports.isManagedClaudeBrowserAttachConfig = isManagedClaudeBrowserAttachConfig;
function buildCurrentPlatformLaunchCommand(userDataDir, devtoolsPort) {
    return buildBrowserLaunchCommands(userDataDir, devtoolsPort)[(0, platform_1.getNodePlatformKey)()];
}
function buildManagedBrowserActionLines() {
    return [
        'Run `ccs browser setup` to configure and start the managed browser session.',
        'Diagnose only: `ccs browser doctor`.',
    ];
}
function buildManagedBrowserAttachSetupOptions(_config) {
    return buildManagedBrowserActionLines();
}
exports.buildManagedBrowserAttachSetupOptions = buildManagedBrowserAttachSetupOptions;
function buildManagedBrowserAttachWarning(_config) {
    return [
        'Claude Browser Attach is not ready yet.',
        `  Managed user-data dir: ${(0, config_manager_1.getCcsPathDisplay)('browser', 'chrome-user-data')}`,
        '  CCS will continue without browser tools for this launch.',
        '',
        ...buildManagedBrowserActionLines().map((line) => `  ${line}`),
    ].join('\n');
}
function ensureManagedBrowserUserDataDir(config) {
    if (!isManagedClaudeBrowserAttachConfig(config)) {
        return {
            usesManagedDefaultDir: false,
            createdProfileDir: false,
        };
    }
    try {
        fs.statSync(config.userDataDir);
        return {
            usesManagedDefaultDir: true,
            createdProfileDir: false,
        };
    }
    catch (error) {
        const code = error.code;
        if (code && code !== 'ENOENT') {
            return {
                usesManagedDefaultDir: true,
                createdProfileDir: false,
            };
        }
    }
    try {
        fs.mkdirSync(config.userDataDir, { recursive: true, mode: 0o700 });
        return {
            usesManagedDefaultDir: true,
            createdProfileDir: true,
        };
    }
    catch {
        return {
            usesManagedDefaultDir: true,
            createdProfileDir: false,
        };
    }
}
exports.ensureManagedBrowserUserDataDir = ensureManagedBrowserUserDataDir;
function describeManagedBrowserAttachNotReady(config, errorMessage, options = {}) {
    if (!isManagedClaudeBrowserAttachConfig(config)) {
        return undefined;
    }
    const launchCommand = options.launchCommand ??
        buildCurrentPlatformLaunchCommand((0, config_manager_1.getCcsPathDisplay)('browser', 'chrome-user-data'), config.devtoolsPort);
    const nextStep = [
        ...buildManagedBrowserActionLines(),
        `Manual launch (${(0, platform_1.getNodePlatformKey)()}): ${launchCommand}`,
    ].join('\n');
    if (errorMessage.includes('Chrome reuse metadata')) {
        const summary = options.createdProfileDir
            ? 'CCS created the managed browser profile directory, but the attach session is not running yet.'
            : 'No running attach-mode Chrome session is using the managed browser profile yet.';
        return {
            state: 'browser_not_running',
            title: 'Claude Browser Attach is not ready yet.',
            detail: `${summary} Diagnostic: ${errorMessage}`,
            nextStep,
            warning: buildManagedBrowserAttachWarning(config),
        };
    }
    if (errorMessage.includes('Chrome DevTools endpoint')) {
        return {
            state: 'endpoint_unreachable',
            title: 'Claude Browser Attach could not reach the managed Chrome session.',
            detail: `CCS found the managed browser profile, but the DevTools endpoint did not answer successfully. Diagnostic: ${errorMessage}`,
            nextStep,
            warning: buildManagedBrowserAttachWarning(config),
        };
    }
    if (errorMessage.includes('Chrome profile directory is invalid')) {
        return {
            state: 'path_missing',
            title: 'Claude Browser Attach could not initialize the managed profile.',
            detail: `CCS could not initialize the managed browser profile directory. Diagnostic: ${errorMessage}`,
            nextStep,
            warning: buildManagedBrowserAttachWarning(config),
        };
    }
    return undefined;
}
exports.describeManagedBrowserAttachNotReady = describeManagedBrowserAttachNotReady;
function getBrowserAttachOverride(env = process.env) {
    const explicitUserDataDir = resolveBrowserUserDataDir(env.CCS_BROWSER_USER_DATA_DIR);
    if (explicitUserDataDir) {
        return {
            userDataDir: explicitUserDataDir,
            devtoolsPort: parseDevtoolsPort(env.CCS_BROWSER_DEVTOOLS_PORT),
            source: 'CCS_BROWSER_USER_DATA_DIR',
        };
    }
    const legacyProfileDir = resolveBrowserUserDataDir(env.CCS_BROWSER_PROFILE_DIR);
    if (legacyProfileDir) {
        return {
            userDataDir: legacyProfileDir,
            devtoolsPort: parseDevtoolsPort(env.CCS_BROWSER_DEVTOOLS_PORT),
            source: 'CCS_BROWSER_PROFILE_DIR',
        };
    }
    return {};
}
exports.getBrowserAttachOverride = getBrowserAttachOverride;
function getEffectiveClaudeBrowserAttachConfig(config, env = process.env) {
    const override = getBrowserAttachOverride(env);
    const configUserDataDir = resolveBrowserUserDataDir(config.claude.user_data_dir) ?? getRecommendedBrowserUserDataDir();
    const configPort = normalizeDevtoolsPort(config.claude.devtools_port);
    const configEvalMode = config.claude.eval_mode ?? 'readonly';
    if (override.userDataDir) {
        return {
            enabled: config.claude.enabled,
            source: override.source,
            overrideActive: true,
            userDataDir: override.userDataDir,
            devtoolsPort: override.devtoolsPort ?? configPort,
            hasExplicitDevtoolsPort: override.devtoolsPort !== undefined,
            evalMode: configEvalMode,
        };
    }
    return {
        enabled: config.claude.enabled,
        source: 'config',
        overrideActive: false,
        userDataDir: configUserDataDir,
        devtoolsPort: configPort,
        hasExplicitDevtoolsPort: true,
        evalMode: configEvalMode,
    };
}
exports.getEffectiveClaudeBrowserAttachConfig = getEffectiveClaudeBrowserAttachConfig;
async function resolveOptionalBrowserAttachRuntime(config) {
    if (!config.enabled) {
        return {};
    }
    const bootstrap = ensureManagedBrowserUserDataDir(config);
    if (bootstrap.createdProfileDir) {
        return {
            warning: buildManagedBrowserAttachWarning(config),
        };
    }
    try {
        const runtimeEnv = await (0, chrome_reuse_1.resolveBrowserRuntimeEnv)({
            profileDir: config.userDataDir,
            devtoolsPort: config.hasExplicitDevtoolsPort ? String(config.devtoolsPort) : undefined,
        });
        return {
            runtimeEnv: {
                ...runtimeEnv,
                CCS_BROWSER_EVAL_MODE: config.evalMode,
            },
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        const managedDefaultMessage = describeManagedBrowserAttachNotReady(config, message, {
            createdProfileDir: bootstrap.createdProfileDir,
        });
        if (managedDefaultMessage) {
            return {
                warning: managedDefaultMessage.warning,
            };
        }
        throw error;
    }
}
exports.resolveOptionalBrowserAttachRuntime = resolveOptionalBrowserAttachRuntime;
function parseDevtoolsPort(value) {
    if (!value?.trim() || !/^\d+$/.test(value.trim())) {
        return undefined;
    }
    return normalizeDevtoolsPort(Number.parseInt(value.trim(), 10));
}
function normalizeDevtoolsPort(value) {
    if (!Number.isFinite(value)) {
        return 9222;
    }
    const port = Math.floor(value);
    if (port < 1 || port > 65535) {
        return 9222;
    }
    return port;
}
//# sourceMappingURL=browser-settings.js.map