"""
The command line module provides the main function of the application.
"""
# from asyncio import subprocess
import subprocess
import sys
import json
import click
from smelly_python.code_smell import CodeSmell
from .generator.webpage_generator import generate_webpage


@click.command()
@click.option('--file', '-f', type=click.Path(exists=True),
              help='Specify the json file generated by pylint.')
@click.option('--command', '-c', help='The command to run pylint')
def main(file, command):
    """
    Main command line interface.
    Takes the first command line argument to be the json generated by pylint.
    """
    if ((file is not None) and (command is not None) or (file == command)):
        print("Please only provide either --file or --command argument")
        sys.exit(1)
    content = ""
    if command:
        print('Running pylint...')
        print([*command.split(), *['--output-format=json']])
        try:
            result = subprocess.run([*command.split(), *['--output-format=json', '--exit-zero']],
                                    capture_output=True, text=True, check=True)
        except subprocess.CalledProcessError:
            print(
                f'Whoops we could not run pylint with the following command: {command}')
            sys.exit(1)
        content = json.loads(result.stdout)
    else:
        with open(file, 'r', encoding='utf-8') as input_file:
            content = json.load(input_file)

    code_smells = CodeSmell.convert_dict(content)
    generate_webpage(code_smells)
