"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRootHelpCatalogEntries = exports.getRootHelpVisibleCommands = exports.handleHelpRoute = exports.handleHelpCommand = exports.showProviderShortcutHelp = void 0;
const package_json_1 = __importDefault(require("../../package.json"));
const ui_1 = require("../utils/ui");
const command_catalog_1 = require("./command-catalog");
function getTopicSummary(name) {
    return command_catalog_1.ROOT_HELP_TOPICS.find((topic) => topic.name === name)?.summary || '';
}
function writeCommandTable(title, entries, writeLine) {
    writeLine((0, ui_1.subheader)(title));
    const maxWidth = Math.max(...entries.map((entry) => entry.name.length));
    for (const entry of entries) {
        writeLine(`  ${(0, ui_1.color)(entry.name.padEnd(maxWidth + 2), 'command')} ${entry.summary}`);
    }
    writeLine('');
}
function writeGroupedCommands(group, writeLine) {
    const entries = (0, command_catalog_1.getPublicRootCommands)()
        .filter((entry) => entry.group === group)
        .map((entry) => ({ name: entry.name, summary: entry.summary }));
    const titles = {
        start: 'Start Here',
        manage: 'Profile Management',
        operations: 'Operations',
        runtime: 'Compatible Runtimes',
    };
    writeCommandTable(titles[group], entries, writeLine);
}
async function showProfilesHelp(writeLine) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)('CCS Profiles Help'));
    writeLine('');
    writeCommandTable('Profile Types', [
        { name: 'ccs auth create <name>', summary: 'Concurrent Claude account profile' },
        { name: 'ccs auth resources <name>', summary: 'Shared resources for an account profile' },
        { name: 'ccs api create', summary: 'API-backed settings profile' },
        { name: 'ccs cliproxy create <name>', summary: 'Named CLIProxy variant profile' },
        { name: 'ccs env <profile>', summary: 'Export an existing profile for other tools' },
    ], writeLine);
    writeCommandTable('Examples', command_catalog_1.ROOT_PROFILE_EXAMPLES, writeLine);
    writeLine(`  ${(0, ui_1.dim)('Deep help: ccs auth --help | ccs api --help | ccs cliproxy --help')}`);
    writeLine('');
}
async function showProvidersHelp(writeLine) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)('CCS Providers Help'));
    writeLine('');
    writeCommandTable('Built-in OAuth Providers', command_catalog_1.BUILTIN_PROVIDER_SHORTCUTS, writeLine);
    writeCommandTable('Common Setup Paths', [
        {
            name: 'ccs <provider> --auth',
            summary: 'Authenticate a provider account without launching',
        },
        { name: 'ccs api create --preset <id>', summary: 'Create an API-backed provider profile' },
        { name: 'ccs config', summary: 'Use the dashboard for provider and model setup' },
        { name: 'ccs help kiro', summary: 'Kiro-specific auth methods and IDC flags' },
    ], writeLine);
    writeCommandTable('GitLab Duo Flags', [
        {
            name: 'ccs gitlab --auth --gitlab-token-login',
            summary: 'Authenticate with a GitLab Personal Access Token',
        },
        {
            name: 'ccs gitlab --auth --token-login',
            summary: 'Legacy alias for GitLab PAT login (still supported)',
        },
        {
            name: 'ccs gitlab --auth --gitlab-url <url>',
            summary: 'Use a self-hosted GitLab base URL during OAuth or PAT auth',
        },
    ], writeLine);
    writeLine(`  ${(0, ui_1.dim)('Deep help: ccs cliproxy --help | ccs api --help')}`);
    writeLine('');
}
async function showProviderShortcutHelp(provider, writeLine = console.log) {
    if (provider === 'kiro') {
        await showKiroHelp(writeLine);
        return;
    }
    await (0, ui_1.initUI)();
    const providerEntry = command_catalog_1.BUILTIN_PROVIDER_SHORTCUTS.find((entry) => entry.name === provider);
    writeLine((0, ui_1.header)(`CCS ${provider} Shortcut Help`));
    writeLine('');
    writeLine(`  ${providerEntry?.summary || 'CLIProxy OAuth provider shortcut'}.`);
    writeLine('');
    writeCommandTable('Common Commands', [
        { name: `ccs ${provider} --auth`, summary: 'Authenticate the provider account via CLIProxy' },
        { name: `ccs ${provider} --accounts`, summary: 'List or manage stored CLIProxy accounts' },
        { name: `ccs ${provider} --config`, summary: 'Open the provider config flow' },
        { name: `ccs ${provider} "task"`, summary: 'Run Claude through this provider shortcut' },
    ], writeLine);
    if (provider === 'gitlab') {
        writeCommandTable('GitLab Duo Flags', [
            {
                name: '--gitlab-token-login',
                summary: 'Use a GitLab Personal Access Token instead of browser OAuth',
            },
            {
                name: '--token-login',
                summary: 'Legacy alias for `--gitlab-token-login`',
            },
            {
                name: '--gitlab-url <url>',
                summary: 'Target a self-hosted GitLab base URL',
            },
        ], writeLine);
    }
    writeLine(`  ${(0, ui_1.dim)('See also: ccs help providers | ccs cliproxy --help')}`);
    writeLine('');
}
exports.showProviderShortcutHelp = showProviderShortcutHelp;
async function showKiroHelp(writeLine) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)('CCS Kiro Help'));
    writeLine('');
    writeLine('  Kiro supports Builder ID, IDC, and management-only social OAuth flows.');
    writeLine('');
    writeCommandTable('Authentication Methods', [
        { name: 'ccs kiro --auth', summary: 'Default AWS Builder ID device-code flow' },
        {
            name: 'ccs kiro --auth --kiro-auth-method aws-authcode',
            summary: 'AWS Builder ID auth-code flow via local callback server',
        },
        {
            name: 'ccs kiro --auth --kiro-auth-method idc',
            summary: 'IAM Identity Center flow; requires IDC start URL',
        },
        {
            name: 'ccs config',
            summary: 'Dashboard flow for GitHub OAuth and account management',
        },
    ], writeLine);
    writeCommandTable('Kiro Flags', [
        {
            name: '--kiro-auth-method <aws|aws-authcode|google|github|idc>',
            summary: 'Select the Kiro auth method',
        },
        { name: '--kiro-idc-start-url <url>', summary: 'Required IDC start URL when using `idc`' },
        { name: '--kiro-idc-region <region>', summary: 'Optional IDC region override' },
        { name: '--kiro-idc-flow <authcode|device>', summary: 'IDC flow type; defaults to authcode' },
        {
            name: '--paste-callback',
            summary: 'Paste the final callback URL for callback-based CLI auth flows',
        },
        { name: '--import', summary: 'Import an existing Kiro IDE token instead of starting OAuth' },
    ], writeLine);
    writeCommandTable('Examples', [
        { name: 'ccs kiro --auth', summary: 'Start the default Builder ID device flow' },
        {
            name: 'ccs kiro --auth --kiro-auth-method aws-authcode --paste-callback',
            summary: 'Use auth-code flow and paste the callback URL manually',
        },
        {
            name: 'ccs kiro --auth --kiro-auth-method idc --kiro-idc-start-url https://d-xxx.awsapps.com/start',
            summary: 'Start IDC auth with the default authcode flow',
        },
        {
            name: 'ccs kiro --auth --kiro-auth-method idc --kiro-idc-start-url https://d-xxx.awsapps.com/start --kiro-idc-flow device',
            summary: 'Use IDC device-code flow instead of authcode',
        },
    ], writeLine);
    writeLine(`  ${(0, ui_1.dim)('GitHub OAuth is dashboard-only: ccs config -> Accounts -> Add Kiro account')}`);
    writeLine('');
}
async function showTargetsHelp(writeLine) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)('CCS Targets Help'));
    writeLine('');
    writeCommandTable('Target Routing', command_catalog_1.ROOT_COMPATIBLE_ALIAS_EXAMPLES, writeLine);
    writeCommandTable('Examples', [
        { name: 'ccs glm --target droid', summary: 'Run a profile on Droid instead of Claude' },
        {
            name: 'ccs --target codex',
            summary: 'Open a native Codex session with your current setup',
        },
        { name: 'ccs codex-api --target codex', summary: 'Run a routed API bridge on native Codex' },
    ], writeLine);
}
async function handleHelpCommand(writeLine = console.log) {
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.header)(`CCS CLI v${package_json_1.default.version}`));
    writeLine('');
    writeLine('  Claude profile switching, provider routing, runtime bridges, and browser tooling.');
    writeLine('');
    writeLine((0, ui_1.subheader)('Usage'));
    writeLine(`  ${(0, ui_1.color)('ccs <profile> [claude-args...]', 'command')}`);
    writeLine(`  ${(0, ui_1.color)('ccs <command> [options]', 'command')}`);
    writeLine(`  ${(0, ui_1.color)('ccs help <topic>', 'command')}`);
    writeLine('');
    writeGroupedCommands('start', writeLine);
    writeGroupedCommands('manage', writeLine);
    writeGroupedCommands('runtime', writeLine);
    writeGroupedCommands('operations', writeLine);
    writeCommandTable('OAuth Provider Shortcuts', command_catalog_1.BUILTIN_PROVIDER_SHORTCUTS.map((entry) => ({
        name: `ccs ${entry.name}`,
        summary: entry.summary,
    })), writeLine);
    writeCommandTable('Examples', command_catalog_1.ROOT_PROFILE_EXAMPLES, writeLine);
    writeCommandTable('Targets and Aliases', command_catalog_1.ROOT_COMPATIBLE_ALIAS_EXAMPLES, writeLine);
    writeCommandTable('More Help', [
        { name: 'ccs help profiles', summary: getTopicSummary('profiles') },
        { name: 'ccs help providers', summary: getTopicSummary('providers') },
        { name: 'ccs help browser', summary: getTopicSummary('browser') },
        { name: 'ccs help completion', summary: getTopicSummary('completion') },
        { name: 'ccs help targets', summary: getTopicSummary('targets') },
        { name: 'ccs api --help', summary: 'Deep help for API profile lifecycle commands' },
        {
            name: 'ccs cliproxy --help',
            summary: 'Deep help for variants, routing, quota, and lifecycle',
        },
        { name: 'ccs proxy --help', summary: 'Deep help for the OpenAI-compatible local proxy' },
        { name: 'ccs docker --help', summary: 'Deep help for Docker deployment commands' },
        { name: 'ccs cursor --help', summary: 'Deep help for Cursor runtime/admin commands' },
        { name: 'ccs copilot --help', summary: 'Deep help for deprecated GitHub Copilot commands' },
    ], writeLine);
    writeLine(`  ${(0, ui_1.dim)('Flags: -h/--help, -v/--version, -sc/--shell-completion, --target <cli>')}`);
    writeLine('');
}
exports.handleHelpCommand = handleHelpCommand;
function listHelpTargets() {
    return command_catalog_1.ROOT_HELP_TOPICS.map((topic) => topic.name).join(', ');
}
async function handleHelpRoute(args, writeLine = console.log) {
    const topic = args[0];
    if (!topic) {
        await handleHelpCommand(writeLine);
        return;
    }
    if (topic === 'profiles') {
        await showProfilesHelp(writeLine);
        return;
    }
    if (topic === 'providers') {
        await showProvidersHelp(writeLine);
        return;
    }
    if (topic === 'kiro') {
        await showKiroHelp(writeLine);
        return;
    }
    if (topic === 'targets') {
        await showTargetsHelp(writeLine);
        return;
    }
    if (topic === 'browser') {
        await (await Promise.resolve().then(() => __importStar(require('./browser-command')))).showBrowserHelp(writeLine);
        return;
    }
    if (topic === 'completion') {
        const { showShellCompletionHelp } = await Promise.resolve().then(() => __importStar(require('./shell-completion-command')));
        showShellCompletionHelp(writeLine);
        return;
    }
    const commandHandlers = {
        api: async () => (await Promise.resolve().then(() => __importStar(require('./api-command/help')))).showApiCommandHelp(writeLine),
        auth: async () => {
            const authModule = await Promise.resolve().then(() => __importStar(require('../auth/auth-commands')));
            const AuthCommands = authModule.default;
            await new AuthCommands().showHelp();
        },
        cleanup: async () => (await Promise.resolve().then(() => __importStar(require('./cleanup-command')))).handleCleanupCommand(['--help']),
        browser: async () => (await Promise.resolve().then(() => __importStar(require('./browser-command')))).showBrowserHelp(writeLine),
        cliproxy: async () => (await Promise.resolve().then(() => __importStar(require('./cliproxy/help-subcommand')))).showHelp(),
        copilot: async () => process.exit(await (await Promise.resolve().then(() => __importStar(require('./copilot-command')))).handleCopilotCommand(['--help'])),
        cursor: async () => await showProviderShortcutHelp('cursor', writeLine),
        proxy: async () => process.exit(await (await Promise.resolve().then(() => __importStar(require('./proxy-command')))).handleProxyCommand(['--help'])),
        docker: async () => (await Promise.resolve().then(() => __importStar(require('./docker/help-subcommand')))).showHelp(),
        migrate: async () => (await Promise.resolve().then(() => __importStar(require('./migrate-command')))).printMigrateHelp(),
        setup: async () => (await Promise.resolve().then(() => __importStar(require('./setup-command')))).handleSetupCommand(['--help']),
        tokens: async () => process.exit(await (await Promise.resolve().then(() => __importStar(require('./tokens-command')))).handleTokensCommand(['--help'])),
    };
    const handler = commandHandlers[topic];
    if (handler) {
        await handler();
        return;
    }
    await (0, ui_1.initUI)();
    writeLine((0, ui_1.color)(`Unknown help topic or command: ${topic}`, 'error'));
    writeLine('');
    writeLine(`  ${(0, ui_1.dim)(`Available help topics: ${listHelpTargets()}`)}`);
    writeLine('');
    process.exitCode = 1;
}
exports.handleHelpRoute = handleHelpRoute;
function getRootHelpVisibleCommands() {
    return (0, command_catalog_1.getPublicRootCommands)().map((entry) => entry.name);
}
exports.getRootHelpVisibleCommands = getRootHelpVisibleCommands;
function getRootHelpCatalogEntries() {
    return command_catalog_1.ROOT_COMMAND_CATALOG;
}
exports.getRootHelpCatalogEntries = getRootHelpCatalogEntries;
//# sourceMappingURL=help-command.js.map