﻿#########################
# Debug Logging Effects #
#########################
# Effect which toggles regula heresy debug messaging.
regula_heresy_debug_toggle_effect = {
	if = {
		limit = {
			regula_heresy_debug_enabled_trigger = yes
		}
		remove_global_variable = regula_heresy_debug_enabled
	}
	else = {
		set_global_variable = {
			name = regula_heresy_debug_enabled
			value = yes
		}
	}
}

# Effect which sends a notification to the magister when we are evaluating
# whether or not a heresy story cycle should start if debug mode is enabled.
#
# scope = the character for whom the heresy story is potentially starting.
regula_heresy_story_start_chance_log_effect = {
	save_temporary_scope_as = heresy_target
	if = {
		limit = {
			regula_heresy_debug_enabled_trigger = yes
		}

		send_interface_message = {
			type = event_generic_neutral_text
			title = regula_heresy_debug_start_chance_title
			desc = regula_heresy_debug_start_chance_desc
		}
	}
}

# Effect which sends a notifcation to the story owner about the state of an
# active regula heresy story.
#
# Specifically, this will log:
# - # of active conspirators
# - growth
# - discontent
# - threat
#
# scope = the regula heresy story.
regula_heresy_story_debug_state_log_effect = {
	if = {
		limit = {
			regula_heresy_debug_enabled_trigger = yes
		}

		save_temporary_scope_as = regula_heresy_story
		story_owner = {
			save_temporary_scope_as = regula_heresy_owner
			send_interface_message = {
				type = event_generic_neutral_text
				title = regula_heresy_debug_state_title
				desc = regula_heresy_debug_state_desc
			}
		}
	}
}

# Effect which sends a notifcation to the story owner a member joining the
# regula heresy story.
#
# Specifically, this will log:
# - Name of new conspirator
#
# scope = the character being added to the heresy story cycle.
# scope:regula_heresy_story = the regula heresy story.
regula_heresy_story_debug_member_add_log_effect = {
	if = {
		limit = {
			regula_heresy_debug_enabled_trigger = yes
		}
		save_temporary_scope_as = new_member

		scope:regula_heresy_story = {
			story_owner = {
				send_interface_message = {
					type = event_generic_neutral_text
					title = regula_heresy_debug_member_add_title
					desc = regula_heresy_debug_member_add_desc
					right_icon = scope:new_member
				}
			}
		}
	}
}

# Effect which logs the end of a regula heresy story.
#
# scope = the regula heresy story.
regula_heresy_story_debug_end_log_effect = {
	if = {
		limit = {
			regula_heresy_debug_enabled_trigger = yes
		}

		save_temporary_scope_as = regula_heresy_story
		story_owner = {
			send_interface_message = {
				type = event_generic_neutral_text
				title = regula_heresy_debug_end_title
				desc = regula_heresy_debug_end_desc
			}
		}
	}
}

##################
# Upkeep Effects #
##################
# Checks for any expected ending conditions for the heresy story cycle,
# and if a condition is detected, transition into a terminal state.
#
# scope = the heresy story cycle.
regula_heresy_check_for_end_state_effect = {
	if = { # Magister Change -> End Conspiracy
		limit = {
			NOT = {
				story_owner = global_var:magister_character
			}
		}
		set_variable = {
			name = regula_heresy_state
			value = flag:silent_end
		}
	}
	else_if = { # All Members Removed -> End Conspiracy
		limit = {
			story_owner = {
				NOR = {
					any_targeting_faction = {
						regula_faction_is_heresy_faction_trigger = yes
					}
					any_targeting_secret = {
						secret_type = regula_heresy_conspirator_secret
					}
				}
			}
		}

		# Story end depends on whether or not the conspiracy was actually
		# in an discovered state.
		if = { # Wasn't even discovered => end silently.
			limit = {
				var:regula_heresy_state = flag:conspiracy_hidden
			}
			set_variable = {
				name = regula_heresy_state
				value = flag:silent_end
			}
		}
		else = { # Discovered, and no more members => crushed.
			set_variable = {
				name = regula_heresy_state
				value = flag:crushed
			}
		}
	}
	else_if = { # No Potential for a Useful Outcome -> End Conspiracy
		limit = {
			# If we haven't yet gone public, and there are no potential heresy
			# counties, then the only way that the heresy could have a
			# meaningful outcome would be vassal members. If we don't have any
			# vassal members, then we should go ahead and end the conspiracy.
			regula_heresy_story_in_secret_state_trigger = yes
			story_owner = {
				regula_heresy_any_potential_heresy_county_trigger = no
				NOT = {
					any_targeting_secret = {
						secret_type = regula_heresy_conspirator_secret
						secret_owner = {
							highest_held_title_tier >= tier_county
						}
					}
				}
			}
		}

		if = { # Wasn't even discovered => end silently.
			limit = {
				var:regula_heresy_state = flag:conspiracy_hidden
			}
			set_variable = {
				name = regula_heresy_state
				value = flag:silent_end
			}
		}
		else = { # Discovered, and no potential for heresy growth.
			set_variable = {
				name = regula_heresy_state
				value = flag:crushed
			}
		}
	}
	else = { # Threat Reached Threshold -> End Conspiracy
		regula_heresy_check_for_disband_effect = yes
	}
}

# Checks if the story cycle has reached threat level needed for disband, and if so,
# moves to a disbanded state.
#
# scope = the heresy story cycle.
regula_heresy_check_for_disband_effect = {
	if = {
		limit = {
			var:regula_heresy_threat >= regula_heresy_threat_needed_for_disband
		}

		if = {
			limit = {
				var:regula_heresy_state = flag:faction_active
			}

			set_variable = {
				name = regula_heresy_state
				value = flag:faction_disband
			}
		}
		else = {
			set_variable = {
				name = regula_heresy_state
				value = flag:disband
			}
		}
	}
}

# Checks whether the heresy has been discovered (target knows of heresy secret)
# while the story is still in hidden state. If so, transition to known and send
# update.
#
# scope = the heresy story cycle.
regula_heresy_check_for_newly_discovered_effect = {
	if = {
		limit = {
			var:regula_heresy_state = flag:conspiracy_hidden
			story_owner = {
				any_targeting_secret = {
					secret_type = regula_heresy_conspirator_secret
					is_known_by = prev
				}
			}
		}

		set_variable = {
			name = regula_heresy_state
			value = flag:conspiracy_discovered
		}
		regula_heresy_send_discover_event_effect = yes
	}
}

# Updates the growth measurement for the heresy story cycle, adding
# members if needed.
#
# scope = the heresy story cycle.
regula_heresy_update_growth_effect = {
	if = {
		limit = {
			regula_heresy_story_in_terminal_state_trigger = no
			regula_heresy_at_war_trigger = no
		}

		change_variable = {
			name = regula_heresy_growth
			add = story_owner.regula_heresy_growth_rate
		}

		if = {
			limit =  {
				var:regula_heresy_growth >= regula_heresy_growth_needed_for_member
			}

			set_variable = {
				name = regula_heresy_growth
				value = 0
			}
			regula_heresy_find_and_add_conspirator_effect = yes
		}
	}
}

# Updates the discontent measurement for the heresy story cycle,
# transitioning to open opposition if needed.
#
# scope = the heresy story cycle.
regula_heresy_update_discontent_effect = {
	if = {
		limit = {
			regula_heresy_story_in_secret_state_trigger = yes
		}

		change_variable = {
			name = regula_heresy_discontent
			add = story_owner.regula_heresy_discontent_rate
		}

		if = {
			limit = {
				var:regula_heresy_discontent >= regula_heresy_discontent_needed_for_open_oppostion
			}

			regula_heresy_story_begin_public_opposition_effect = yes
		}
	}
}

#############################
# Member Management Effects #
#############################
# Marks the scoped character as a heresy conspiracy member in growth stage
# of the conspiracy.
#
# scope = the character to make a conspirator.
# scope:regula_heresy_story = the conspiracy the character is joining.
# scope:regula_heresy_target = the target of the conspiracy.
regula_heresy_mark_character_as_conspirator_effect = {
	if = {
		limit = {
			scope:regula_heresy_story = {
				regula_heresy_story_in_public_state_trigger = yes
			}
		}
		regula_heresy_character_and_county_begin_public_opposition_effect = yes
	}
	else = {
		add_secret = {
			type = regula_heresy_conspirator_secret
			target = scope:regula_heresy_target
		}
	}

	# Mark this new member on the heresy story for tracking purposes.
	scope:regula_heresy_story = {
		add_to_variable_list = {
			name = regula_heresy_all_conspirators
			target = prev
		}
	}

	# If the character is not landed, and not already 'blocked_from_leaving',
	# then go ahead and block the character from leaving for a short duration
	# so that they don't join the heresy and then immediately leave it.
	# Uses the `blocked_from_leaving` flag which controls base game wandering
	# behavior.
	if = {
		limit = {
			is_landed = no
			NOT = { has_character_flag = blocked_from_leaving }
		}

		add_character_flag = {
			flag = blocked_from_leaving
			days = 180
		}
	}

	regula_heresy_story_debug_member_add_log_effect = yes
}

# Adds a new county character to be a member of the heresy conspiracy.
#
# scope = the county for which we are creating the peasant member.
# scope:regula_heresy_story = the conspiracy the character is joining.
# scope:regula_heresy_target = the target of the conspiracy.
regula_heresy_find_or_create_conspirator_for_county_effect = {
	save_temporary_scope_as = location_county

	# Pick county that heretical beliefs came from.
	if = {
		limit = {
			regula_heresy_potential_heresy_county_directly_trigger = yes
		}
		save_temporary_scope_as = belief_county
	}
	else = {
		random_title_to_title_neighboring_and_across_water_county = {
			limit = {
				regula_heresy_potential_heresy_county_directly_trigger = yes
			}
			save_temporary_scope_as = belief_county
		}
	}

	# First, attempt picking an existing pool character from the province who
	# is not already a guest somewhere.
	random_pool_character = {
		province = scope:location_county.title_province
		limit = {
			regula_heresy_potential_heresy_character_trigger = yes
			regula_heresy_conspirator_character_trigger = no
			is_foreign_court_or_pool_guest = no
		}

		weight = {
			base = 100
			regula_heresy_character_join_modifier = {
				TARGET = scope:regula_heresy_target
			}
		}

		save_scope_as = new_conspirator
	}

	# If we didn't find an existing pool character, go ahead and create
	# a new one.
	if = {
		limit = {
			NOT = { exists = scope:new_conspirator }
		}

		random_list = {
			1 = { # Peasant Leader
				create_character = {
					save_scope_as = new_conspirator
					template = regula_heresy_peasant_conspirator

					location = scope:location_county.title_province
					culture = scope:belief_county.culture
					faith = scope:belief_county.faith
				}
			}
			1 = { # Monk
				create_character = {
					save_scope_as = new_conspirator
					template = regula_heresy_monk_conspirator

					location = scope:location_county.title_province
					culture = scope:belief_county.culture
					faith = scope:belief_county.faith
				}
			}
			1 = { # Noble
				create_character = {
					save_scope_as = new_conspirator
					template = regula_heresy_noble_conspirator

					location = scope:location_county.title_province
					culture = scope:belief_county.culture
					faith = scope:belief_county.faith
				}
			}
		}

		# Save this character to the story so that we know to clean them up on
		# story completion if they are not otherwise handled.
		scope:regula_heresy_story = {
			add_to_variable_list = {
				name = regula_heresy_cleanup_characters
				target = scope:new_conspirator
			}
		}
	}

	scope:regula_heresy_story = {
		# Make this character a guest of one of the story owner's vassals.
		# Prefer more heretical vassals if possible.
		story_owner = {
			save_temporary_scope_as = heresy_story_owner
			random_vassal_or_below = {
				weight = {
					base = 1
					modifier = {
						factor = 5
						regula_heresy_potential_heresy_character_trigger = yes
						regula_heresy_conspirator_character_trigger = no
					}
					modifier = {
						factor = 10
						regula_heresy_potential_heresy_character_trigger = yes
						regula_heresy_conspirator_character_trigger = yes
					}
				}
				add_visiting_courtier = scope:new_conspirator
			}
		}
	}

	scope:new_conspirator = {
		regula_heresy_mark_character_as_conspirator_effect = yes
	}
}

# Cleans up any characters created as part of the heresy story who are not
# otherwise handled.
#
# scope = the story cycle to clean up.
regula_heresy_cleanup_generated_conspirators_effect = {
	# All created conspirators who haven't reached some
	# relevant-to-other-character state disappear.
	every_in_list = {
		variable = regula_heresy_cleanup_characters

		limit = {
			is_alive = yes
			is_landed = no
			is_courtier = no
			is_imprisoned = no
			is_regula_devoted_trigger = no
		}

		death = {
			death_reason = death_vanished
		}
	}

	clear_variable_list = regula_heresy_cleanup_characters
}

# Adds a conspirator to the scoped regula heresy story cycle, selecting from
# the pool of available heresy sources.
#
# This is tracked by simply giving the selected or created conspirator a
# regula_heresy_conspirator_secret targetting the story owner.
#
# scope = the story cycle to add a conspirator to.
regula_heresy_find_and_add_conspirator_effect = {
	save_temporary_scope_as = regula_heresy_story

	story_owner = {
		save_temporary_scope_as = regula_heresy_target
		random_list = {
			75 = { # Heresy from vassals or courtiers.
				trigger = {
					regula_heresy_any_potential_heresy_character_trigger = yes
				}

				# Attempt vassal first.
				random_vassal_or_below = {
					limit = {
						regula_heresy_potential_heresy_character_trigger = yes
						regula_heresy_conspirator_character_trigger = no
					}

					weight = {
						base = 100
						regula_heresy_character_join_modifier = {
							TARGET = scope:regula_heresy_target
						}
					}

					save_scope_as = heresy_character
				}

				# Otherwise, fall back on courtiers.
				if = {
					limit = {
						NOT = {
							exists = scope:heresy_character
						}
					}

					random_courtier = {
						limit = {
							regula_heresy_potential_heresy_character_trigger = yes
							regula_heresy_conspirator_character_trigger = no
							is_landed = no
						}

						weight = {
							base = 100
							regula_heresy_character_join_modifier = {
								TARGET = scope:regula_heresy_target
							}
						}

						save_scope_as = heresy_character
					}
				}

				scope:heresy_character = {
					regula_heresy_mark_character_as_conspirator_effect = yes
				}
			}
			25 = { # Heresy from counties
				trigger = {
					regula_heresy_any_potential_heresy_county_trigger = yes
				}

				random_realm_county = {
					limit = {
						regula_heresy_potential_heresy_county_including_neighbors_trigger = yes
					}

					regula_heresy_find_or_create_conspirator_for_county_effect = yes
				}
			}
			1 = { # Fallback NOOP
				trigger = {
					regula_heresy_any_potential_heresy_character_trigger = no
					regula_heresy_any_potential_heresy_county_trigger = no
				}
			}
		}
	}
}

# Imprisons a random capturable member of the heresy conspiracy story cycle.
#
# scope = the character target of the heresy conspiracy.
# SAVE_AS = the scope name to save the captured character as.
regula_heresy_apprehend_random_capturable_member_effect = {
	save_temporary_scope_as = heresy_target
	if = { # If secrets exist, that is the first place to look.
		limit = {
			any_targeting_secret = {
				secret_type = regula_heresy_conspirator_secret
				is_known_by = scope:heresy_target
				secret_owner = {
					is_imprisoned = no
				}
			}
		}

		random_targeting_secret = {
			limit = {
				secret_type = regula_heresy_conspirator_secret
				is_known_by = scope:heresy_target
				secret_owner = {
					is_imprisoned = no
				}
			}

			weight = {
				base = 100
				regula_heresy_character_capture_modifier = {
					CHARACTER = secret_owner
					HERESY_TARGET = scope:heresy_target
				}
			}

			secret_owner = {
				save_scope_as = $SAVE_AS$
			}

			regula_heresy_imprison_target_effect = {
				TARGET = scope:$SAVE_AS$
				IMPRISONER = scope:heresy_target
			}

			remove_secret = yes
		}
	}
	else = { # Otherwise, fall back on faction members.
		random_targeting_faction = {
			limit = {
				faction_is_at_war = no
				regula_faction_is_heresy_faction_trigger = yes
				any_faction_member = {
					is_imprisoned = no
				}
			}

			save_temporary_scope_as = heresy_faction
			random_faction_member = {
				limit = {
					is_imprisoned = no
				}

				weight = {
					base = 100
					regula_heresy_character_capture_modifier = {
						CHARACTER = this
						HERESY_TARGET = scope:heresy_target
					}
				}

				save_scope_as = $SAVE_AS$
				regula_heresy_imprison_target_effect = {
					TARGET = scope:$SAVE_AS$
					IMPRISONER = scope:heresy_target
				}

				leave_faction_with_cooldown_effect = {
					FACTION = scope:heresy_faction
					YEARS = 20
				}
			}
		}
	}

	# Increase threat whenever a member is apprehended.
	every_owned_story = {
		limit = {
			story_type = story_regula_heresy
		}

		change_variable = {
			name = regula_heresy_threat
			add = scope:$SAVE_AS$.regula_heresy_threat_gain_per_apprehended_member
		}
	}
}

# Imprisons the given member of a heresy conspiracy in the given IMPRISONER's
# dungeon.
#
# TARGET = the character being imprisoned.
# IMPRISONER = the character doing the imprisoning.
regula_heresy_imprison_target_effect = {
	$IMPRISONER$ = {
		add_opinion = {
			target = $TARGET$
			modifier = regula_heresy_conspirator_opinion
		}
	}

	$TARGET$ = {
		if = {
			limit = {
				is_imprisoned = no
			}
			hard_imprison_character_effect = {
				TARGET = $TARGET$
				IMPRISONER = $IMPRISONER$
			}
			hidden_effect = {
				change_prison_type = dungeon
			}
		}
	}
}

# Effect which handles selection of a heresy conspirator to be revealed to the
# magister during an interrogation.
#
# Output character is saved to scope:revealed_conspirator, though no character
# may be saved in cases where:
# - No other valid characters exist in the conspiracy.
# - We randomly decided to not reveal any other characters.
#
# scope:actor - the character initiating the interrogation (magister)
# scope:recipient - the character being interrogated
# scope:revealed_conspirator - output character to be revealed (or null)
regula_heresy_interrogation_pick_revealed_conspirator = {
	scope:actor = {
		random_owned_story = {
			limit = {
				story_type = story_regula_heresy
				regula_heresy_story_in_secret_state_trigger = yes
				is_target_in_variable_list = { 
					name = regula_heresy_all_conspirators
					target = scope:recipient
				}
			}

			random_list = {
				50 = { # Learn of a new, unknown member.
					trigger = {
						any_in_list = {
							variable = regula_heresy_all_conspirators

							is_alive = yes
							NOT = { this = scope:recipient }
							NOT = { is_imprisoned_by = scope:actor }
							any_secret = {
								secret_type = regula_heresy_conspirator_secret
								secret_target ?= scope:actor
								NOT = { is_known_by = scope:actor }
							}
						}
					}

					random_in_list = {
						variable = regula_heresy_all_conspirators

						limit = {
							is_alive = yes
							NOT = { this = scope:recipient }
							NOT = { is_imprisoned_by = scope:actor }
							any_secret = {
								secret_type = regula_heresy_conspirator_secret
								secret_target ?= scope:actor
								NOT = { is_known_by = scope:actor }
							}
						}

						save_scope_as = revealed_conspirator
					}
				}
				20 = { # Already Known
					trigger = {
						any_in_list = {
							variable = regula_heresy_all_conspirators

							is_alive = yes
							NOT = { this = scope:recipient }
							NOT = { is_imprisoned_by = scope:actor }
							any_secret = {
								secret_type = regula_heresy_conspirator_secret
								secret_target ?= scope:actor
								is_known_by = scope:actor
							}
						}
					}

					random_in_list = {
						variable = regula_heresy_all_conspirators

						limit = {
							is_alive = yes
							NOT = { this = scope:recipient }
							NOT = { is_imprisoned_by = scope:actor }
							any_secret = {
								secret_type = regula_heresy_conspirator_secret
								secret_target ?= scope:actor
								is_known_by = scope:actor
							}
						}

						save_scope_as = revealed_conspirator
					}
				}
				10 = { # Already Captured
					trigger = {
						any_in_list = {
							variable = regula_heresy_all_conspirators

							is_alive = yes
							NOT = { this = scope:recipient }
							is_imprisoned_by = scope:actor
						}
					}

					random_in_list = {
						variable = regula_heresy_all_conspirators

						limit = {
							is_alive = yes
							NOT = { this = scope:recipient }
							is_imprisoned_by = scope:actor
						}

						save_scope_as = revealed_conspirator
					}
				}
				20 = {} # None Found
			}
		}
	}
}

# Determines the result of a successful interrogation for a heretic
# interrogation. Specifically, determines the mode which should be used,
# saving said mode to $SAVE_SCOPE_AS$.
#
# Possible modes are:
# - flag:none_known - No active conspirators are discovered.
# - flag:already_captured - The conspirator discovered is already captured.
# - flag:already_known - The conspirator discovered is already known.
# - flag:success - A new conspirator was discovered.
#
# SAVE_SCOPE_AS - the output state determined.
#
# scope:actor - the character initiating the interrogation.
# scope:revealed_conspirator - the character to be revealed (may not exist)
regula_heresy_interrogation_result_effect = {
	if = { # Character doesn't know any conspirators.
		limit = {
			NOT = { exists = scope:revealed_conspirator }
		}

		save_scope_value_as = {
			name = $SAVE_SCOPE_AS$
			value = flag:none_known
		}
	}
	else_if = { # Already Imprisoned
		limit = {
			scope:revealed_conspirator = {
				is_imprisoned_by = scope:actor
			}
		}

		save_scope_value_as = {
			name = $SAVE_SCOPE_AS$
			value = flag:already_captured
		}
	}
	else_if = { # Not captured, but already known.
		limit = {
			scope:revealed_conspirator = {
				any_secret = {
					secret_type = regula_heresy_conspirator_secret
					secret_target ?= scope:actor
					is_known_by = scope:actor
				}
			}
		}

		save_scope_value_as = {
			name = $SAVE_SCOPE_AS$
			value = flag:already_known
		}
	}
	else_if = { # Character not captured and is not part of the conspiracy.
		limit = {
			scope:revealed_conspirator = {
				NOT = {
					any_secret = {
						secret_type = regula_heresy_conspirator_secret
						secret_target ?= scope:actor
					}
				}
			}
		}

		save_scope_value_as = {
			name = $SAVE_SCOPE_AS$
			value = flag:none_known
		}
	}
	else = {
		save_scope_value_as = {
			name = $SAVE_SCOPE_AS$
			value = flag:success
		}
	}
}

# Clean up effect used when heresy story is ending to flag any remaining known
# members as criminals.
#
# scope = the heresy story.
regula_heresy_flag_known_members_as_criminals_effect = {
	story_owner = {
		save_temporary_scope_as = heresy_target

		every_targeting_secret = {
			limit = {
				secret_type = regula_heresy_conspirator_secret
				is_known_by = scope:heresy_target
			}

			secret_owner = {
				save_temporary_scope_as = heresy_member
			}

			scope:heresy_target = {
				add_opinion = {
					target = scope:heresy_member
					modifier = regula_heresy_conspirator_opinion
				}
			}
		}

		every_targeting_faction = {
			limit = {
				regula_faction_is_heresy_faction_trigger = yes
			}

			every_faction_member = {
				save_temporary_scope_as = heresy_member
				scope:heresy_target = {
					add_opinion = {
						target = scope:heresy_member
						modifier = regula_heresy_conspirator_opinion
					}
				}
			}
		}
	}
}

# Effect which allows courtiers & guests to potentially leave their court at
# the end of a heresy cycle which ended in white peace.
#
# scope = the character potentially leaving the court they are in
regula_heresy_conspirator_leave_court_effect = {
	if = {
		limit = {
			is_landed = no
			is_imprisoned = no
			OR = {
				is_courtier = yes
				is_pool_guest = yes
				is_foreign_court_guest = yes
			}
		}

		# Even if the character doesn't end up leaving - they should no longer
		# be blocked from leaving by the conspiracy.
		if = {
			limit = {
				has_character_flag = blocked_from_leaving
			}
			remove_character_flag = blocked_from_leaving
		}

		random = {
			chance = 0

			# We only even consider leaving the court if our host is the
			# magister or a devoted. And our chance to leave is influenced by
			# boldness and rationality.
			modifier = {
				add = 80
				host ?= {
					has_trait = magister_trait_group
				}
			}
			modifier = {
				add = 50
				host ?= {
					is_regula_devoted_trigger = yes
				}
			}
			ai_value_modifier = {
				ai_boldness = -0.5
				ai_rationality = 0.5
			}

			if = { # Go home rather than start wandering
				limit = {
					is_foreign_court_guest = yes
				}
				return_to_court = yes
			}
			else = {
				host ?= {
					remove_courtier_or_guest = prev
				}
			}
		}
	}
}

########################################
# Public Opposition Transition Effects #
########################################
# Forces the scoped character to join the existing heresy faction against the
# target character.
#
# The heresy faction is assumed to exist when calling this effect.
#
# scope = the character beginning open resistance.
# scope:regula_heresy_target = the target of the heresy.
regula_heresy_character_join_heresy_faction_effect = {
	if = {
		limit = {
			scope:regula_heresy_target = {
				any_targeting_faction = {
					regula_faction_is_heresy_faction_trigger = yes
				}
			}
		}

		scope:regula_heresy_target = {
			random_targeting_faction = {
				limit = {
					regula_faction_is_heresy_faction_trigger = yes
				}
				save_temporary_scope_as = heresy_faction
			}
		}

		join_faction_skip_check = scope:heresy_faction

		every_secret = {
			limit = {
				secret_type = regula_heresy_conspirator_secret
			}
			remove_secret = yes
		}
	}
}

# Forces the scoped county to create (or join if one already exists) a heresy
# faction against the given target character.
#
# scope = the county beginning open resistance.
# scope:regula_heresy_target = the target of the heresy.
regula_heresy_county_create_or_join_heresy_faction_effect = {
	if = {
		limit = {
			scope:regula_heresy_target = {
				NOT = {
					any_targeting_faction = {
						regula_faction_is_heresy_faction_trigger = yes
					}
				}
			}
		}

		title_create_faction = {
			type = regula_heresy_faction
			target = scope:regula_heresy_target
		}
	}
	else = {
		scope:regula_heresy_target = {
			random_targeting_faction = {
				limit = {
					regula_faction_is_heresy_faction_trigger = yes
				}
				save_temporary_scope_as = heresy_faction
			}
		}

		if = {
			limit = {
				NOT = {
					any_title_joined_faction = {
						this = scope:heresy_faction
					}
				}
			}
			title_join_faction = scope:heresy_faction
		}
	}
}

# Picks a random heresy source county to join the heresy faction (or create it
# if one doesn't yet exist).
#
# This will specifically try to find counties which are valid heresy faction
# members, aren't already in the faction, and whose liege or above are not
# in the faction.
#
# Of special note here - the weighting of the county selection is done to
# prioritize a few different factors:
# 1 - County neighbors a county already in the faction.
# 2 - County is on the border of the realm.
# 3 - County is adjacent to other heretical counties.
#
# Finally, we downweight counties which are not directly heretical.
#
# The overall effect of this is that these counties which are selected for
# unlanded conspiracy members tend to blob up rather than being scattered
# across the realm and tend to have at least one county on the border of the
# realm.
#
# scope = the target character of the heresy storyline.
# scope:regula_heresy_target = same as scope
regula_heresy_pick_county_to_join_heresy_faction_effect = {
	random_realm_county = {
		limit = {
			# Must be a valid county to join the faction.
			regula_faction_heresy_valid_county_trigger = {
				TARGET = scope:regula_heresy_target
			}

			# Must not pick a county down the tree from a conspiracy member.
			holder = {
				regula_heresy_conspirator_character_trigger = no
				NOT = {
					any_liege_or_above = {
						regula_heresy_conspirator_character_trigger = yes
					}
				}
			}

			# Must not already be in a heresy faction.
			NOT = {
				any_title_joined_faction = {
					regula_faction_is_heresy_faction_trigger = yes
				}
			}
		}

		weight = {
			base = 1

			# Strongly prefer counties neighboring those already in the
			# faction.
			modifier = {
				factor = 1000
				any_neighboring_county = {
					any_title_joined_faction = {
						regula_faction_is_heresy_faction_trigger = yes
					}
				}
			}

			# Even more so if we are adjacent to multiple faction members.
			# Tries to make heresy territory typically blobby rather than
			# a chain.
			modifier = {
				factor = 100
				any_neighboring_county = {
					count >= 2
					any_title_joined_faction = {
						regula_faction_is_heresy_faction_trigger = yes
					}
				}
			}

			# Less strongly prefer counties on the border of the realm
			# or with neighboring heretical counties.
			modifier = {
				factor = 20
				any_title_to_title_neighboring_and_across_water_county = {
					OR = {
						regula_faction_heresy_valid_county_trigger = {
							TARGET = scope:regula_heresy_target
						}
						NOT = { prev.holder.top_liege = holder.top_liege }
					}
				}
			}

			# If the county is not directly heretical, then downweight
			# it in the selection. We still want blobing & bordering,
			# but prefer to use directly heretical from among those.
			modifier = {
				factor = 0.5
				NOT = {
					regula_heresy_potential_heresy_county_directly_trigger = yes
				}
			}
		}

		regula_heresy_county_create_or_join_heresy_faction_effect = yes
	}
}

# Performs logic needed to have a character & some associated county join the
# heresy opposition faction.
#
# scope = the character joining the public opposition.
# scope:regula_heresy_target = the target of the heresy story.
regula_heresy_character_and_county_begin_public_opposition_effect = {
	if = {
		limit = {
			is_landed = yes
		}

		capital_county = {
			regula_heresy_county_create_or_join_heresy_faction_effect = yes
		}
	}
	else = {
		scope:regula_heresy_target = {
			regula_heresy_pick_county_to_join_heresy_faction_effect = yes
		}
	}

	regula_heresy_character_join_heresy_faction_effect = yes
}

# Starts public opposition for a regula heresy conspiracy.
#
# This typically will take the form of conspirators forming a faction against
# the target.
#
# scope = the regula heresy conspiracy story
regula_heresy_story_begin_public_opposition_effect = {
	set_variable = {
		name = regula_heresy_state
		value = flag:faction_active
	}

	save_temporary_scope_as = regula_heresy_story
	story_owner = {
		save_scope_as = regula_heresy_target
		set_local_variable = {
			name = unlanded_conspirators
			value = 0
		}

		# Move characters & associated counties into the faction.
		every_targeting_secret = {
			limit = {
				secret_type = regula_heresy_conspirator_secret
			}

			secret_owner = {
				regula_heresy_character_and_county_begin_public_opposition_effect = yes
			}
		}

		# Finally, add discontent to the faction based on the heresy story's
		# current discontent. This adds a max of 80 discontent to the faction
		# at boil over point, scaled down linearly based fraction of boil over
		# disconent level reached.
		every_targeting_faction = {
			limit = {
				regula_faction_is_heresy_faction_trigger = yes
			}

			add_faction_discontent = {
				value = 80
				multiply = {
					value = scope:regula_heresy_story.var:regula_heresy_discontent
					divide = regula_heresy_discontent_needed_for_open_oppostion
					max = 1
				}
			}
		}
	}
}

############################
# State Management Effects #
############################
# Begins a new heresy story cycle for the scoped character, and adds a
# character to the cycle.
#
# scope = the target of the heresy story cycle
regula_heresy_start_story_cycle_effect = {
	create_story = {
		type = story_regula_heresy
	}
	random_owned_story = {
		limit = { story_type = story_regula_heresy }
		regula_heresy_find_and_add_conspirator_effect = yes
	}
}

# Transitions the active heresy story to the heretic victor state.
#
# scope = the faction ending in heretic victory.
regula_heresy_transition_to_faction_victory = {
	faction_target = {
		every_owned_story = {
			limit = {
				story_type = story_regula_heresy
			}

			set_variable = {
				name = regula_heresy_state
				value = flag:faction_victory
			}
		}
	}
}

# Transitions the active heresy story to the heretic white peace state.
#
# scope = the faction ending in heretic defeat.
regula_heresy_transition_to_faction_white_peace = {
	faction_target = {
		every_owned_story = {
			limit = {
				story_type = story_regula_heresy
			}

			set_variable = {
				name = regula_heresy_state
				value = flag:faction_peace
			}
		}
	}
}

# Transitions the active heresy story to the heretic defeat state.
#
# scope = the faction ending in heretic defeat.
regula_heresy_transition_to_faction_defeat = {
	faction_target = {
		every_owned_story = {
			limit = {
				story_type = story_regula_heresy
			}

			set_variable = {
				name = regula_heresy_state
				value = flag:faction_defeat
			}
		}
	}
}

# Simply ends the active heresy story once the faction is being torn down.
#
# scope = the faction ending in heretic defeat.
regula_heresy_faction_teardown = {
	faction_target = {
		every_owned_story = {
			limit = {
				story_type = story_regula_heresy
			}
			end_story = yes
		}
	}
}

########################
# Deprograming Effects #
########################
# Forces conversion of a given character, un-charming them if possible,
# and changing their faith to the faith of the character who is converting
# them.
#
# scope = the character being converted
# CONVERTER = the character doing conversion
regula_heresy_force_convert_character_effect = {
	save_temporary_scope_as = convertee

	# Remove any charmed statuses which can be removed.
	if = {
		limit = {
			is_regula_devoted_trigger = yes
			NOR = {
				has_trait = contubernalis
				has_trait = regula_undying
			}
		}

		remove_trait = domina
		remove_trait = familia_paelex
		remove_trait = paelex
		remove_trait = mulsa
		remove_trait = tropaeum
		remove_trait = orba
		remove_trait = retired_paelex
		remove_trait = sigillum

		if = {
			limit = {
				magister_alive_trigger = yes
			}

			add_opinion = {
				modifier = regula_heresy_uncharmed_opinion
				target = global_var:magister_character
			}
		}
	}

	# Now, if the character is regula or crypto regula, go ahead
	# and convert them.
	if = {
		limit = {
			OR = {
				is_regula_trigger = yes
				is_crypto_regula_trigger = yes
			}
		}

		random_list = {
			100 = {
				opinion_modifier = {
					who = scope:convertee
					opinion_target = $CONVERTER$
					multiplier = 1
				}

				if = {
					limit = {
						is_regula_trigger = yes
					}
					set_character_faith_with_conversion = $CONVERTER$
				}
				else = {
					remove_character_secret_faith = yes
				}
			}
			100 = {
				trigger = {
					magister_alive_trigger = yes
				}

				opinion_modifier = {
					who = scope:convertee
					opinion_target = global_var:magister_character
					multiplier = 1
				}

				if = {
					limit = {
						is_regula_trigger = yes
					}
					faith = {
						save_temporary_scope_as = convertee_secret_faith
					}
					set_character_faith = $CONVERTER$.faith
					convert_to_regula_secretly_effect = {
						FAITH = scope:convertee_secret_faith
					}
				}
				else = {
					secret_faith = {
						save_temporary_scope_as = convertee_secret_faith
					}
					convert_to_regula_secretly_effect = {
						FAITH = scope:convertee_secret_faith
					}
				}
			}
		}
	}
}

# Forces conversion of a given county, changing their faith to the faith of the
# character who is converting them.
#
# scope = the county being converted
# CONVERTER = the character (or county) doing conversion
regula_heresy_force_convert_county_effect = {
	if = {
		limit = {
			is_regula_trigger = yes
		}

		set_county_faith = $CONVERTER$.faith
	}
}

###################################
# Councillor Notification Effects #
###################################
# Effect which sends any needed events to notify the player a heresy story
# cycle being discovered in their realm.
#
# Note: Discovery events will only be sent if the story owner has an active
# inquisitor.
#
# scope = the discovered story cycle.
regula_heresy_send_discover_event_effect = {
	if = {
		limit = {
			story_owner = {
				any_councillor = {
					has_council_position = councillor_inquisitor
				}
			}
		}

		save_scope_as = regula_heresy_story
		story_owner = {
			save_scope_as = councillor_liege
			random_councillor = {
				limit = {
					has_council_position = councillor_inquisitor
				}
				save_scope_as = councillor
			}
			trigger_event = regula_council_event.5000 # Heresy Discovered
		}
	}
}

# Effect which sends any needed events to notify the player a heresy story
# cycle moving into open opposition phase.
#
# Note: Events will only be sent if the story owner has an active
# inquisitor.
#
# scope = the faction which has been started
regula_heresy_send_open_opposition_event_effect = {
	if = {
		limit = {
			faction_target = {
				any_councillor = {
					has_council_position = councillor_inquisitor
				}
			}
		}

		save_scope_as = regula_heresy_faction
		faction_target = {
			save_scope_as = councillor_liege
			random_councillor = {
				limit = {
					has_council_position = councillor_inquisitor
				}
				save_scope_as = councillor
			}
			trigger_event = regula_council_event.5005 # Heresy Public Opposition
		}
	}
}

# Effect which sends any needed ending events to notify the player of the
# ending of the heresy story cycle.
#
# Note: Ending events will only be sent if the story owner has an active
# inquisitor.
#
# scope = the ending story cycle.
regula_heresy_send_end_event_effect = {
	if = {
		limit = {
			story_owner = {
				any_councillor = {
					has_council_position = councillor_inquisitor
				}
			}
		}

		# Save event scopes.
		story_owner = {
			save_scope_as = councillor_liege
			random_councillor = {
				limit = {
					has_council_position = councillor_inquisitor
				}
				save_scope_as = councillor
			}
		}
		scope:councillor = {
			set_variable = {
				name = final_heresy_state
				value = prev.var:regula_heresy_state
				days = 1
			}
		}

		if = {
			limit = {
				scope:councillor.var:final_heresy_state = flag:faction_peace
			}

			story_owner = {
				trigger_event = regula_council_event.5015 # Heresy Ended - White Peace
			}
		}
		else_if = {
			limit = {
				scope:councillor.var:final_heresy_state = flag:faction_victory
			}

			story_owner = {
				trigger_event = regula_council_event.5020 # Heresy Ended - Heretic Victory
			}
		}
		else_if = {
			limit = {
				# As long as state isn't the 'silent - nothing to share' state,
				# then send regula victory end event.
				NOT = { scope:councillor.var:final_heresy_state = flag:silent_end }
			}

			story_owner = {
				trigger_event = regula_council_event.5010 # Heresy Ended - Magister Victory
			}
		}
	}
}
