import sys
import os
from logging import getLogger
import signal
from typing import Any

from Model.error.errorcodes import UNEXPECTED_ERROR_CODE, SUCCESS_EXIT_CODE, \
    KEYBOARD_INTERRUPT_CODE

def handle(sig: int, frame: Any) -> None:
    raise KeyboardInterrupt()

signal.signal(signal.SIGINT, handle)
# On Windows, SIGBREAK may exist
if hasattr(signal, "SIGBREAK"):
    signal.signal(signal.SIGBREAK, handle)

def launch_app():
    logger = getLogger(__name__)
    is_setup_logger = False
    exit_code = SUCCESS_EXIT_CODE
    try:
        from logger import setup_config
        setup_config()
        is_setup_logger = True
        from app import App
        uart_tool = App()
        exit_code = uart_tool.run()
    except SystemExit as e:
        exit_code = e.code if isinstance(e.code, int) else UNEXPECTED_ERROR_CODE
        if e.code != 0:
            logger.debug(f"System exit: {e}", exc_info=True)
    except KeyboardInterrupt:
        logger.warning("Interrupted by user (Ctrl+C)")
        exit_code = KEYBOARD_INTERRUPT_CODE
    except ImportError as e:
        logger.error(f"Import error: {e}", exc_info=True)
        exit_code = UNEXPECTED_ERROR_CODE
    except BaseException as e:
        logger.error(f"Unexpected error: {e}", exc_info=True)
        exit_code = UNEXPECTED_ERROR_CODE
    finally:
        if is_setup_logger:
            from logger import close_all_handler
            from logger.atmosic_logger import copy_fail_log_to_fail_folder
            close_all_handler()
            if exit_code != SUCCESS_EXIT_CODE:
                copy_fail_log_to_fail_folder(exit_code)
        if "DISPLAY_EXIT_CODE" in os.environ:
            if exit_code == SUCCESS_EXIT_CODE:
                print("Exit code: 0")
            else:
                color_header = "\033[91m"
                color_footer = "\033[0m"
                print(f"{color_header}Exit code: {exit_code}{color_footer}",
                      file= sys.stderr)
        sys.exit(exit_code)