How to iterate through nested map within nested map

I am trying to flatten a nested map within another nested map and then use this for a dynamic block within another dynamic block, and was wondering if this is possible?
here is some details of what i am trying to achieve

variable "gateways" {
    type    = map(any)
    default = {
           gateway1 = {
                  name = "gatewayname"
                  url_paths = {
                         upm1 = { 
                                name = "url_path_name"
                                path_rule = {
                                        pr1 = {
                                             name = "pr_name1"
                                             paths = "path1"
                                             extra = "extra_name1"
                                        },
                                        pr2 = {
                                              name = "pr_name2"
                                             paths = "path2"
                                             extra = "extra_name2"
                                        }
                                 }
                           }
                      }
                }
           }

I am then trying to flatten using the below

locals {
  upm = flatten([
    for gw_key, gws in var.gateways : [
    for urls in gws.url_paths : [
    for pm_key in urls.path_rule : {
      gw_key = gw_key 
      urlpathmapkey = urls.url_path_name
      pathmapname = pm_key.name
      paths = pm_key.paths
      name = pm_key.extra
    }
    ]
    
    ]
  ])
}

and then trying to use this for the double nested dynamic block

resource "azurerm_application_gateway" "network" {
  for_each            = var.gateway
  name                = each.value.name
  location            = each.value.location

      dynamic "url_path_map" {
          for_each = {
            for u in local.upm : "${u.gw_key}.${u.urlpathmapkey}" => u
          }
      content {
        name                                = each.value.urlpathmapkey

        dynamic "path_rule" {
          for_each = {
            for pm in local.upm : 
          "${pm.gw_key}.${pm.urlpathmapkey}${pm.pathmapname}${pm.paths}${pm.name}" 
         => pm
          }
          content {
            name                            = each.value.pathmapname
            paths                           = each.value.paths
            backend_address_pool_name       = "${each.value.name}-beap"
            backend_http_settings_name      = "${each.value.name}-be-htst"

          }

        }
      }
    }
}

Of course please bear in mind that there is a lot more details and blocks for the app gateway but for the purposes of simplifying what i am after, i have only included the bits that i cannot get working. i.e the path_rule dynamic block is a block that is nested in the url_path_map dynamic block. hoping this all makes sense
thanks