import { header } from './style.js';
import { globalOptions } from '../input/args.js';
import { table } from './table.js';
import { knownEnv } from '../model/env.js';

const wrap = (str, prefix = '', suffix = '') => str ? `${prefix}${str}${suffix}` : '';

export const getOptionsHelp = (opts) => {
    const names = Object.keys(opts);
    names.sort((a, b) => (opts[a].index ?? 0) - (opts[b].index ?? 0));
    return table({
        showHeaders: false,
        data: names.map(name => [
            ' ' + wrap(opts[name].keys.join(', '), ' ') + wrap(opts[name].helpLiteral, ' '),
            opts[name].helpText ?? ''
        ])
    }).toString();
};

export const getCommandHelp = (meta) => [
    meta.desc,
    '',
    header('Usage:'),
    '  ' + meta.usage,
    meta.alias
        ? '\n' + header('Alias:') + '\n  ' + meta.alias + '\n'
        : '',
    header('Arguments:'),
    getOptionsHelp(meta.options),
    '',
    header('Global Flags:'),
    getOptionsHelp(globalOptions)
].join('\n');

export const getEnvironmentVariablesHelp = (cli) => {
    const envMap = knownEnv(cli);
    return table({
        type: 'rows',
        showHeaders: false,
        headers: [
            { name: 'name', title: 'Name' },
            { name: 'description', title: 'Description' },
        ],
        data: Object.entries(envMap).map(
            ([name, { description }]) => ({ name: '  ' + name, description })
        )
    });
};

export const getGeneralHelp = (ctx, commands) => [
    `${ctx.cli.description} (v${ctx.cli.version})`,
    '',
    header('Usage:'),
    `  ${ctx.cli.bin} [COMMAND] [ARGUMENTS] [GLOBAL_FLAGS]`,
    '',
    header('Commands:'),
    table({
        showHeaders: false,
        data: commands.map(cmd => {
            const meta = cmd.getMetadata();
            return [
                '  ' + meta.name + (meta.alias ? ', ' + meta.alias : ''),
                meta.desc
            ];
        })
    }),
    '',
    header('Global Flags:'),
    getOptionsHelp(globalOptions),
    '',
    header('Environment Variables:'),
    getEnvironmentVariablesHelp(ctx.cli)
].join('\n');
