# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

"""IAM role ARN parsing for auto-link configuration."""

import re

# arn:aws:iam::<12-digit account>:role/<path-qualified role name>
# Group 2 captures everything after "role/" so an IAM path is preserved, e.g.
# "cloudzero/CloudZeroResourceOwnerRole" for arn:aws:iam::123456789012:role/cloudzero/CloudZeroResourceOwnerRole
IAM_ROLE_ARN = re.compile(r"^arn:aws:iam::(\d{12}):role/(.+)$")


def parse_iam_role_arn(arn: str) -> tuple[str, str]:
    """Parse an IAM role ARN into its account ID and path-qualified role name.

    The role name is everything after ``role/``, so any IAM path is retained and
    must be applied verbatim when reconstructing the ARN for other accounts.

    Args:
        arn: Full IAM role ARN, e.g. ``arn:aws:iam::123456789012:role/cloudzero/MyRole``.

    Returns:
        Tuple of ``(account_id, role_name)`` where ``role_name`` keeps its path.

    Raises:
        ValueError: If the input is not a well-formed IAM role ARN.
    """
    match = IAM_ROLE_ARN.match(arn.strip()) if arn else None
    if not match:
        raise ValueError(
            f"'{arn}' is not a valid IAM role ARN. Expected arn:aws:iam::<account-id>:role/<path/RoleName>"
        )

    account_id, role_name = match.group(1), match.group(2)
    if role_name.endswith("/"):
        raise ValueError(f"'{arn}' is missing a role name after the path")

    return account_id, role_name
