import boto3

from aws.constants import ENVS
from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary

def get_caller_identity_arn():
    try:
        sts_client = boto3.client('sts')
        response = sts_client.get_caller_identity()
        arn = response['Arn']
        logger.debug(f"get_caller_identity_arn: {arn}")
        logger.debug(f"get_caller_identity_res: {response}")
        # arn:aws:sts::540530651831:assumed-role/github_action_prod_account_dev_envs/GitHub_to_AWS_via_FederatedOIDC
        # i need to get the role name from this string
        split_arn = arn.split("/")[1:-1]
        role_name = "/".join(split_arn)
        return role_name
    except Exception as e:
        logger.error(f"Error in get_caller_identity_arn: {e}, returning empty string")
        return ""


def assume_role_get_creds(env_name):
    try:
        current_role_arn = get_caller_identity_arn()
        account_id = ENVS[env_name]['aws_account']
        role_name = ENVS[env_name]['role_name']
        role_arn = f"arn:aws:iam::{account_id}:role/{role_name}"
        if current_role_arn == role_name:
            logger.info(f"already assumed the role {role_arn}")
            return
        sts_client = boto3.client('sts')
        logger.info(f"getting creds for {env_name} of role {role_arn}")
        response = sts_client.assume_role(
            RoleArn=role_arn,
            RoleSessionName='AssumeRoleSession'
        )
        credentials = response['Credentials']
        return credentials
    except Exception as e:
        exit_on_error_and_write_summary(f"Error in assume_role_get_creds for {env_name}: {e}")

