How can I fix inconsistent conditional result types when returning values from the same map?

I have a map of values, and I’m basically trying to replace a number of different values while in a giant loop.

I’ve gotten so far, and feel like I’ve almost got this working but stumbling at what maybe the final step.

 Error: Inconsistent conditional result types
│   on line 25, in locals:
│   25:       source_ranges = distinct(flatten([for source in [for source in v.source_ranges_names : source == "#Env" ? replace(source, "#Env", env) : (length(regexall("#Env_customer_cidr", source)) > 0 && env == "prod" ? local.defined_ranges["prod_customer_cidr"] : (length(regexall("#Env_customer_cidr", source)) > 0 && env == "test" ? local.defined_ranges["test_customer_cidr"] : local.defined_ranges[source] ))]: local.defined_ranges[source] ]))
│     ├────────────────
│     │ local.defined_ranges is object with 18 attributes
│     │ local.defined_ranges["prod_customer_cidr"] is tuple with 1 element
│     │ local.defined_ranges["test_customer_cidr"] is tuple with 1 element
│ The true and false result expressions must have consistent types. The given
│ expressions are string and list of string, respectively.

I don’t understand the cause of the error, as I’m referring back to the same object each time and the values in the object are all defined the same way:

   "defined_ranges": {
        "random_cidr": [
        "prod_customer_cidr": [
        "test_customer_cidr": [

In the example error above, source would have a value such as ‘random_cidr’.

I realise this can likely be refactored into something far easier to read/understand but I’m still getting my head around what the terraform is doing.