﻿yearly_global_pulse = {
    on_actions = {
        riseandfall_check_puppet_regency
        riseandfall_warlord_expire_legacy
        riseandfall_warlord
        riseandfall_marry_male_puppet_master_target
        riseandfall_marry_female_puppet_master_target
        riseandfall_split_title_monitor
    }
}

# Temporary Rebel banners expire even when the optional realm-crisis system is
# disabled; this also governs Puppet Masters who choose the legacy Warlord path.
riseandfall_warlord_expire_legacy = {
    effect = {
        every_ruler = {
            limit = {
                has_character_flag = rf_warlord_legacy
                riseandfall_is_any_warlord_trigger = yes
            }
            if = {
                limit = {
                    NOT = { has_variable = rf_warlord_legacy_expiry }
                    NOT = { has_variable = rf_warlord_legacy_expiry_initialized }
                }
                set_variable = { name = rf_warlord_legacy_expiry value = 1 years = 5 }
                set_variable = { name = rf_warlord_legacy_expiry_initialized value = 1 }
            }
            else_if = {
                limit = {
                    has_variable = rf_warlord_legacy_expiry_initialized
                    NOT = { has_variable = rf_warlord_legacy_expiry }
                }
                riseandfall_warlord_retire_legacy_se = yes
            }
        }
    }
}

random_yearly_everyone_pulse = {
    on_actions = {
        # Give each eligible realm its own incident day instead of clustering rolls on January 1.
        riseandfall_low_stability_roll
        riseandfall_force_diadochi_wars
    }
}

on_imprison = {
    on_actions = {
        riseandfall_warlord_imprisoned
    }
}

on_death = {
    on_actions = {
        riseandfall_preserve_puppet_master_successor_on_death
        riseandfall_mark_puppet_succession_on_death
    }
}

# Preserve the ruler's native diarchy successor before a dead Puppet Master is
# removed and the diarchy temporarily becomes inactive.
riseandfall_preserve_puppet_master_successor_on_death = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        riseandfall_preserve_puppet_master_successor_on_death_se = yes
    }
}

# Puppet Master resync: diarchy changes are rare and can leave the court
# position out of step with the active puppet master until the pulse fallback.
on_entered_diarchy = {
    on_actions = {
        riseandfall_check_current_puppet_regency
    }
}

on_left_diarchy = {
    on_actions = {
        riseandfall_check_current_puppet_regency
    }
}

on_diarch_change = {
    on_actions = {
        riseandfall_check_current_puppet_regency
    }
}

on_diarch_designation = {
    on_actions = {
        riseandfall_check_current_puppet_regency
    }
}

on_title_gain = {
    on_actions = {
        riseandfall_prepare_puppet_succession_on_title_gain
        riseandfall_check_current_puppet_regency
        riseandfall_warlord_loyal_on_liege_grant
        riseandfall_warlord_title_cleanup
        riseandfall_successor_primary_title_sync
    }
}

# A claimant/pretender who wins a war can become the new independent holder
# without using on_title_gain_inheritance. Queue the same Puppet Master choice
# used for an inherited realm after the title transfer has settled.
riseandfall_prepare_puppet_succession_on_title_gain = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        is_landed = yes
        is_independent_ruler = yes
        NOT = { has_character_flag = rf_puppet_succession_event_queued }
        exists = scope:title
        exists = scope:previous_holder
        primary_title = {
            this = scope:title
        }
        scope:previous_holder = {
            is_independent_ruler = yes
            OR = {
                has_diarchy_type = puppet_regency
                has_character_flag = rf_puppet_regency_persistent
            }
        }
    }
    effect = {
        clear_saved_scope = rf_civil_war_puppet_master
        scope:previous_holder = {
            if = {
                limit = {
                    has_variable = rf_puppet_regency_diarch
                }
                var:rf_puppet_regency_diarch = {
                    save_scope_as = rf_civil_war_puppet_master
                }
            }
            if = {
                limit = {
                    NOT = { exists = scope:rf_civil_war_puppet_master }
                    has_active_diarchy = yes
                    exists = diarch
                }
                diarch = {
                    save_scope_as = rf_civil_war_puppet_master
                }
            }
        }
        if = {
            limit = {
                exists = scope:rf_civil_war_puppet_master
                scope:rf_civil_war_puppet_master = {
                    is_alive = yes
                    is_adult = yes
                    is_imprisoned = no
                    is_incapable = no
                }
            }
            riseandfall_clear_puppet_succession_pending_se = yes
            add_character_flag = { flag = rf_puppet_succession_pending days = 30 }
            add_character_flag = { flag = rf_puppet_succession_event_queued days = 30 }
            set_variable = { name = rf_puppet_succession_predecessor value = scope:previous_holder }
            set_variable = { name = rf_puppet_succession_diarch value = scope:rf_civil_war_puppet_master }
            if = {
                limit = { scope:previous_holder = { has_variable = riseandfall_puppet_regency_years } }
                set_variable = { name = rf_puppet_succession_years value = scope:previous_holder.var:riseandfall_puppet_regency_years }
            }
            trigger_event = {
                id = riseandfall_puppet_master.110
                days = 1
            }
        }
        clear_saved_scope = rf_civil_war_puppet_master
    }
}

on_title_gain_inheritance = {
    on_actions = {
        riseandfall_resolve_puppet_succession_on_inheritance
        riseandfall_check_current_puppet_regency
        riseandfall_warlord_inherit_vassal_trait
        riseandfall_warlord_title_cleanup
        riseandfall_warlord_inherited_legacy
        riseandfall_successor_primary_title_sync
    }
}

on_title_lost = {
    on_actions = {
        riseandfall_warlord_title_cleanup
    }
}

# Preserve an active Warlord vassal's alignment when their landed title passes
# to an heir. Independent inherited realms are handled separately as legacy.
riseandfall_warlord_inherit_vassal_trait = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        is_landed = yes
        is_independent_ruler = no
        exists = scope:previous_holder
        scope:previous_holder = {
            OR = {
                has_trait = warlord
                has_trait = loyalwarlord
            }
        }
        exists = liege
        liege = {
            exists = primary_title
            primary_title = { has_variable = rf_warlord_era_active }
        }
    }
    effect = {
        if = {
            limit = { scope:previous_holder = { has_trait = loyalwarlord } }
            riseandfall_warlord_become_loyal = yes
        }
        else_if = {
            limit = { scope:previous_holder = { has_trait = warlord } }
            riseandfall_warlord_become_warlord = yes
        }
    }
}

riseandfall_force_diadochi_wars = {
    trigger = {
        is_ai = yes
    }
    effect = {
        riseandfall_diadochi_wars_se = yes
    }
}


riseandfall_low_stability_roll = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        is_landed = yes
        is_independent_ruler = yes
        # Low-stability incidents are reserved for duchy-tier realms and above.
        primary_title.tier >= tier_duchy
    }
    effect = {
        # Root is the ruler supplied by random_yearly_everyone_pulse.
        save_scope_as = ruler_low_stability
        riseandfall_low_stability_roll_se = yes
    }
}

riseandfall_check_puppet_regency = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        riseandfall_check_puppet_regency_end = yes
        # Match the Warlord succession flow: reconcile on the actual ruler
        # scope, not on the outer/global on-action scope.
        every_ruler = {
            limit = {
                is_landed = yes
                exists = primary_title
                OR = {
                    has_diarchy_type = puppet_regency
                    has_realm_law = riseandfall_puppet_regency_partition_succession_law
                    has_realm_law = riseandfall_puppet_regency_single_heir_succession_law
                }
            }
            riseandfall_puppet_regency_reconcile_succession_se = yes
        }
    }
}

# Code diarchy/title hooks provide the affected liege as root. Repair only that
# character; the yearly handler above owns the whole-world safety scan.
riseandfall_check_current_puppet_regency = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        OR = {
            has_diarchy_type = puppet_regency
            has_character_flag = rf_puppet_regency_persistent
            employs_court_position = riseandfall_puppet_master_court_position
        }
    }
    effect = {
        riseandfall_maintain_current_puppet_regency_se = yes
        if = {
            limit = {
                is_landed = yes
                exists = primary_title
                OR = {
                    has_diarchy_type = puppet_regency
                    has_realm_law = riseandfall_puppet_regency_partition_succession_law
                    has_realm_law = riseandfall_puppet_regency_single_heir_succession_law
                }
            }
            riseandfall_puppet_regency_reconcile_succession_se = yes
        }
    }
}

riseandfall_mark_puppet_succession_on_death = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        is_independent_ruler = yes
        has_diarchy_type = puppet_regency
        has_active_diarchy = yes
    }
    effect = {
        # Death fires before inheritance has fully settled; mark the likely heir
        # and resolve the puppet succession after title inheritance.
        clear_saved_scope = rf_dying_puppet_master
        if = {
            limit = { exists = diarch }
            diarch = { save_scope_as = rf_dying_puppet_master }
        }
        if = {
            limit = {
                exists = primary_heir
                primary_heir = { is_alive = yes }
            }
            primary_heir = {
                riseandfall_clear_puppet_succession_pending_se = yes
                add_character_flag = { flag = rf_puppet_succession_pending days = 30 }
                set_variable = { name = rf_puppet_succession_predecessor value = root }
                if = {
                    limit = { exists = scope:rf_dying_puppet_master }
                    set_variable = { name = rf_puppet_succession_diarch value = scope:rf_dying_puppet_master }
                }
                if = {
                    limit = { root = { has_variable = riseandfall_puppet_regency_years } }
                    set_variable = { name = rf_puppet_succession_years value = root.var:riseandfall_puppet_regency_years }
                }
                if = { limit = { is_landed = yes } add_character_flag = { flag = rf_puppet_succession_heir_was_landed days = 30 } }
                if = { limit = { root = { government_has_mechanic = administrative } } add_character_flag = { flag = rf_puppet_succession_predecessor_admin days = 30 } }
            }
        }
        else_if = {
            limit = {
                exists = player_heir
                player_heir = { is_alive = yes }
            }
            player_heir = {
                riseandfall_clear_puppet_succession_pending_se = yes
                add_character_flag = { flag = rf_puppet_succession_pending days = 30 }
                set_variable = { name = rf_puppet_succession_predecessor value = root }
                if = {
                    limit = { exists = scope:rf_dying_puppet_master }
                    set_variable = { name = rf_puppet_succession_diarch value = scope:rf_dying_puppet_master }
                }
                if = {
                    limit = { root = { has_variable = riseandfall_puppet_regency_years } }
                    set_variable = { name = rf_puppet_succession_years value = root.var:riseandfall_puppet_regency_years }
                }
                if = { limit = { is_landed = yes } add_character_flag = { flag = rf_puppet_succession_heir_was_landed days = 30 } }
                if = { limit = { root = { government_has_mechanic = administrative } } add_character_flag = { flag = rf_puppet_succession_predecessor_admin days = 30 } }
            }
        }
        clear_saved_scope = rf_dying_puppet_master
    }
}

riseandfall_resolve_puppet_succession_on_inheritance = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        has_character_flag = rf_puppet_succession_pending
        has_variable = rf_puppet_succession_predecessor
        exists = scope:previous_holder
        var:rf_puppet_succession_predecessor ?= scope:previous_holder
        is_landed = yes
        is_independent_ruler = yes
        NOT = { has_character_flag = rf_puppet_succession_event_queued }
    }
    effect = {
        if = {
            limit = {
                has_active_diarchy = yes
                NOT = { has_diarchy_type = puppet_regency }
            }
            riseandfall_clear_puppet_succession_pending_se = yes
        }
        else_if = {
            limit = {
                OR = {
                    has_character_flag = rf_puppet_succession_heir_was_landed
                    has_character_flag = rf_puppet_succession_predecessor_admin
                    government_has_mechanic = administrative
                }
            }
            add_character_flag = { flag = rf_puppet_succession_event_queued days = 30 }
            trigger_event = { id = riseandfall_puppet_master.110 delayed = yes }
        }
        else = {
            riseandfall_accept_puppet_succession_status_quo_se = yes
            riseandfall_clear_puppet_succession_pending_se = yes
        }
    }
}


riseandfall_warlord = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        # Cleanup: handle unlanded/independent warlords
        riseandfall_warlord_cleanup_se = yes

        # Reconcile temporary family succession laws after deaths, title
        # transfers, and other paths that can remove a Rebel Warlord.
        every_ruler = {
            limit = {
                is_landed = yes
                exists = primary_title
            }
            riseandfall_warlord_reconcile_succession_se = yes
        }

        # Evaluate each independent realm once. The count and territory share
        # cover direct Warlords and their full subrealms.
        every_independent_ruler = {
            limit = {
                is_landed = yes
            }
            riseandfall_warlord_refresh_crisis_strength_se = yes
            if = {
                limit = {
                    exists = primary_title
                    primary_title = { has_variable = rf_warlord_era_active }
                    any_vassal = {
                        is_landed = yes
                        riseandfall_is_active_warlord_trigger = yes
                    }
                }
                # Keep an already tracked era normalized and renew the legal
                # basis for vanilla AI suppression. Traits alone must never
                # recreate an era after its title marker has been cleared.
                riseandfall_warlord_mark_era_active_se = yes
                every_vassal = {
                    limit = {
                        is_landed = yes
                        riseandfall_is_active_warlord_trigger = yes
                    }
                    riseandfall_warlord_renew_liege_reason_se = yes
                }
            }
            # While the title marker exists, every direct landed vassal must
            # choose either the Rebel or Loyal Warlord camp. This also catches
            # newly granted, transferred, or otherwise newly arrived vassals.
            if = {
                limit = {
                    exists = primary_title
                    primary_title = { has_variable = rf_warlord_era_active }
                }
                primary_title = {
                    if = {
                        limit = { NOT = { has_variable = rf_warlord_era_age_initialized } }
                        set_variable = { name = rf_warlord_loyal_victory_locked value = 1 years = 10 }
                        set_variable = { name = rf_warlord_era_age_initialized value = 1 }
                    }
                }
                riseandfall_warlord_notify_vassals = yes
            }
            every_vassal = {
                limit = {
                    is_ai = yes
                    is_landed = yes
                    riseandfall_is_active_warlord_trigger = yes
                }
                riseandfall_warlord_ai_reconsider_se = yes
            }
            # Alignment changes can alter both sides' shares, so recalculate
            # before checking the loyal 51% victory and the empty-era fallback.
            riseandfall_warlord_refresh_crisis_strength_se = yes
            riseandfall_warlord_try_loyal_victory_se = yes
            riseandfall_warlord_try_end_era_se = yes
        }
    }
}

# root = recipient, scope:title = gained title, scope:previous_holder = granter.
# This only catches a real liege grant, not inheritance or conquest.
riseandfall_warlord_loyal_on_liege_grant = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
        is_landed = yes
        is_independent_ruler = no
        exists = scope:title
        scope:title.tier >= tier_county
        exists = scope:previous_holder
        liege = scope:previous_holder
        liege = {
            exists = primary_title
            primary_title = { has_variable = rf_warlord_era_active }
        }
    }
    effect = {
        riseandfall_warlord_become_loyal = yes
    }
}

# Lightweight cleanup used by on_title_gain / on_title_gain_inheritance / on_title_lost
# Only enforces warlord trait consistency — never fires events
riseandfall_warlord_title_cleanup = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        riseandfall_warlord_cleanup_se = yes
    }
}

# An inherited active-era title becoming a secondary title carries its banners
# as historical legacy, without activating a crisis in the new ruler's realm.
riseandfall_warlord_inherited_legacy = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        riseandfall_warlord_mark_inherited_legacy_se = yes
    }
}

riseandfall_successor_primary_title_sync = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        riseandfall_realm_split_migrate_successor_primary_title_se = yes
    }
}

# Rise and Fall: respond to imprison actions
# root = prisoner, scope:imprisoner = the character who imprisoned them
# If a warlord is imprisoned by their liege, remove the warlord trait so they stop behaving as an independent warlord
# Call the scripted effect which handles warlord trait removal when a liege imprisons a vassal
riseandfall_warlord_imprisoned = {
    effect = {
        # root = prisoner, scope:imprisoner = the character who imprisoned them
        # Call the scripted effect which handles warlord trait removal when a liege imprisons a vassal
        riseandfall_warlord_imprisoned_se = yes
    }
}


# On_actions for puppet masters (diarchs): AI-only unlanded diarchs should be given spouses by their liege's court.
# We iterate each ruler with a puppet_regency diarchy and pick any courtier who is that ruler's diarch, then call the marriage scripted effects.
riseandfall_marry_male_puppet_master_target = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        every_ruler = {
            limit = { has_diarchy_type = puppet_regency }
            save_scope_as = liege
            every_courtier = {
                limit = {
                    is_diarch_of_target = scope:liege
                    is_ai = yes
                    is_landed = no
                    is_ruler = no
                    NOT = { has_trait_with_flag = can_not_marry }
                    is_male = yes
                    is_adult = yes
                    is_married = no
                    is_betrothed = no
                }
                save_scope_as = diarch_candidate
                # call the scripted effect on the diarch character (root)
                riseandfall_marry_puppet_master_male_se = yes
            }
        }
    }
}

riseandfall_marry_female_puppet_master_target = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        every_independent_ruler = {
            limit = { has_diarchy_type = puppet_regency }
            save_scope_as = liege
            every_courtier = {
                limit = {
                    is_diarch_of_target = scope:liege
                    is_ai = yes
                    is_landed = no
                    is_ruler = no
                    NOT = { has_trait_with_flag = can_not_marry }
                    is_female = yes
                    is_adult = yes
                    is_married = no
                    is_betrothed = no
                }
                save_scope_as = diarch_candidate
                # call the scripted effect on the diarch character (root)
                riseandfall_marry_puppet_master_female_se = yes
            }
        }
    }
}

riseandfall_split_title_monitor = {
    trigger = {
        has_game_rule = riseandfall_low_stability_events_enabled
    }
    effect = {
        every_ruler = {
            limit = {
                is_landed = yes
                exists = primary_title
            }
            save_scope_as = rf_ruler
            scope:rf_ruler = {
                riseandfall_split_title_monitor_cleanup_se = yes
            }
        }
    }
}
