import subprocess
import os
import shutil

# Global variable to control the printing of updates.
print_updates = True


def run_executable_and_capture_terminal_output_as_list(
    executable_name: str, workflow_map_name: str
) -> list:
    """
    Runs an executable with a specified workflow map name as an argument and captures the terminal output as a list.

    Parameters:
    - executable_name: Name of the executable file (without extension).
    - workflow_map_name: Name of the workflow map to be passed as an argument.

    Returns:
    - A list of strings, each representing a line of terminal output.
    """
    terminal_output_as_list = subprocess.check_output(
        f"python3 {executable_name}.py {workflow_map_name}",
        shell=True,
        universal_newlines=True,
    ).split("\n")
    return terminal_output_as_list


def get_penultimate_terminal_output(
    executable_name: str, workflow_map_name: str
) -> str:
    """
    Gets the penultimate (second-to-last) entry of the terminal output generated by running an executable.

    Parameters:
    - executable_name: Name of the executable file.
    - workflow_map_name: Name of the workflow map to be passed as an argument.

    Returns:
    - The penultimate line of terminal output as a string.
    """
    terminal_output_as_list = run_executable_and_capture_terminal_output_as_list(
        executable_name, workflow_map_name
    )

    if len(terminal_output_as_list) < 2:
        penultimate_terminal_output = "Error: list has less than 2 entries"
    else:
        penultimate_terminal_output = terminal_output_as_list[-2]

    if print_updates:
        print("\nPenultimate Terminal entry captured for test:")
        print(penultimate_terminal_output)

    return penultimate_terminal_output


def clear_previous_output():
    """
    Clears the output directory if it exists.
    """
    if os.path.exists("output/"):
        print("Removing existing output directory")
        shutil.rmtree("output/")


def compare_two_excel_files_as_dictionaries(xl1: dict, xl2: dict) -> bool:
    """
    Compares two dictionaries representing Excel files to check for equality.

    Parameters:
    - xl1: The first Excel file represented as a dictionary.
    - xl2: The second Excel file represented as a dictionary.

    Returns:
    - A boolean value indicating whether the Excel files are equal.
    """
    equal = True
    if xl1.keys() != xl2.keys():
        equal = False
    for key in xl1.keys():
        if not xl1[key].equals(xl2[key]):
            equal = False
    return equal
