#!/usr/bin/env python3

'''opencos.eda is an executable script (as `eda <command> ...`)

This is the entrypoint for tool discovery, and running targets from command line or DEPS
markup files
'''

import os
import signal

from opencos import util, engine
from opencos.util import safe_emoji, Colors
from opencos.utils import subprocess_helpers
from opencos.tui import tui


# Configure util:
util.progname = "EDA"
util.global_log.default_log_enabled = True
util.global_log.default_log_filepath = os.path.join('eda.work', 'eda.log')
util.global_log.default_log_disable_with_args.extend([
    # avoid default log on certain eda commands
    'help', 'waves', 'deps-help', 'targets', 'show-tools'
])

IS_EDA_UI: bool = False


# ******************************************************************************
# MAIN


# **************************************************************
# **** Interrupt Handler

def signal_handler(sig, frame) -> None: # pylint: disable=unused-argument
    '''Handles Ctrl-C, called by main_cli() if running from command line'''
    util.fancy_stop()
    util.error(f'{safe_emoji("❌ ")}Received Ctrl+C...', start='\nINFO: [EDA] ')
    subprocess_helpers.cleanup_all()
    util.exit(-1)

# **************************************************************
# **** Startup Code


def main(*args):
    ''' Returns return code (int), entry point for calling eda.main(*list) directly in py code'''

    config, unparsed, original_args = engine.main_init(*args)

    util.info("*** OpenCOS EDA ***", color=Colors.bcyan)

    if IS_EDA_UI:
        # special snowflake case if someone called with a singular arg --debug
        # (without --help or exit)
        util.debug("Starting automatic tool setup: init_config()")
        config = engine.init_config(config=config, quiet=True)
        if not config:
            util.error(f'eda.py main: problem loading config, args: {original_args}')
            return 3

        config['tui'] = {
            'original_args': original_args,
            'run_from': os.getcwd(),
            'eda_from': os.path.dirname(__file__)
        }

        app = tui.EDAApp(config)
        util.set_tui_context(app)
        app.run()
        main_ret = 0

    else:

        if engine.is_eda_interactive(original_args):
            # Force them into help:
            util.info('(no args detected, running with --help)')
            unparsed = ['--help']

        main_ret =  engine.process_tokens(
            tokens=list(unparsed), original_args=original_args, config=config
        )
    # Stop the util log, needed for pytests that call eda.main directly that otherwise
    # won't close the log file via util's atexist.register(stop_log)
    util.global_log.stop()
    return main_ret


def main_cli() -> None:
    ''' Executable script entry point - eda

    from pyproject.tom::project.scripts, or from __main__.
    Returns None, will exit with return code.
    '''
    signal.signal(signal.SIGINT, signal_handler)
    util.global_exit_allowed = True
    # Strip eda or eda.py from sys.argv, we know who we are if called from __main__:
    rc = main()
    subprocess_helpers.cleanup_all()
    util.exit(rc)


def main_ui() -> None:
    ''' Executable script entry point - eda-ui

    from pyproject.tom::project.scripts, or from __main__.
    Returns None, will exit with return code.
    '''
    global IS_EDA_UI # pylint: disable=global-statement
    IS_EDA_UI = True
    main_cli()


if __name__ == '__main__':
    main_cli()
