
from github.env import write_github_env
from terragrunt.constants import APPLY, DESTROY

def set_slack_status(exec_mode, drift=''):
    """
    Set the Slack notification status based on the execution mode and drift status.

    Args:
        exec_mode (str): The execution mode (apply or destroy).
        drift (str or None): The drift status.

    Raises:
        RuntimeError: If the execution mode is unknown.
    """
    if exec_mode == APPLY and drift:
        status = "warning"
    elif exec_mode == APPLY and not drift:
        status = "good"
    elif exec_mode == DESTROY:
        status = "danger"
    else:
        raise RuntimeError(f"unknown execution mode {exec_mode}")
    write_github_env(status, 'SLACK_STATUS')


def format_changes_for_slack_message(data: dict, diff: str = None):
    """
    Generate slack message body from terraform planned changes summary
    """
    # TODO: check if there're changes and if any create this summary as GH artifict and provide link
    if not isinstance(data, dict):
        raise ValueError("data should be a dict")
    if not data and not diff:
        return "*No changes*"
    formatted_message = ''
    if diff:
        formatted_message += ":heavy_exclamation_mark: *Environment Drift detected* :heavy_exclamation_mark:\n"
        formatted_message += ":warning: *Validate* the diff in the workflow log :warning:\n"

    for key, resources in data.items():
        formatted_message += f'`{key}`\n'
        if not isinstance(resources, dict):
            raise ValueError("data.resources should be a dict")
        for resource_type, values in resources.items():
            formatted_message += f'    *{resource_type}*:\n'
            for value in values:
                formatted_message += f'    - {value}\n'
    return formatted_message


def prepend_message_with_inputs(data, work_dir, env_name, plan_version, exec_mode):
    """
    Prepend the slack message with the inputs used in the workflow
    """
    formatted_message = f"*Environment*: {env_name}\n"
    formatted_message += f"*Manifest dir*: {work_dir}\n"
    formatted_message += f"*Plan version*: {plan_version}\n"
    formatted_message += f"*Execution mode*: {exec_mode}\n"
    formatted_message += "`-----------------------------------`\n"
    formatted_message += "\n"
    formatted_message += data
    return formatted_message
