from typing import Dict
from typing import List
import re


def filter_allowed_instances(pulumi_state, default_region, login, pulumi_stack_name) -> Dict[str, List[str]]:
    """
    Select all MySQL User resources for the given user.

    :param pulumi_state: The Pulumi Stack state.
    :param default_region: The default AWS region.
    :param login: The user login (email).
    :param pulumi_stack_name: The name of the Pulumi stack.

    :return: A dictionary that associates the AWS regions found to a list with their corresponding RDS instances
    identifiers.
    """
    databases = dict()
    # urn:pulumi:<STACK_NAME>::sari::mysql:index/grant:Grant::(<REGION>/)?<DB_ID>(.<DB_NAME>)?/<LOGIN>
    grant_pattern = re.compile(f"urn:pulumi:{pulumi_stack_name}::sari::mysql:index/grant:Grant::"
                               "(?:(?P<region>[a-z0-9-]+)/)?"
                               "(?P<db_id>[a-z0-9-]+)"
                               r"(\.(?P<db_name>[a-z0-9_-]+))?"
                               f"/{login}")
    for res in pulumi_state["checkpoint"]["latest"]["resources"]:
        urn = res["urn"]
        if match := grant_pattern.match(urn):
            region = match.group("region") or default_region
            db_id = match.group("db_id")
            db_name = res["inputs"]["database"]
            databases.setdefault(region, {}).setdefault(db_id, []).append(db_name)
    return databases