locals {
  # Duration parsing map
  duration_units = {
    "s" = 1
    "m" = 60
    "h" = 3600
    "d" = 86400
  }

  # Mapping for datasources
  datasource_mapping      = { for ds in var.datasources : ds.uid => ds.name }
  datasource_mapping_type = { for ds in var.datasources : ds.uid => lookup(ds, "type", "prometheus") }

  # Folder time range mapping with 1-minute default
  folder_time_ranges = {
    for uid in distinct([for group in var.groups : lookup(var.folder_uids, group.dashboard_alert_group_name, null) if group.dashboard_alert_group_name != null]) :
    uid => lookup(var.folder_time_ranges, uid, 60) # Default to 60 seconds (1 minute) if not specified
  }

  # Combine all alerts and their respective configurations
  combined_alerts = flatten([
    for group in var.groups : [
      for datasource_uid in group.alerts_on_datasources_uid :
      {
        alert_group_name = group.dashboard_alert_group_name
        folder_uid       = lookup(var.folder_uids, group.dashboard_alert_group_name, null)
        datasource_name  = lookup(local.datasource_mapping, datasource_uid, "unknown")
        datasource_uid   = datasource_uid
        datasource_type  = lookup(local.datasource_mapping_type, datasource_uid, "prometheus")

        alert_files = [
          for file_path in fileset(group.alert_definitions_path, "**/*.yaml") :
          {
            # Store full YAML content
            content = yamldecode(file("${group.alert_definitions_path}/${file_path}"))

            # Extract commonly used fields
            name        = try(yamldecode(file("${group.alert_definitions_path}/${file_path}")).name, null)
            alert_type  = try(yamldecode(file("${group.alert_definitions_path}/${file_path}")).datasource_type, "prometheus")
            editor_type = try(yamldecode(file("${group.alert_definitions_path}/${file_path}")).editor_type, null)
            mode        = try(yamldecode(file("${group.alert_definitions_path}/${file_path}")).mode, "single")

            # File metadata
            alert_file_path = "${group.alert_definitions_path}/${file_path}"
            alert_category  = split("/", file_path)[0]
          }
          if can(group.alert_definitions_path) &&
          group.alert_definitions_path != null &&
          (try(trimspace(group.alert_definitions_path), "") != "")
        ]
      }
    ]
  ])

  # Group alerts by datasource
  grouped_alerts_by_datasource = {
    for alert in local.combined_alerts :
    "${alert.datasource_name} (${alert.alert_group_name})" => merge(alert, {
      alert_files = flatten([
        for a in local.combined_alerts :
        a.alert_files if a.datasource_name == alert.datasource_name && a.alert_group_name == alert.alert_group_name
      ])
    })
  }
}
