"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.handleBrowserCommand = exports.showBrowserHelp = void 0;
const browserUtils = __importStar(require("../utils/browser"));
const config_manager_1 = require("../utils/config-manager");
const platform_1 = require("../utils/browser/platform");
const ui_1 = require("../utils/ui");
const config_loader_facade_1 = require("../config/config-loader-facade");
function summarizeBrowserHealth(status) {
    const claudeNeedsAttention = status.claude.enabled && status.claude.state !== 'ready';
    if (claudeNeedsAttention) {
        return { label: 'action required', exitCode: 1 };
    }
    if (status.codex.enabled && status.codex.state !== 'enabled') {
        return { label: 'partial', exitCode: 0 };
    }
    return { label: 'ready', exitCode: 0 };
}
function isBrowserPolicy(value) {
    return value === 'auto' || value === 'manual';
}
function parseBrowserLane(value) {
    if (value === 'claude' || value === 'codex' || value === 'all') {
        return value;
    }
    return undefined;
}
function writeCommandTable(writeLine) {
    writeLine((0, ui_1.subheader)('Commands'));
    writeLine(`  ${(0, ui_1.color)('ccs browser setup', 'command')}                      Configure Claude Browser Attach and print the manual launch command`);
    writeLine(`  ${(0, ui_1.color)('ccs browser status', 'command')}                     Show Claude attach and Codex browser readiness`);
    writeLine(`  ${(0, ui_1.color)('ccs browser doctor', 'command')}                     Explain what is missing and how to fix it`);
    writeLine(`  ${(0, ui_1.color)('ccs browser policy', 'command')}                     Show the saved browser exposure policy and safe defaults`);
    writeLine(`  ${(0, ui_1.color)('ccs browser policy --all manual', 'command')}        Keep browser tooling hidden unless a launch uses --browser`);
    writeLine(`  ${(0, ui_1.color)('ccs browser enable <claude|codex|all>', 'command')}  Turn a browser lane on without forcing auto-exposure`);
    writeLine(`  ${(0, ui_1.color)('ccs browser disable <claude|codex|all>', 'command')} Turn a browser lane off`);
    writeLine('');
}
function writeIntro(writeLine) {
    writeLine('  Claude Browser Attach reuses a local Chrome session for Claude-target launches.');
    writeLine('  Codex Browser Tools inject managed Playwright MCP overrides into Codex-target launches.');
    writeLine('  New installs, plus upgrades without saved browser settings, keep both lanes off by default; enable a lane and use `--browser` when you want browser access.');
    writeLine('');
    writeLine((0, ui_1.subheader)('Launch Overrides'));
    writeLine(`  ${(0, ui_1.color)('--browser', 'command')}     Force browser tooling on for the current launch when the lane is enabled`);
    writeLine(`  ${(0, ui_1.color)('--no-browser', 'command')}  Suppress browser tooling for the current launch even when policy is auto`);
    writeLine('');
}
function writeLaunchPolicy(policy, writeLine) {
    writeLine(`  Policy: ${browserUtils.describeBrowserPolicy(policy)}`);
    writeLine(`  Default launch behavior: ${browserUtils.describeDefaultBrowserExposure(policy)}`);
}
function writeClaudeStatus(status, writeLine, includeLaunchGuidance) {
    const userDataDirDisplay = status.effectiveUserDataDir === status.recommendedUserDataDir
        ? (0, config_manager_1.getCcsPathDisplay)('browser', 'chrome-user-data')
        : status.effectiveUserDataDir;
    writeLine((0, ui_1.subheader)('Claude Browser Attach'));
    writeLine(`  State: ${status.state}`);
    writeLine(`  Enabled: ${status.enabled ? 'yes' : 'no'}`);
    writeLaunchPolicy(status.policy, writeLine);
    writeLine(`  Source: ${status.source}${status.overrideActive ? ' (env override active)' : ''}`);
    writeLine(`  User data dir: ${userDataDirDisplay}`);
    writeLine(`  DevTools port: ${status.devtoolsPort}`);
    writeLine(`  Managed MCP: ${status.managedMcpServerName}`);
    writeLine(`  Managed path: ${status.managedMcpServerPath}`);
    if (status.runtimeEnv?.CCS_BROWSER_DEVTOOLS_HTTP_URL) {
        writeLine(`  DevTools endpoint: ${status.runtimeEnv.CCS_BROWSER_DEVTOOLS_HTTP_URL}`);
    }
    writeLine(`  Detail: ${status.detail}`);
    writeLine(`  Next step: ${status.nextStep}`);
    if (includeLaunchGuidance && status.enabled && status.state !== 'ready') {
        const platform = (0, platform_1.getNodePlatformKey)();
        writeLine(`  Launch command (${platform}): ${status.launchCommands[platform]}`);
    }
    writeLine('');
}
function writeCodexStatus(status, writeLine) {
    writeLine((0, ui_1.subheader)('Codex Browser Tools'));
    writeLine(`  State: ${status.state}`);
    writeLine(`  Enabled: ${status.enabled ? 'yes' : 'no'}`);
    writeLaunchPolicy(status.policy, writeLine);
    writeLine(`  Managed server: ${status.serverName}`);
    writeLine(`  Supports overrides: ${status.supportsConfigOverrides ? 'yes' : 'no'}`);
    writeLine(`  Codex binary: ${status.binaryPath || 'not detected'}`);
    if (status.version) {
        writeLine(`  Codex version: ${status.version}`);
    }
    writeLine(`  Detail: ${status.detail}`);
    writeLine(`  Next step: ${status.nextStep}`);
    writeLine('');
}
function writeSetupSummary(result, writeLine, label) {
    writeLine((0, ui_1.subheader)('Overall'));
    writeLine(`  Command: ${label}`);
    writeLine(`  Result: ${result.ready ? 'ready' : 'action required'}`);
    writeLine(`  Config updated: ${result.configUpdated ? 'yes' : 'no'}`);
    writeLine(`  Created user-data dir: ${result.createdUserDataDir ? 'yes' : 'no'}`);
    writeLine(`  Browser MCP ready: ${result.mcpReady ? 'yes' : 'no'}`);
    if (result.notes.length > 0) {
        for (const note of result.notes) {
            writeLine(`  Note: ${note}`);
        }
    }
    writeLine('');
}
function writePolicySummary(writeLine) {
    const config = (0, config_loader_facade_1.getBrowserConfig)();
    writeLine((0, ui_1.header)('ccs browser policy'));
    writeLine('');
    writeIntro(writeLine);
    writeLine('  New installs and upgrades without saved browser settings: both lanes start disabled and manual.');
    writeLine('');
    writeLine((0, ui_1.subheader)('Claude Browser Attach'));
    writeLine(`  Enabled: ${config.claude.enabled ? 'yes' : 'no'}`);
    writeLaunchPolicy(config.claude.policy, writeLine);
    writeLine('');
    writeLine((0, ui_1.subheader)('Codex Browser Tools'));
    writeLine(`  Enabled: ${config.codex.enabled ? 'yes' : 'no'}`);
    writeLaunchPolicy(config.codex.policy, writeLine);
    writeLine('');
    writeLine((0, ui_1.subheader)('Examples'));
    writeLine(`  ${(0, ui_1.color)('ccs browser policy --all manual', 'command')}  ${(0, ui_1.dim)('# keep browser tooling hidden until a launch opts in')}`);
    writeLine(`  ${(0, ui_1.color)('ccs glm --browser "open the site"', 'command')}  ${(0, ui_1.dim)('# one-run browser opt-in')}`);
    writeLine(`  ${(0, ui_1.color)('ccs glm --no-browser "summarize the docs"', 'command')}  ${(0, ui_1.dim)('# one-run browser opt-out')}`);
    writeLine('');
}
function writeToggleSummary(subcommand, lane, writeLine) {
    const config = (0, config_loader_facade_1.getBrowserConfig)();
    const verb = subcommand === 'enable' ? 'enabled' : 'disabled';
    writeLine((0, ui_1.header)(`ccs browser ${subcommand}`));
    writeLine('');
    writeLine(`  Updated ${lane} browser lane${lane === 'all' ? 's' : ''}.`);
    writeLine(`  Browser lanes are now ${verb} as requested.`);
    if (subcommand === 'enable') {
        writeLine('  Enabled lanes still respect policy, so browser access stays hidden until `--browser` while policy is manual.');
    }
    writeLine('');
    writeLine((0, ui_1.subheader)('Current State'));
    writeLine(`  Claude enabled: ${config.claude.enabled ? 'yes' : 'no'}`);
    writeLine(`  Claude policy: ${config.claude.policy}`);
    writeLine(`  Codex enabled: ${config.codex.enabled ? 'yes' : 'no'}`);
    writeLine(`  Codex policy: ${config.codex.policy}`);
    writeLine('');
}
function updateBrowserPolicies(updates) {
    (0, config_loader_facade_1.mutateConfig)((config) => {
        const current = (0, config_loader_facade_1.getBrowserConfig)();
        config.browser = {
            claude: {
                enabled: current.claude.enabled,
                policy: updates.claude ?? current.claude.policy,
                user_data_dir: current.claude.user_data_dir,
                devtools_port: current.claude.devtools_port,
            },
            codex: {
                enabled: current.codex.enabled,
                policy: updates.codex ?? current.codex.policy,
            },
        };
    });
}
function updateBrowserEnabled(subcommand, lane) {
    const nextEnabled = subcommand === 'enable';
    (0, config_loader_facade_1.mutateConfig)((config) => {
        const current = (0, config_loader_facade_1.getBrowserConfig)();
        config.browser = {
            claude: {
                enabled: lane === 'all' || lane === 'claude' ? nextEnabled : current.claude.enabled,
                policy: current.claude.policy,
                user_data_dir: current.claude.user_data_dir,
                devtools_port: current.claude.devtools_port,
            },
            codex: {
                enabled: lane === 'all' || lane === 'codex' ? nextEnabled : current.codex.enabled,
                policy: current.codex.policy,
            },
        };
    });
}
function parsePolicyArgs(args) {
    let claude;
    let codex;
    for (let index = 0; index < args.length; index += 2) {
        const flag = args[index];
        const value = args[index + 1];
        if (!flag) {
            break;
        }
        if (flag !== '--all' && flag !== '--claude' && flag !== '--codex') {
            return { error: `Unknown browser policy argument: ${flag}` };
        }
        if (!value || value.startsWith('-')) {
            return { error: `${flag} requires a value: auto or manual.` };
        }
        if (!isBrowserPolicy(value)) {
            return { error: `${flag} must be one of: auto, manual.` };
        }
        if (flag === '--all' || flag === '--claude') {
            claude = value;
        }
        if (flag === '--all' || flag === '--codex') {
            codex = value;
        }
    }
    return { claude, codex };
}
function isHelpRequest(args) {
    return args.length === 0 || args[0] === 'help' || args.includes('--help') || args.includes('-h');
}
async function showBrowserHelp(writeLine = console.log) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)('CCS Browser Help'));
    writeLine('');
    writeIntro(writeLine);
    writeLine((0, ui_1.subheader)('Usage'));
    writeLine(`  ${(0, ui_1.color)('ccs browser <setup|status|doctor|policy|enable|disable>', 'command')}`);
    writeLine(`  ${(0, ui_1.color)('ccs help browser', 'command')}`);
    writeLine('');
    writeCommandTable(writeLine);
    writeLine((0, ui_1.subheader)('What Each Lane Does'));
    writeLine('  Claude Browser Attach expects a Chrome user-data dir and remote debugging port.');
    writeLine('  Codex Browser Tools depend on a Codex build that supports --config overrides.');
    writeLine('  New installs and upgrades without saved browser settings keep both lanes off by default, so enabling a lane does not auto-expose browser tooling unless policy is set to auto.');
    writeLine('');
    writeLine((0, ui_1.subheader)('Examples'));
    writeLine(`  ${(0, ui_1.color)('ccs browser setup', 'command')}                   ${(0, ui_1.dim)('# configure browser attach and print the manual launch command')}`);
    writeLine(`  ${(0, ui_1.color)('ccs browser policy --all manual', 'command')}    ${(0, ui_1.dim)('# keep browser tooling hidden until a launch opts in')}`);
    writeLine(`  ${(0, ui_1.color)('ccs glm --browser "inspect app"', 'command')}    ${(0, ui_1.dim)('# one-run browser opt-in')}`);
    writeLine(`  ${(0, ui_1.color)('ccs glm --no-browser "summarize app"', 'command')} ${(0, ui_1.dim)('# one-run browser opt-out')}`);
    writeLine(`  ${(0, ui_1.color)('ccs config', 'command')}                         ${(0, ui_1.dim)('# open Settings > Browser in the dashboard')}`);
    writeLine('');
}
exports.showBrowserHelp = showBrowserHelp;
async function handleBrowserCommand(args, writeLine = console.log) {
    if (isHelpRequest(args)) {
        await showBrowserHelp(writeLine);
        return;
    }
    const subcommand = args[0];
    if (subcommand === 'setup') {
        if (args.includes('--no-launch')) {
            await (0, ui_1.initUI)();
            writeLine((0, ui_1.color)('`ccs browser setup` no longer supports `--no-launch`.', 'error'));
            writeLine(`  ${(0, ui_1.dim)('Setup is config-only and already prints the manual launch command.')}`);
            writeLine('');
            process.exitCode = 1;
            return;
        }
        await (0, ui_1.initUI)();
        const result = await browserUtils.runBrowserSetup();
        const label = 'ccs browser setup';
        writeLine((0, ui_1.header)(label));
        writeLine('');
        writeIntro(writeLine);
        writeSetupSummary(result, writeLine, label);
        writeClaudeStatus(result.status.claude, writeLine, !result.ready);
        writeCodexStatus(result.status.codex, writeLine);
        process.exitCode = result.ready ? 0 : 1;
        return;
    }
    if (subcommand === 'policy') {
        const parsed = parsePolicyArgs(args.slice(1));
        await (0, ui_1.initUI)();
        if (parsed.error) {
            writeLine((0, ui_1.color)(parsed.error, 'error'));
            writeLine('');
            process.exitCode = 1;
            return;
        }
        if (parsed.claude || parsed.codex) {
            updateBrowserPolicies(parsed);
        }
        writePolicySummary(writeLine);
        return;
    }
    if (subcommand === 'enable' || subcommand === 'disable') {
        const lane = parseBrowserLane(args[1]);
        await (0, ui_1.initUI)();
        if (!lane || args.length > 2) {
            writeLine((0, ui_1.color)(`Usage: ccs browser ${subcommand} <claude|codex|all>`, 'error'));
            writeLine('');
            process.exitCode = 1;
            return;
        }
        updateBrowserEnabled(subcommand, lane);
        writeToggleSummary(subcommand, lane, writeLine);
        return;
    }
    if (subcommand === 'doctor' && (args.includes('--fix') || args.includes('-f'))) {
        await (0, ui_1.initUI)();
        writeLine((0, ui_1.color)('`ccs browser doctor` is read-only.', 'error'));
        writeLine(`  ${(0, ui_1.dim)('Run `ccs browser setup` for the browser remediation flow.')}`);
        writeLine('');
        process.exitCode = 1;
        return;
    }
    if (subcommand !== 'status' && subcommand !== 'doctor') {
        await (0, ui_1.initUI)();
        writeLine((0, ui_1.color)(`Unknown browser subcommand: ${subcommand}`, 'error'));
        writeLine('');
        writeLine(`  ${(0, ui_1.dim)('Supported subcommands: setup, status, doctor, policy, enable, disable')}`);
        writeLine('');
        process.exitCode = 1;
        return;
    }
    await (0, ui_1.initUI)();
    const status = await browserUtils.getBrowserStatus();
    writeLine((0, ui_1.header)(`ccs browser ${subcommand}`));
    writeLine('');
    writeIntro(writeLine);
    if (subcommand === 'doctor') {
        const summary = summarizeBrowserHealth(status);
        writeLine((0, ui_1.subheader)('Overall'));
        writeLine(`  Claude Browser Attach: ${status.claude.title}`);
        writeLine(`  Codex Browser Tools: ${status.codex.title}`);
        writeLine(`  Result: ${summary.label}`);
        writeLine('');
    }
    writeClaudeStatus(status.claude, writeLine, subcommand === 'doctor');
    writeCodexStatus(status.codex, writeLine);
    if (subcommand === 'doctor') {
        process.exitCode = summarizeBrowserHealth(status).exitCode;
    }
}
exports.handleBrowserCommand = handleBrowserCommand;
//# sourceMappingURL=browser-command.js.map