"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveHelpRequest = resolveHelpRequest;
exports.printHelp = printHelp;
exports.printNearestHelp = printNearestHelp;
exports.renderHelp = renderHelp;
exports.renderAllHelp = renderAllHelp;
const locale_1 = require("../commands/locale");
const branding_1 = require("../core/branding");
const catalog_1 = require("../i18n/catalog");
const help_topics_1 = require("./help-topics");
const HELP_OPTION_TOKENS = new Set(["--help", "-h"]);
const HELP_ALL_TOKEN = "--all";
const TOPIC_BY_PATH = new Map(help_topics_1.HELP_TOPICS.map((topic) => [formatHelpPath(topic.path), topic]));
function resolveHelpRequest(argv) {
    const [command, ...args] = argv;
    if (command === undefined) {
        return undefined;
    }
    if (HELP_OPTION_TOKENS.has(command)) {
        return { kind: "help", path: [], all: false };
    }
    if (command === "help") {
        const path = args.filter((token) => !HELP_OPTION_TOKENS.has(token));
        if (isAllHelpPath(path)) {
            return { kind: "help", path: [], all: true };
        }
        if (path.length === 0) {
            return { kind: "help", path: [], all: false };
        }
        return { kind: "unsupported-command-help", path };
    }
    const helpIndex = argv.findIndex((token) => HELP_OPTION_TOKENS.has(token));
    if (helpIndex === -1) {
        return undefined;
    }
    const path = argv.slice(0, helpIndex);
    return {
        kind: "help",
        path,
        all: false,
    };
}
async function printHelp(cwd = process.cwd(), path = [], all = false) {
    const locale = await (0, locale_1.loadCommandLocale)(cwd);
    const helpText = all ? renderAllHelp(locale) : renderHelp(path, locale);
    if (helpText === null) {
        return false;
    }
    console.log(helpText);
    return true;
}
async function printNearestHelp(cwd = process.cwd(), path = []) {
    await printHelp(cwd, resolveNearestHelpPath(path));
}
function renderHelp(path, locale) {
    if (path.length === 0) {
        return renderRootHelp(locale);
    }
    const topic = TOPIC_BY_PATH.get(formatHelpPath(path));
    if (topic === undefined) {
        return null;
    }
    return renderTopicHelp(topic, locale);
}
function renderAllHelp(locale) {
    return [
        renderRootHelp(locale),
        ...help_topics_1.HELP_TOPICS.map((topic) => renderTopicHelp(topic, locale)),
    ].join("\n\n---\n\n");
}
function isAllHelpPath(path) {
    return path.length === 1 && path[0] === HELP_ALL_TOKEN;
}
function renderRootHelp(locale) {
    return [
        `${branding_1.CLI_COMMAND_NAME} <command>`,
        "",
        (0, catalog_1.translate)(locale, "help.commands.heading"),
        ...renderCommandSummaries(help_topics_1.HELP_TOPICS.filter((topic) => topic.root), []),
        "",
        (0, catalog_1.translate)(locale, "help.notes.heading"),
        `  ${(0, catalog_1.translate)(locale, "help.notes.initConfig", { configFilename: branding_1.CONFIG_FILENAME })}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.initResolveConnections")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.authSetupInteractive")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.authClearConfirm")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.labelsSync")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.serviceEnable", { serviceName: branding_1.SERVICE_DISPLAY_NAME })}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.serviceDrain")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.aiRunningOwnership")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.issueCreateModes")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.resolutionCreateModes")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.workflowCreateModes")}`,
        `  ${(0, catalog_1.translate)(locale, "help.notes.workflowIssueCreateSplit")}`,
        "",
        (0, catalog_1.translate)(locale, "help.commandSpecificHint", {
            cliCommand: branding_1.CLI_COMMAND_NAME,
        }),
    ].join("\n");
}
function renderTopicHelp(topic, locale) {
    const childTopics = getDirectChildTopics(topic.path);
    const sections = [
        renderSection((0, catalog_1.translate)(locale, "help.usage.heading"), topic.usages.flatMap((usage) => renderUsage(usage, { indent: "  ", includeCliCommand: true }))),
        topic.summary,
    ];
    if (childTopics.length > 0) {
        sections.push(renderSection((0, catalog_1.translate)(locale, "help.commands.heading"), renderCommandSummaries(childTopics, topic.path)));
    }
    const optionLines = renderOptionLines(topic);
    if (optionLines.length > 0) {
        sections.push(renderSection((0, catalog_1.translate)(locale, "help.options.heading"), optionLines));
    }
    if (topic.notes && topic.notes.length > 0) {
        sections.push(renderSection((0, catalog_1.translate)(locale, "help.notes.heading"), topic.notes.map((note) => `  ${note}`)));
    }
    if (topic.examples && topic.examples.length > 0) {
        sections.push(renderSection((0, catalog_1.translate)(locale, "help.examples.heading"), topic.examples.map((example) => `  ${example}`)));
    }
    if (topic.docs && topic.docs.length > 0) {
        sections.push(renderSection((0, catalog_1.translate)(locale, "help.docs.heading"), topic.docs.map((doc) => `  ${branding_1.CLI_COMMAND_NAME} docs show ${doc}`)));
    }
    if (childTopics.length > 0) {
        sections.push(topic.subcommandHint ??
            (0, catalog_1.translate)(locale, "help.subcommandSpecificHint", {
                cliCommand: branding_1.CLI_COMMAND_NAME,
                commandPath: formatHelpPath(topic.path),
            }));
    }
    return sections.filter((section) => section.length > 0).join("\n\n");
}
function resolveNearestHelpPath(path) {
    for (let length = path.length - 1; length > 0; length -= 1) {
        const candidate = path.slice(0, length);
        if (TOPIC_BY_PATH.has(formatHelpPath(candidate))) {
            return candidate;
        }
    }
    return [];
}
function renderSection(heading, lines) {
    return [heading, ...lines].join("\n");
}
function renderOptionLines(topic) {
    return [
        ...(topic.options?.map((option) => `  ${option}`) ?? []),
        ...(topic.optionSections?.flatMap((section) => renderOptionSection(section)) ?? []),
    ];
}
function renderOptionSection(section) {
    return [
        `  ${section.heading}`,
        ...(section.description ? [`    ${section.description}`] : []),
        ...section.options.map((option) => `    ${option}`),
    ];
}
function renderCommandSummaries(topics, basePath) {
    const rows = topics.map((topic) => ({
        commandPath: formatHelpPath(topic.path.slice(basePath.length)),
        summary: topic.summary,
    }));
    const commandColumnWidth = Math.max(0, ...rows.map((row) => row.commandPath.length));
    return rows.map((row) => `  ${row.commandPath.padEnd(commandColumnWidth)}  ${row.summary}`);
}
function renderUsage(usage, options) {
    const [firstLine = "", ...restLines] = usage.split("\n");
    const commandPrefix = options.includeCliCommand ? `${branding_1.CLI_COMMAND_NAME} ` : "";
    const continuationPrefix = options.includeCliCommand
        ? " ".repeat(commandPrefix.length)
        : "";
    return [
        `${options.indent}${commandPrefix}${firstLine}`,
        ...restLines.map((line) => `${options.indent}${continuationPrefix}${line}`),
    ];
}
function getDirectChildTopics(path) {
    return help_topics_1.HELP_TOPICS.filter((topic) => topic.path.length === path.length + 1 &&
        path.every((part, index) => topic.path[index] === part));
}
function formatHelpPath(path) {
    return path.join(" ");
}
