import os
import click
from click.formatting import join_options

from lektor.cli import cli as root_command


OUT = os.path.abspath(os.path.join(
    os.path.dirname(__file__), '..', 'content', 'docs', 'cli'))


def get_opts(param):
    any_prefix_is_slash = []
    def _write(opts):
        rv, any_slashes = join_options(opts)
        if any_slashes:
            any_prefix_is_slash[:] = [True]
        if not param.is_flag and not param.count:
            rv += ' ' + param.make_metavar()
        return rv
    rv = [_write(param.opts)]
    if param.secondary_opts:
        rv.append(_write(param.secondary_opts))
    return (any_prefix_is_slash and '; ' or ' / ').join(rv)


def write_page(data):
    path = data['path'][1:]
    if not path:
        return
    filename = os.path.join(OUT, *(path + ['contents.lr']))
    dirname = os.path.dirname(filename)
    try:
        os.makedirs(dirname)
    except OSError:
        pass

    args = [x['metavar'] for x in data['arguments']]
    body = [
        '`%s`' % ' '.join(data['path'] + args),
        '',
        data['help'] or '',
    ]

    body.append('')
    body.append('## Options')
    body.append('')
    for opt in data['options']:
        prefix = '- `%s`: ' % opt['opt_string']
        for line in click.wrap_text(
                opt['help'] or '', 74, prefix, '  ').splitlines():
            body.append(line)
    body.append('- `--help`: print this help page.')

    fields = [
        ('comment', 'This file is auto generated by dump-cli-help.py'),
        ('title', path[-1]),
        ('summary', data['summary']),
        ('type', 'cmdlet'),
        ('body', '\n'.join(body)),
    ]

    with open(filename, 'w') as f:
        f.write('\n---\n'.join('%s:%s%s' % (
            k,
            len(v.splitlines()) > 1 and '\n\n' or ' ',
            v
        ) for k, v in fields))


def dump_command(cmd, path):
    data = {
        'path': path,
        'summary': cmd.short_help,
        'help': cmd.help.replace('\b', ''),
        'options': [],
        'arguments': [],
    }

    for param in cmd.params:
        if isinstance(param, click.Option):
            data['options'].append({
                'opt_string': get_opts(param),
                'help': param.help,
            })
        else:
            data['arguments'].append({
                'metavar': param.make_metavar(),
            })

    write_page(data)

    if isinstance(cmd, click.Group):
        for child_name, child_cmd in cmd.commands.iteritems():
            dump_command(child_cmd, path + [child_name])


dump_command(root_command, ['lektor'])
