'''Handler for: eda waves --tool=cognichip or --tool=cognichip-beta'''

import json
from pathlib import Path
import os

from opencos.commands.waves import CommandWaves
from opencos.eda_base import Tool
from opencos.files import safe_shutil_which
from opencos.utils.subprocess_helpers import IS_LINUX, IS_MACOS, IS_WINDOWS
from opencos.utils.macos_utils import get_macos_tool_info
from opencos.utils.win_utils import get_windows_tool_info

class ToolCognichip(Tool):
    '''
    Derived class for tool specifics for Cognichip

    Holds version, and waveviewer_exe
    '''

    _TOOL = 'cognichip'
    _EXE = 'cognichip'

    waveviewer_exe = ''

    def __init__(self, config: dict):
        super().__init__(config=config)

    def get_versions(self, **kwargs) -> str:
        if self._VERSION:
            return self._VERSION

        self._VERSION = ''

        # cognichip[-beta] --version is fast enough to call subprocess, but that
        # doesn't return the correct value (yet), so instead look for the
        # (note: look for correct 'cognichip' vs 'cognichip-beta'):
        #   Linux: EXE_PATH/../share/cognichip-beta/resources/app/product.json
        #   Macos: /Applications/Cognichip Beta.app/Contents/Resources/app/product.json
        #   Win: $env:LOCALAPPDATA\Programs\Cognichip Beta\resources\app\product.json
        # and look for key "cognichipVersion".
        self.waveviewer_exe = safe_shutil_which(self._EXE)

        if IS_LINUX:
            # For macos, shutil which won't work for cognichip, we'll check later.
            # For windows, we could require it to be in $env:Path, but we can also
            # fish it out of $env:LOCALPPDATA if not in Path.
            if not self.waveviewer_exe:
                return self._VERSION

        product_json_fpath = ''

        if IS_LINUX:
            bin_fpath = Path(self.waveviewer_exe).parent
            product_json_fpath = (
                bin_fpath.parent / 'share' / self._TOOL / 'resources' / 'app' / 'product.json'
            )

        elif IS_MACOS:
            # Note that eda_tool_helper and eda have to be aware of macos tax.
            app_name = self.config.get('tools', {}).get(self._TOOL, {}).get(
                'macos-app-name', ''
            )
            if app_name:
                data = get_macos_tool_info(
                    app_name, prefer_exes=[
                        self._EXE, 'cognichip', 'code'
                    ]
                )
                product_json_fpath = Path(data.get('metadata', ''))
                if exe := data.get('bin', ''):
                    # pass back to what macos tells us:
                    self.waveviewer_exe = exe
                    self._EXE = exe

        elif IS_WINDOWS:
            app_name = 'Cognichip'
            data = get_windows_tool_info(app_name, prefer_exes=[self._EXE])
            product_json_fpath = Path(data.get('metadata', ''))
            if exe := data.get('bin', ''):
                # pass back to what win_utils tells us:
                self.waveviewer_exe = exe
                self._EXE = exe


        if not product_json_fpath or not product_json_fpath.is_file():
            return self._VERSION

        data = {}
        with open(str(product_json_fpath), encoding='utf-8') as f:
            data = json.load(f)
        self._VERSION = data.get('cognichipVersion', '')
        return self._VERSION


class CommandWavesCognichip(CommandWaves, ToolCognichip):
    '''Handler for: eda waves --tool=cognichip

    This is registerd in eda's CONFIG-YML config.tools.cognichip.handlers.waves
    '''

    def __init__(self, config: dict):
        CommandWaves.__init__(self, config=config)
        ToolCognichip.__init__(self, config=self.config)

    def do_it(self) -> None:
        command_list = [
            self.waveviewer_exe, '--disable-workspace-trust', '-r', self.wave_file
        ]
        self.exec(os.path.dirname(self.wave_file), command_list)
