is_valid_refugee_pop = {
	is_non_sapient_robot = no
	NOR = {
		has_trait = trait_hive_mind
		can_think = no
		AND = {
			has_virtual_species_trait = yes
			exists = owner
			owner = {
				NOT = {
					has_active_tradition = tr_virtuality_finish
				}
			}
		}
	}
	owner = {
		any_relation = {
			is_country_type = default
			has_communications = prev #relations include countries that have made first contact but not established comms
			NOT = { has_policy_flag = refugees_not_allowed }
			prevprev = { #this ensures Pop scope, as root will not always be pop scope
				OR = {
					has_citizenship_type = { type = citizenship_full country = prev }
					has_citizenship_type = { type = citizenship_organic_trophy country = prev }
					AND = {
						has_citizenship_type = { type = citizenship_limited country = prev }
						prev = { has_policy_flag = refugees_allowed }
					}
				}
			}
			OR = {
				AND = {
					has_policy_flag = robots_allowed
					prevprev = { is_robotic_species = yes }
				}
				prevprev = { is_robotic_species = no }
			}
			any_owned_planet = {
				is_under_colonization = no
				is_controlled_by = owner
				has_orbital_bombardment = no
			}
		}
	}
}

country_has_habitability_and_housing = {
	has_country_flag = valid_refugee_destination_for_@event_target:refugee_pop
	any_owned_planet = {
		planet_has_habitability_and_housing = {
			[[HABITABILITY]
				HABITABILITY = $HABITABILITY$
			]
			[[HOUSING]
				HOUSING = $HOUSING$
			]
		}
	}
}

planet_has_habitability_and_housing = {
	[[HABITABILITY]
		habitability = { who = event_target:refugee_pop value >= $HABITABILITY$ }
	]
	[[HOUSING]
		free_housing >= $HOUSING$
	]
	is_under_colonization = no
	is_controlled_by = owner
	has_orbital_bombardment = no
	NOT = { is_planet_class = pc_cosmogenesis_world }
}

has_any_habitability = {
	is_country_type = default
	has_communications = prev
	NOT = { has_policy_flag = refugees_not_allowed }
	event_target:refugee_pop = {
		OR = {
			has_citizenship_type = { type = citizenship_full country = prev }
			has_citizenship_type = { type = citizenship_organic_trophy country = prev }
			AND = {
				has_citizenship_type = { type = citizenship_limited country = prev }
				prev = { has_policy_flag = refugees_allowed }
			}
		}
		OR = {
			AND = {
				prev = { has_policy_flag = robots_allowed }
				is_robotic_species = yes
			}
			is_robotic_species = no
		}
	}
	any_owned_planet = {
		is_under_colonization = no
		is_controlled_by = owner
		has_orbital_bombardment = no
		NOT = { is_planet_class = pc_cosmogenesis_world }
	}
}
