#!/usr/bin/env python3
"""Generate our documentation using pydoc-markdown

PYTHON_ARGCOMPLETE_OK
"""
import os
from pathlib import Path
from subprocess import CalledProcessError

summary_demarc = '<!-- DO NOT ADD OR CHANGE ANYTHING BELOW THIS LINE -->'

from milc import set_metadata

set_metadata(name='generate_docs', author='MILC', version='1.3.0')
from milc import cli


@cli.argument('--commit', arg_only=True, action='store_true', help='Commit changes to git.')
@cli.entrypoint('Generate documentation.')
def main(cli):
    doc_path = Path('docs')
    doc_files = []

    for file in Path('milc').glob('**/*.py'):
        if file.name == '__init__.py':
            continue

        # Generate the markdown
        module_name = str(file)[5:-3]
        module_name = module_name.replace('/', '.')
        cmd = ['pydoc-markdown', '-I', 'milc', '-m', module_name]

        try:
            result = cli.run(cmd, check=True)
        except CalledProcessError as e:
            cli.log.error('Could not process file %s: %s', file.name, e)

            for line in e.stderr.split('\n'):
                cli.log.debug(line)

            continue

        # Write the markdown to a file
        filename = f"api_{module_name.replace('.', '_')}.md"
        doc_files.append((module_name, filename))
        doc_file = doc_path / filename
        doc_file.write_text(result.stdout)

    if cli.args.commit:
        cli.run(['git', 'add', 'docs'], capture_output=False)
        cli.run(['git', 'commit', '-m', '[ci] Updated API documentation'], capture_output=False)


if __name__ == '__main__':
    cli()
