# Budding Instinct (ap_budding_instinct)
# Scope: country (root = the budding hive)

# Rolls once per established colony (2,000+ pops, 10% each), then founds at most two buds.
apb_budding_pulse = {
	set_variable = { which = apb_budding_rolls value = 0 }
	every_owned_planet = {
		limit = {
			is_colony = yes
			is_under_colonization = no
			pop_amount >= 2000
		}
		random = {
			chance = 10
			root = { change_variable = { which = apb_budding_rolls value = 1 } }
		}
	}
	if = {
		limit = { check_variable = { which = apb_budding_rolls value >= 1 } }
		apb_budding_bud_once = yes
	}
	if = {
		limit = { check_variable = { which = apb_budding_rolls value >= 2 } }
		apb_budding_bud_once = yes
	}
	clear_variable = apb_budding_rolls
}

# One bud: prefer good worlds (70%+ habitability), fall back to tolerable ones (40%+).
apb_budding_bud_once = {
	remove_country_flag = apb_budding_done
	apb_budding_bud_at = { HAB = 0.7 }
	if = {
		limit = { NOT = { has_country_flag = apb_budding_done } }
		apb_budding_bud_at = { HAB = 0.4 }
	}
	remove_country_flag = apb_budding_done
}

# Founds a colony on one random eligible planet inside root's borders.
# The limit mirrors vanilla's colonisation rules: can_colonize_planet_trigger is what the
# can_colonize_planet game rule (colony ships) checks; holy worlds, anomalies, owned planets
# (which includes every pre-FTL world) and systems holding a pre-FTL civilisation are excluded.
apb_budding_bud_at = {
	random_planet_within_border = {
		limit = {
			has_owner = no
			is_colony = no
			is_colonizable = yes
			habitable_planet = yes
			# Negative checks are written as NOR on the "= yes" form: in-game, "is_under_colonization = no"
			# never matched an unowned planet (vanilla only uses the "= no" form on owned planets).
			NOR = {
				is_under_colonization = yes
				has_anomaly = yes
				has_modifier = holy_planet
			}
			can_colonize_planet_trigger = { SCOPE = root }
			solar_system = {
				NOT = {
					any_system_planet = {
						exists = owner
						owner = { is_primitive = yes }
					}
				}
			}
			habitability = { who = root.species value >= $HAB$ }
		}
		create_colony = {
			owner = root
			species = root.species
		}
		create_pop_group = {
			species = root.species
			size = 100
		}
		set_planet_flag = apb_budding_announce
		root = {
			set_country_flag = apb_budding_done
			country_event = { id = apb_budding.2 }
		}
	}
}
