# Ported from original Workshop mod (2782571928) with
# Extended with dynamic RP modifiers and event cooldown for the player.

initialize_dynamic_research_slots = {
	set_country_flag = dynamic_research_slots_initialized

	# Set mod metadata (version, compatibility signals) - must be first
	dr_set_mod_metadata = yes

	set_variable = { current_research_slots = amount_research_slots	}
	set_variable = { target_research_slots = 2 }
	set_variable = { removed_research_slots = 0 }

	# Allow other mods to signal compatibility or perform checks before initialization
	dr_check_compatibility_submods = yes

	# Apply all default configuration values (factory weights, thresholds, Easy Slots, game rules)
	dr_apply_research_config = yes

	if = {
		limit = {
			check_variable = { current_research_slots > target_research_slots }
		}
		set_variable = { removed_research_slots = var:current_research_slots }
		subtract_from_variable = { removed_research_slots = var:target_research_slots }
		set_research_slots = var:target_research_slots
		add_to_variable = { easy_research_slots = var:removed_research_slots }
	}

	# Rebuild effective thresholds (including Easy Slots) based on config.
	dr_rebuild_research_thresholds = yes

	# Allow submods to initialize their own variables or perform setup tasks.
	dr_initialize_submods = yes
}

calculate_modifiers_to_rp = {
	set_variable = { civilian_rp_modifier = 0 }
	set_variable = { military_rp_modifier = 0 }
	set_variable = { naval_rp_modifier = 0 }
	set_variable = { total_rp_modifier = 0 }

	# Apply modifier logic only if not disabled via flag.
	if = {
		limit = { NOT = { has_country_flag = dr_disable_rp_modifiers } }
		dr_apply_rp_modifier_logic = yes
	}

	# Validate and cap modifier values (defensive programming)
	if = {
		limit = {
			check_variable = {
				var = total_rp_modifier
				value = 1.0
				compare = greater_than
			}
		}
		set_variable = { total_rp_modifier = 1.0 }
	}
	if = {
		limit = {
			check_variable = {
				var = total_rp_modifier
				value = -0.5
				compare = less_than
			}
		}
		set_variable = { total_rp_modifier = -0.5 }
	}
}


recalculate_dynamic_research_slots = {
	# Compatibility hooks: allow other mods to disable dynamic slot changes per country.
	# If the flag is set, we keep our bookkeeping in sync but skip all slot logic.
	# - dr_disable_dynamic_research_slots: completely disables the system (keeps variables in sync)
	# - dr_disable_research_slot_changes: disables slot changes but still calculates RP (for display/debug)
	if = {
		limit = { has_country_flag = dr_disable_dynamic_research_slots }
		set_variable = { current_research_slots = amount_research_slots }
	}

	if = {
		limit = { NOT = { has_country_flag = dr_disable_dynamic_research_slots } }

		if = {
			limit = {
				check_variable = {
					var = current_research_slots
					value = amount_research_slots
					compare = less_than
				}
			}
			set_variable = { temp = amount_research_slots }
			subtract_from_variable = { temp = current_research_slots }
			add_to_variable = { easy_research_slots = temp }
			country_event = dynamic_research_slots.2
			multiply_variable = { temp = -1 }
			add_research_slot = var:temp
		}

		# Rebuild effective thresholds after Easy Slot changes.
		dr_rebuild_research_thresholds = yes

		# Allow submods to adjust thresholds after Easy Slot logic is applied.
		dr_adjust_research_thresholds_submods = yes

		set_variable = { total_research_power = 0 }
		set_variable = { facility_research_power = 0 }

		# Allow submods to set factory modifiers before RP calculation.
		dr_apply_factory_modifiers_submods = yes

		set_variable = { base_civilian_research_power = 0 }
		add_to_variable = { base_civilian_research_power = research_power_per_civ }
		multiply_variable = { base_civilian_research_power = num_of_civilian_factories }
		set_variable = { temp = 1 }
		add_to_variable = { temp = civilian_rp_modifier }
		set_variable = { civilian_research_power = base_civilian_research_power }
		multiply_variable = { civilian_research_power = temp }


		set_variable = { base_military_research_power = 0 }
		add_to_variable = { base_military_research_power = research_power_per_mil }
		multiply_variable = { base_military_research_power = num_of_military_factories }
		set_variable = { temp = 1 }
		add_to_variable = { temp = military_rp_modifier }
		set_variable = { military_research_power = base_military_research_power }
		multiply_variable = { military_research_power = temp }

		set_variable = { base_naval_research_power = 0 }
		add_to_variable = { base_naval_research_power = research_power_per_nav }
		multiply_variable = { base_naval_research_power = num_of_naval_factories }
		set_variable = { temp = 1 }
		add_to_variable = { temp = naval_rp_modifier }
		set_variable = { naval_research_power = base_naval_research_power }
		multiply_variable = { naval_research_power = temp }

		add_to_variable = { total_research_power = civilian_research_power }
		add_to_variable = { total_research_power = military_research_power }
		add_to_variable = { total_research_power = naval_research_power }

		# Experimental Facilities give additional flat Research Power.
		# Building variables (nuclear_facility, naval_facility, air_facility, land_facility)
		# are only defined at state scope, so we need to iterate over owned states
		# and accumulate counts per facility type on the country.
		set_variable = { nuclear_facility_count = 0 }
		set_variable = { naval_facility_count = 0 }
		set_variable = { air_facility_count = 0 }
		set_variable = { land_facility_count = 0 }
		set_variable = { nuclear_reactor_count = 0 }
		set_variable = { heavy_water_reactor_count = 0 }
		set_variable = { commercial_reactor_count = 0 }

		every_owned_state = {
			if = {
				limit = { nuclear_facility > 0 }
				ROOT = { add_to_variable = { nuclear_facility_count = 1 } }
			}
			if = {
				limit = { naval_facility > 0 }
				ROOT = { add_to_variable = { naval_facility_count = 1 } }
			}
			if = {
				limit = { air_facility > 0 }
				ROOT = { add_to_variable = { air_facility_count = 1 } }
			}
			if = {
				limit = { land_facility > 0 }
				ROOT = { add_to_variable = { land_facility_count = 1 } }
			}
			if = {
				limit = { nuclear_reactor > 0 }
				ROOT = { add_to_variable = { nuclear_reactor_count = 1 } }
			}
			if = {
				limit = { nuclear_reactor_heavy_water > 0 }
				ROOT = { add_to_variable = { heavy_water_reactor_count = 1 } }
			}
			if = {
				limit = { commercial_nuclear_reactor > 0 }
				ROOT = { add_to_variable = { commercial_reactor_count = 1 } }
			}
		}

		# Allow submods to adjust facility counters (custom buildings, scripted logic, etc.).
		dr_collect_facility_counts_submods = yes

		# Validate facility counts (defensive programming - prevent negative values)
		# Note: Due to HOI4 scripting limitations (no variable references), each facility type
		# must be validated individually. This redundancy is necessary.
		if = {
			limit = {
				check_variable = {
					var = nuclear_facility_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { nuclear_facility_count = 0 }
		}
		if = {
			limit = {
				check_variable = {
					var = naval_facility_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { naval_facility_count = 0 }
		}
		if = {
			limit = {
				check_variable = {
					var = air_facility_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { air_facility_count = 0 }
		}
		if = {
			limit = {
				check_variable = {
					var = land_facility_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { land_facility_count = 0 }
		}
		# Validate nuclear reactor counts (defensive programming - prevent negative values)
		if = {
			limit = {
				check_variable = {
					var = nuclear_reactor_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { nuclear_reactor_count = 0 }
		}
		if = {
			limit = {
				check_variable = {
					var = heavy_water_reactor_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { heavy_water_reactor_count = 0 }
		}
		if = {
			limit = {
				check_variable = {
					var = commercial_reactor_count
					value = 0
					compare = less_than
				}
			}
			set_variable = { commercial_reactor_count = 0 }
		}

		# Apply per-facility RP based on accumulated counts (can be disabled via flag).
		if = {
			limit = { NOT = { has_country_flag = dr_disable_facility_rp } }
			
			# Nuclear facilities
			set_variable = { facility_count_var = nuclear_facility_count }
			set_variable = { rp_per_facility_value = rp_per_nuclear_facility }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_nuclear }
			dr_apply_facility_rp_if_present = yes
			
			# Naval facilities
			set_variable = { facility_count_var = naval_facility_count }
			set_variable = { rp_per_facility_value = rp_per_naval_facility }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_naval }
			dr_apply_facility_rp_if_present = yes
			
			# Air facilities
			set_variable = { facility_count_var = air_facility_count }
			set_variable = { rp_per_facility_value = rp_per_air_facility }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_air }
			dr_apply_facility_rp_if_present = yes
			
			# Land facilities
			set_variable = { facility_count_var = land_facility_count }
			set_variable = { rp_per_facility_value = rp_per_land_facility }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_land }
			dr_apply_facility_rp_if_present = yes
			
			# Nuclear Reactor
			set_variable = { facility_count_var = nuclear_reactor_count }
			set_variable = { rp_per_facility_value = rp_per_nuclear_reactor }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_nuclear_reactor }
			dr_apply_facility_rp_if_present = yes
			
			# Heavy Water Reactor
			set_variable = { facility_count_var = heavy_water_reactor_count }
			set_variable = { rp_per_facility_value = rp_per_heavy_water_reactor }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_heavy_water_reactor }
			dr_apply_facility_rp_if_present = yes
			
			# Commercial Reactor
			set_variable = { facility_count_var = commercial_reactor_count }
			set_variable = { rp_per_facility_value = rp_per_commercial_reactor }
			set_variable = { reduction_factor_value = experimental_facility_rp_reduction_commercial_reactor }
			dr_apply_facility_rp_if_present = yes
		}

		# Allow submods to convert facility counts (vanilla or custom) into RP (only if facility RP is enabled).
		if = {
			limit = { NOT = { has_country_flag = dr_disable_facility_rp } }
			dr_apply_facility_rp_submods = yes
		}

		# Apply global RP modifier (from war and alliance rules) - can be disabled via flag.
		if = {
			limit = { NOT = { has_country_flag = dr_disable_rp_modifiers } }
			set_variable = { temp = 1 }
			add_to_variable = { temp = total_rp_modifier }
			multiply_variable = { total_research_power = temp }
		}

		# Final hook for submods to adjust total RP after modifiers have been applied.
		dr_total_rp_modifier_submods = yes

		# Validate total research power (defensive programming - prevent negative values)
		if = {
			limit = {
				check_variable = {
					var = total_research_power
					value = 0
					compare = less_than
				}
			}
			set_variable = { total_research_power = 0 }
		}

		# Validate research_for_slot array (defensive programming - ensure array exists)
		if = {
			limit = {
				NOT = { has_variable = research_for_slot^3 }
			}
			# Re-initialize if array is missing
			dr_apply_research_config = yes
			dr_rebuild_research_thresholds = yes
		}

		for_each_loop = {
			array = research_for_slot

			if = {
				limit = {
					check_variable = {
						var = total_research_power
						value = research_for_slot^i
						compare = greater_than_or_equals
					}
				}
				set_variable = { target_research_slots = i }
			}
		}

		if = {
			limit = {
				check_variable = {
					var = target_research_slots
					value = current_research_slots
					compare = not_equals
				}
			}

			# Slots have changed

			# Player: only show the event if no cooldown is running (or it has expired)
			if = {
				limit = { is_ai = no }

				if = {
					limit = {
						OR = {
							NOT = { has_variable = dr_player_event_cooldown }
							check_variable = {
								var = dr_player_event_cooldown
								value = 0
								compare = less_than_or_equals
							}
						}
					}
					country_event = dynamic_research_slots.1
					set_variable = { dr_player_event_cooldown = 14 }
				}
			}

			# AI: can always fire the event (if used)
			if = {
				limit = { is_ai = yes }
				country_event = dynamic_research_slots.1
			}
		}

		set_variable = { max_research_slots = research_for_slot^num }
		subtract_from_variable = { max_research_slots = 1 }
		set_variable = { next_research_slot_at = 0 }
		if = {
			limit = {
				check_variable = {
					var = target_research_slots
					value = max_research_slots
					compare = less_than
				}
			}
			set_variable = { temp = target_research_slots }
			add_to_variable = { temp = 1 }
			set_variable = { next_research_slot_at = var:research_for_slot^temp }
		}

		# Allow disabling slot changes while keeping RP calculation active (for display/debug purposes).
		if = {
			limit = { NOT = { has_country_flag = dr_disable_research_slot_changes } }
			set_research_slots = var:target_research_slots
		}
		set_variable = { current_research_slots = amount_research_slots }
	}

	# Update tracking variables after a recalculation so we don't trigger again immediately
	set_variable = { dr_last_civ_count = num_of_civilian_factories }
	set_variable = { dr_last_mil_count = num_of_military_factories }
	set_variable = { dr_last_nav_count = num_of_naval_factories }
	set_variable = { dr_days_since_last_full_check = 0 }
}

# Smart check: Only returns true (sets flag) if factory counts have changed
dr_check_for_factory_changes = {
	clr_country_flag = dr_factories_changed
	
	# Check Civs
	if = {
		limit = {
			check_variable = {
				var = dr_last_civ_count
				value = num_of_civilian_factories
				compare = not_equals
			}
		}
		set_country_flag = dr_factories_changed
	}

	# Check Mils (only if not already found change)
	if = {
		limit = {
			NOT = { has_country_flag = dr_factories_changed }
			check_variable = {
				var = dr_last_mil_count
				value = num_of_military_factories
				compare = not_equals
			}
		}
		set_country_flag = dr_factories_changed
	}

	# Check Docks (only if not already found change)
	if = {
		limit = {
			NOT = { has_country_flag = dr_factories_changed }
			check_variable = {
				var = dr_last_nav_count
				value = num_of_naval_factories
				compare = not_equals
			}
		}
		set_country_flag = dr_factories_changed
	}
}

# Wrapper: Runs recalculation ONLY if factories changed OR it's been 7 days
dr_recalculate_if_needed = {
	# 1. Check if factories changed
	dr_check_for_factory_changes = yes

	# 2. Check if it's been 7 days (weekly fallback for custom buildings)
	if = {
		limit = {
			check_variable = {
				var = dr_days_since_last_full_check
				value = 7
				compare = greater_than_or_equals
			}
		}
		set_country_flag = dr_force_weekly_update
	}

	# 3. Execute if either condition is met
	if = {
		limit = {
			OR = {
				has_country_flag = dr_factories_changed
				has_country_flag = dr_force_weekly_update
			}
		}
		recalculate_dynamic_research_slots = yes
		
		# Cleanup flags
		clr_country_flag = dr_factories_changed
		clr_country_flag = dr_force_weekly_update
	}
}

# Submod hook: compatibility check - allows other mods to signal compatibility or perform checks before config is applied
dr_check_compatibility_submods = { }

# Submod hook: initialize custom variables or perform setup tasks during initialization (after config is applied)
dr_initialize_submods = { }

# Submod hook: adjust facility counters after vanilla counting pass
dr_collect_facility_counts_submods = { }

# Submod hook: convert facility counters into RP, or add additional RP sources
dr_apply_facility_rp_submods = { }

# Submod hook: adjust the per-facility RP after the base RP and built-in reduction logic are applied.
# Override this effect to tweak `temp_facility_rp` using the helper variables (facility_rp_count, facility_rp_reduction_factor, facility_rp_multiplier, etc.).
dr_apply_experimental_facility_rp_scaling = { }

# Submod hook: set factory modifiers (civilian_rp_modifier, military_rp_modifier, naval_rp_modifier)
# before the factory RP calculation runs. These modifiers are applied multiplicatively.
dr_apply_factory_modifiers_submods = { }

# Submod hook: adjust research slot thresholds after Easy Slot logic has been applied.
# This allows tweaking thresholds based on custom logic without overriding the entire threshold array.
dr_adjust_research_thresholds_submods = { }

# Submod hook: tweak total RP after the vanilla global modifier is applied
dr_total_rp_modifier_submods = { }

# Submod hook: override opinion factor calculation for alliance members
# If this hook sets alliance_rel_factor and sets the dr_opinion_factor_custom_set flag,
# the default calculation is skipped. This allows submods to explicitly set 0.0 if needed.
# Example:
#   set_variable = { alliance_rel_factor = 0.5 }
#   set_country_flag = dr_opinion_factor_custom_set
dr_get_opinion_factor_for_ally_submods = { }

# Helper effect: Calculate RP for a single facility type
# Expects: facility_rp_count, rp_per_facility_var, facility_rp_reduction_factor
# Sets: temp_facility_rp and adds it to total_research_power and facility_research_power
dr_calculate_single_facility_rp = {
	set_variable = { temp_facility_rp = facility_rp_count }
	multiply_variable = { temp_facility_rp = rp_per_facility_var }
	set_variable = { facility_rp_multiplier = 1 }
	if = {
		limit = {
			check_variable = {
				var = facility_rp_count
				value = 1
				compare = greater_than
			}
		}
		set_variable = { facility_rp_discount = facility_rp_count }
		subtract_from_variable = { facility_rp_discount = 1 }
		multiply_variable = { facility_rp_discount = facility_rp_reduction_factor }
		divide_variable = { facility_rp_discount = 2 }
		subtract_from_variable = { facility_rp_multiplier = facility_rp_discount }
		if = {
			limit = {
				check_variable = {
					var = facility_rp_multiplier
					value = 0
					compare = less_than
				}
			}
			set_variable = { facility_rp_multiplier = 0 }
		}
	}
	multiply_variable = { temp_facility_rp = facility_rp_multiplier }
	dr_apply_experimental_facility_rp_scaling = yes
	add_to_variable = { total_research_power = temp_facility_rp }
	add_to_variable = { facility_research_power = temp_facility_rp }
}

# Helper effect: Apply RP for a facility type if count > 0
# Expects: facility_count_var (variable containing the count)
#          rp_per_facility_value (variable or literal value)
#          reduction_factor_value (variable or literal value)
dr_apply_facility_rp_if_present = {
	if = {
		limit = {
			check_variable = {
				var = facility_count_var
				value = 0
				compare = greater_than
			}
		}
		set_variable = { facility_rp_count = facility_count_var }
		set_variable = { rp_per_facility_var = rp_per_facility_value }
		set_variable = { facility_rp_reduction_factor = reduction_factor_value }
		dr_calculate_single_facility_rp = yes
	}
}