from actions_logging.app_logging import logger
from common.common import run_command
from github.constants import WORKFLOW_DISPATCH_EVENT_NAME
from github.env import exit_on_error_and_write_summary, get_required_env_var, write_github_summary
from core.constants import MANIFESTS_CONFIG, MANIFEST_SVC_NAMES
from core.update_manifests import prepare_and_validate_manifest_config


def create_run_command_str(script_name, manifest_type, manifest_role, image_tags):
    """
    get the data that relevant for each one of the manifest types and envs
    the data comes from constants and from env vars
    with the data will create the run command for the update_user_script.py from sx-gw-manifest-generator repo
    :param script_name: the script name which run
    :param manifest_type: will serve as the value of type=
    :param manifest_role: wil serve as the value of role=
    :param image_tags: will serve as the value of image_tags= (for the new gw service that created)
    :return:
    """
    image_tags_str = f" --tags {image_tags}" if image_tags else ""
    run_command_str = (
        f"python3 {script_name} "
        "--create-manifest-only "
        f"--set type={manifest_type} "
        f"role={manifest_role}"
        f"{image_tags_str}"
    )
    logger.debug(f"run_command_str: {run_command_str}")
    return run_command_str


def create_image_tags_str_by_artifact_name(artifact_name, gw_svc_version):
    try:
        if artifact_name not in MANIFEST_SVC_NAMES:
            msg = f"artifact_name {artifact_name} not in MANIFEST_SVC_NAMES. will use the GW_SERVICE_NAME"
            logger.error_red_bg(msg)
            write_github_summary(msg)
            service_names = [artifact_name]
        else:
            service_names = MANIFEST_SVC_NAMES[artifact_name]
        image_tags_list = [f"{service_name}={gw_svc_version}" for service_name in service_names]
        image_tags_str = ", ".join(image_tags_list)
        return image_tags_str
    except Exception as e:
        raise Exception(f"Failed to create image tags str by artifact name. Error: {e}")


def main():
    """
    I'll get the arg value of --version_to_deploy and then i'll run the update_manifests.py script
    with the args relevant for each manifest type. v3 v4 and edge
    """
    try:
        logger.info_green("will create versioned v3 v4 and edge manifests via update user scripts from sx-gw-manifest-generator repo")
        event_name = get_required_env_var('EVENT_NAME')
        image_tags = ""
        if event_name == WORKFLOW_DISPATCH_EVENT_NAME:
            logger.info(f"event_name is {WORKFLOW_DISPATCH_EVENT_NAME}. will have to get service name and version from env vars")
            gw_svc_name = get_required_env_var('SERVICE_NAME')
            gw_svc_version = get_required_env_var('SERVICE_VERSION')
            image_tags = create_image_tags_str_by_artifact_name(gw_svc_name, gw_svc_version)
            logger.debug(f"image_tags: {image_tags}")
        for manifest_key in MANIFESTS_CONFIG:
            script_name, manifest_role, manifest_type = prepare_and_validate_manifest_config(manifest_key)
            run_command_str = create_run_command_str(script_name,
                                                     manifest_type,
                                                     manifest_role,
                                                     image_tags)
            run_command(run_command_str)
    except Exception as e:
        exit_on_error_and_write_summary(f"Failed to update manifests. Error: {e}")


if __name__ == '__main__':
    main()
