'''opencos.commands.show_tools - command handler for: eda show_tools [args]

Note this command is handled differently than others (such as CommandSim),
it is generally run as simply

    > eda show_tools

uses no tools and will print a pretty list of tools installed (similar to --help)
'''

# Note - similar code waiver, tricky to eliminate it with inheritance when
# calling reusable methods.
# pylint: disable=R0801

import json
import os

from opencos import util, eda_tool_helper
from opencos.eda_base import Command


class CommandShowTools(Command):
    '''command handler for: eda targets'''

    command_name = 'targets'

    def __init__(self, config: dict):
        super().__init__(config)
        # We don't have any args, clear them, and add a few we'll support
        # --quiet handled by opencos.util
        # --json-to-stdout handled by us
        self.args = {
            'json-to-stdout': False,
            'json-out': '',
        }
        self.args_help = {
            'json-to-stdout': 'Prints tool information as JSON to STDOUT',
            'json-out': 'Optional JSON filename to save output',
        }
        self.config = config
        self.status = 0

    def process_tokens( # pylint: disable=unused-argument
        self, tokens: list, process_all: bool = True,
        pwd: str = os.getcwd()
    ) -> list:
        '''This is effectively our 'run' method, entrypoint from opencos.eda.main'''

        # disable artifacts, logging is disabled by eda.py adding 'deps-help' to:
        #   util.global_log.default_log_disable_with_args
        util.artifacts.enabled = False

        # run with process_all=False, we don't care about unparsed args
        super().process_tokens(tokens=tokens, process_all=False, pwd=pwd)

        if any(self.args[a] for a in ('json-to-stdout', 'json-out')):
            self._print_tools_as_json()

        return []

    def _print_tools_as_json(self) -> None:
        '''Prints a JSON string to STDOUT for tool, path, version'''

        info = eda_tool_helper.get_handler_info_with_versions(
            config=self.config, include_commands=True, sort=True, all_details=True
        )
        if self.args['json-to-stdout']:
            print(json.dumps(info, indent=4))
        if filepath := self.args['json-out']:
            try:
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(json.dumps(info, indent=4))
                util.info(f'Wrote tool information --json-out JSON file: {filepath}')
            except PermissionError:
                self.error(f'PermissionError trying to write --json-out JSON file: {filepath}')
            except IOError as e:
                self.error(f'IOError while trying to write --json-out JSON file: {filepath}, {e}')
