﻿##########################
# Rise and Fall - Dynamic Story Mode
# Campaign director for world climate, story roles, collapse pressure, and successor grace.

riseandfall_story_world_climate_se = {
    # Yearly campaign read: this is the director's "table state" before individual
    # rulers are scored. World climate is weighted by independent realm size, so
    # tiny unstable realms do not outweigh the actual powers shaping the map.
    set_global_variable = { name = riseandfall_story_world_eligible_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_stable_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_unstable_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_risky_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_crisis_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_empire_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_hegemony_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_blob_count value = 0 }
    set_global_variable = { name = riseandfall_story_world_stable_pct value = 0 }
    set_global_variable = { name = riseandfall_story_world_unstable_pct value = 0 }
    set_global_variable = { name = riseandfall_story_world_risky_pct value = 0 }
    set_global_variable = { name = riseandfall_story_world_crisis_pct value = 0 }
    set_global_variable = { name = riseandfall_story_world_pressure value = 0 }
    set_global_variable = { name = riseandfall_story_world_climate value = 0 }
    set_global_variable = { name = riseandfall_world_total value = 0 }
    set_global_variable = { name = riseandfall_world_total_development value = 0 }

    if = {
        limit = { has_game_rule = riseandfall_dynamic_story_mode_forced }
    }

    every_independent_ruler = {
        limit = { is_landed = yes }
        change_global_variable = { name = riseandfall_world_total add = realm_size }
        save_scope_as = rf_story_development_ruler
        set_variable = { name = riseandfall_rs_total_development value = 0 }
        every_realm_county = {
            scope:rf_story_development_ruler = {
                change_variable = { name = riseandfall_rs_total_development add = prev.development_level }
            }
        }
        change_global_variable = { name = riseandfall_world_total_development add = var:riseandfall_rs_total_development }
    }
    if = { limit = { global_var:riseandfall_world_total < 1 } set_global_variable = { name = riseandfall_world_total value = 1 } }
    if = { limit = { global_var:riseandfall_world_total_development < 1 } set_global_variable = { name = riseandfall_world_total_development value = 1 } }

    every_independent_ruler = {
        limit = {
            is_landed = yes
            has_variable = riseandfall_realm_stability_score
        }
        change_global_variable = { name = riseandfall_story_world_eligible_count add = realm_size }

        # Stability bands mirror the low-stability event curve. The risk estimate
        # is local to Story Mode so the world read does not depend on stale tooltip vars.
        set_variable = { name = tmp_story_low_threshold value = 30 }
        if = { limit = { highest_held_title_tier >= tier_duchy } set_variable = { name = tmp_story_low_threshold value = 35 } }
        if = { limit = { highest_held_title_tier >= tier_kingdom } set_variable = { name = tmp_story_low_threshold value = 40 } }
        if = { limit = { highest_held_title_tier >= tier_empire } set_variable = { name = tmp_story_low_threshold value = 45 } }
        if = { limit = { highest_held_title_tier >= tier_hegemony } set_variable = { name = tmp_story_low_threshold value = 50 } }
        set_variable = { name = tmp_story_crisis_threshold value = var:tmp_story_low_threshold }
        change_variable = { name = tmp_story_crisis_threshold add = -15 }
        set_variable = { name = tmp_story_stable_threshold value = var:tmp_story_low_threshold }
        change_variable = { name = tmp_story_stable_threshold add = 30 }
        set_variable = { name = tmp_story_low_event_diff value = var:tmp_story_low_threshold }
        set_variable = { name = tmp_story_current_stability value = var:riseandfall_realm_stability_score }
        change_variable = { name = tmp_story_current_stability multiply = -1 }
        change_variable = { name = tmp_story_low_event_diff add = var:tmp_story_current_stability }
        clamp_variable = { name = tmp_story_low_event_diff min = 0 max = 50 }
        set_variable = { name = tmp_story_low_event_chance value = 0 }
        if = {
            limit = { var:riseandfall_realm_stability_score > var:tmp_story_low_threshold }
            set_variable = { name = tmp_story_low_event_chance value = 0 }
        }
        else = {
            set_variable = { name = tmp_story_low_event_sq value = var:tmp_story_low_event_diff }
            change_variable = { name = tmp_story_low_event_sq multiply = var:tmp_story_low_event_diff }
            set_variable = { name = tmp_story_low_event_chance value = var:tmp_story_low_event_sq }
            change_variable = { name = tmp_story_low_event_chance multiply = 100 }
            change_variable = { name = tmp_story_low_event_chance divide = var:tmp_story_low_threshold }
            change_variable = { name = tmp_story_low_event_chance divide = var:tmp_story_low_threshold }
            if = { limit = { AND = { var:tmp_story_low_event_diff > 0 var:tmp_story_low_event_chance < 1 } } set_variable = { name = tmp_story_low_event_chance value = 1 } }
        }
        clamp_variable = { name = tmp_story_low_event_chance min = 0 max = 100 }

        if = {
            limit = {
                var:riseandfall_realm_stability_score >= var:tmp_story_stable_threshold
            }
            change_global_variable = { name = riseandfall_story_world_stable_count add = realm_size }
        }
        if = {
            limit = {
                var:riseandfall_realm_stability_score < var:tmp_story_low_threshold
            }
            change_global_variable = { name = riseandfall_story_world_unstable_count add = realm_size }
        }
        if = {
            limit = {
                OR = {
                    var:riseandfall_realm_stability_score < var:tmp_story_low_threshold
                    var:tmp_story_low_event_chance > 0
                }
            }
            change_global_variable = { name = riseandfall_story_world_risky_count add = realm_size }
        }
        if = {
            limit = {
                var:riseandfall_realm_stability_score < var:tmp_story_crisis_threshold
            }
            change_global_variable = { name = riseandfall_story_world_crisis_count add = realm_size }
        }
        if = {
            limit = { primary_title.tier >= tier_empire }
            change_global_variable = { name = riseandfall_story_world_empire_count add = 1 }
        }
        if = {
            limit = { primary_title.tier >= tier_hegemony }
            change_global_variable = { name = riseandfall_story_world_hegemony_count add = 1 }
        }

        set_variable = { name = tmp_story_world_total value = global_var:riseandfall_world_total }
        if = { limit = { var:tmp_story_world_total < 1 } set_variable = { name = tmp_story_world_total value = 1 } }
        set_variable = { name = tmp_story_world_development_total value = global_var:riseandfall_world_total_development }
        if = { limit = { var:tmp_story_world_development_total < 1 } set_variable = { name = tmp_story_world_development_total value = 1 } }
        set_variable = { name = tmp_story_realm_pct value = realm_size }
        change_variable = { name = tmp_story_realm_pct multiply = 100 }
        change_variable = { name = tmp_story_realm_pct divide = var:tmp_story_world_total }
        round_variable = { name = tmp_story_realm_pct nearest = 1 }
        set_variable = { name = tmp_story_development_pct value = var:riseandfall_rs_total_development }
        change_variable = { name = tmp_story_development_pct multiply = 100 }
        change_variable = { name = tmp_story_development_pct divide = var:tmp_story_world_development_total }
        round_variable = { name = tmp_story_development_pct nearest = 1 }
        if = {
            limit = {
                OR = {
                    var:tmp_story_realm_pct >= 8
                    var:tmp_story_development_pct >= 8
                    primary_title.tier >= tier_hegemony
                }
            }
            change_global_variable = { name = riseandfall_story_world_blob_count add = 1 }
        }
        remove_variable = tmp_story_world_total
        remove_variable = tmp_story_world_development_total
        remove_variable = tmp_story_realm_pct
        remove_variable = tmp_story_development_pct
        remove_variable = tmp_story_low_threshold
        remove_variable = tmp_story_crisis_threshold
        remove_variable = tmp_story_stable_threshold
        remove_variable = tmp_story_low_event_diff
        remove_variable = tmp_story_current_stability
        remove_variable = tmp_story_low_event_chance
        if = { limit = { has_variable = tmp_story_low_event_sq } remove_variable = tmp_story_low_event_sq }
    }

    # Convert counts into percentages. These globals are intentionally exposed as
    # coarse campaign signals so individual realms can react to the wider age.
    if = {
        limit = { global_var:riseandfall_story_world_eligible_count > 0 }
        set_global_variable = { name = riseandfall_story_world_stable_pct value = global_var:riseandfall_story_world_stable_count }
        change_global_variable = { name = riseandfall_story_world_stable_pct multiply = 100 }
        change_global_variable = { name = riseandfall_story_world_stable_pct divide = global_var:riseandfall_story_world_eligible_count }
        round_global_variable = { name = riseandfall_story_world_stable_pct nearest = 1 }

        set_global_variable = { name = riseandfall_story_world_unstable_pct value = global_var:riseandfall_story_world_unstable_count }
        change_global_variable = { name = riseandfall_story_world_unstable_pct multiply = 100 }
        change_global_variable = { name = riseandfall_story_world_unstable_pct divide = global_var:riseandfall_story_world_eligible_count }
        round_global_variable = { name = riseandfall_story_world_unstable_pct nearest = 1 }

        set_global_variable = { name = riseandfall_story_world_risky_pct value = global_var:riseandfall_story_world_risky_count }
        change_global_variable = { name = riseandfall_story_world_risky_pct multiply = 100 }
        change_global_variable = { name = riseandfall_story_world_risky_pct divide = global_var:riseandfall_story_world_eligible_count }
        round_global_variable = { name = riseandfall_story_world_risky_pct nearest = 1 }

        set_global_variable = { name = riseandfall_story_world_crisis_pct value = global_var:riseandfall_story_world_crisis_count }
        change_global_variable = { name = riseandfall_story_world_crisis_pct multiply = 100 }
        change_global_variable = { name = riseandfall_story_world_crisis_pct divide = global_var:riseandfall_story_world_eligible_count }
        round_global_variable = { name = riseandfall_story_world_crisis_pct nearest = 1 }
    }

    # World pressure nudges the director toward the active rule target:
    # Long Campaign wants about 10% risky realm-size, Accelerated wants about 30%.
    # Widespread crisis still asks for recovery so the map does not become a uniform death spiral.
    if = {
        limit = { global_var:riseandfall_story_world_crisis_pct >= 25 }
        set_global_variable = { name = riseandfall_story_world_pressure value = -2 }
        set_global_variable = { name = riseandfall_story_world_climate value = 4 }
    }
    else_if = {
        limit = {
            OR = {
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_dynamic
                    global_var:riseandfall_story_world_risky_pct >= 10
                }
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    global_var:riseandfall_story_world_risky_pct >= 30
                }
            }
        }
        set_global_variable = { name = riseandfall_story_world_pressure value = -1 }
        set_global_variable = { name = riseandfall_story_world_climate value = 3 }
    }
    else_if = {
        limit = {
            OR = {
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_dynamic
                    global_var:riseandfall_story_world_risky_pct < 10
                }
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    global_var:riseandfall_story_world_risky_pct < 30
                }
            }
            OR = {
                global_var:riseandfall_story_world_stable_pct >= 60
                global_var:riseandfall_story_world_blob_count >= 2
            }
            NOT = { global_var:riseandfall_story_world_crisis_pct >= 10 }
        }
        set_global_variable = { name = riseandfall_story_world_pressure value = 2 }
        set_global_variable = { name = riseandfall_story_world_climate value = 1 }
    }
    else_if = {
        limit = {
            OR = {
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_dynamic
                    global_var:riseandfall_story_world_risky_pct < 10
                }
                AND = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    global_var:riseandfall_story_world_risky_pct < 30
                }
            }
        }
        set_global_variable = { name = riseandfall_story_world_pressure value = 1 }
        set_global_variable = { name = riseandfall_story_world_climate value = 1 }
    }
    else = {
        set_global_variable = { name = riseandfall_story_world_pressure value = 0 }
        set_global_variable = { name = riseandfall_story_world_climate value = 2 }
    }

    # Collapse arcs are tracked per major realm. Existing buildup always stays
    # active, while a peaceful world can begin new arcs for every stable hegemon
    # whose strongest nearby non-allied rival is below the intended 75% check.
    every_independent_ruler = {
        remove_character_flag = rf_story_decline_target
        if = {
            limit = {
                OR = {
                    has_variable = riseandfall_story_collapse_pressure
                    primary_title = { has_variable = riseandfall_story_title_collapse_pressure }
                }
            }
            add_character_flag = { flag = rf_story_decline_target days = 370 }
        }
    }
    if = {
        limit = { global_var:riseandfall_story_world_pressure >= 1 }
        every_independent_ruler = {
            limit = {
                is_landed = yes
                has_variable = riseandfall_realm_stability_score
                var:riseandfall_realm_stability_score >= 60
                OR = {
                    primary_title.tier >= tier_empire
                    realm_size >= 30
                }
                has_variable = riseandfall_story_strongest_rival_pct
                var:riseandfall_story_strongest_rival_pct < 75
            }
            add_character_flag = { flag = rf_story_decline_target days = 370 }
        }
    }
}

riseandfall_clear_story_director_vars_se = {
    # Hard reset used when Story Mode is off or when a ruler should no longer
    # carry stale director state. These variables are recalculated yearly, so it
    # is safer to clear them than to let old story roles linger after land loss.
    remove_variable = riseandfall_story_role
    remove_variable = riseandfall_story_role_years
    remove_variable = riseandfall_story_protection
    remove_variable = riseandfall_story_collapse_pressure
    remove_variable = riseandfall_story_world_climate
    remove_variable = riseandfall_story_blob_pressure_base
    remove_variable = riseandfall_story_blob_pressure_scaled
    remove_variable = riseandfall_story_blob_pressure
    remove_variable = riseandfall_story_reign_tension
    remove_variable = riseandfall_story_stagnation_pressure
    remove_variable = riseandfall_story_ancient_regime
    remove_variable = riseandfall_story_last_succession_year
    remove_variable = riseandfall_story_no_succession_years
    remove_variable = riseandfall_story_ruler_shield
    remove_variable = riseandfall_story_complacent_vassals
    remove_variable = riseandfall_story_complacent_vassal_pressure
    remove_variable = riseandfall_story_rival_count
    remove_variable = riseandfall_story_strongest_rival_pct
    remove_variable = riseandfall_story_external_rival_relief
    remove_variable = riseandfall_story_strength_baseline
    remove_variable = riseandfall_story_collapse_gain_last
    remove_variable = riseandfall_story_arc
    remove_variable = riseandfall_story_arc_phase
    remove_variable = riseandfall_rs_development_pct
    remove_character_flag = rf_story_decline_target
}

# Collapse buildup belongs to the central title as well as its current holder.
# This preserves an active campaign through ordinary succession and through a
# vassal or claimant taking the primary title from the old ruler.
riseandfall_restore_story_collapse_from_primary_title_se = {
    if = {
        limit = {
            exists = primary_title
            primary_title = { has_variable = riseandfall_story_title_collapse_pressure }
        }
        primary_title = { save_scope_as = rf_story_collapse_title }
        if = {
            limit = { NOT = { has_variable = riseandfall_story_collapse_pressure } }
            set_variable = { name = riseandfall_story_collapse_pressure value = scope:rf_story_collapse_title.var:riseandfall_story_title_collapse_pressure }
        }
        else_if = {
            limit = { var:riseandfall_story_collapse_pressure < scope:rf_story_collapse_title.var:riseandfall_story_title_collapse_pressure }
            set_variable = { name = riseandfall_story_collapse_pressure value = scope:rf_story_collapse_title.var:riseandfall_story_title_collapse_pressure }
        }
        clear_saved_scope = rf_story_collapse_title
    }
}

riseandfall_store_story_collapse_on_primary_title_se = {
    if = {
        limit = { exists = primary_title }
        save_scope_as = rf_story_collapse_ruler
        primary_title = { save_scope_as = rf_story_collapse_title }
        if = {
            limit = { has_variable = riseandfall_story_collapse_pressure }
            scope:rf_story_collapse_title = {
                set_variable = { name = riseandfall_story_title_collapse_pressure value = scope:rf_story_collapse_ruler.var:riseandfall_story_collapse_pressure }
            }
        }
        else_if = {
            limit = { scope:rf_story_collapse_title = { has_variable = riseandfall_story_title_collapse_pressure } }
            scope:rf_story_collapse_title = { remove_variable = riseandfall_story_title_collapse_pressure }
        }
        clear_saved_scope = rf_story_collapse_title
        clear_saved_scope = rf_story_collapse_ruler
    }
}

# A low-stability incident or structural fracture releases part of the current
# Story Mode collapse arc. Percentage relief scales naturally with severity and
# cannot create negative pressure.
riseandfall_story_collapse_relief_se = {
    if = {
        limit = {
            OR = {
                has_game_rule = riseandfall_dynamic_story_mode_dynamic
                has_game_rule = riseandfall_dynamic_story_mode_forced
            }
        }
        # A title transfer can leave the durable title copy as the only source.
        riseandfall_restore_story_collapse_from_primary_title_se = yes
        if = {
            limit = { has_variable = riseandfall_story_collapse_pressure }
            if = {
                limit = { var:riseandfall_story_collapse_pressure <= 1 }
                set_variable = { name = riseandfall_story_collapse_gain_last value = var:riseandfall_story_collapse_pressure }
                change_variable = { name = riseandfall_story_collapse_gain_last multiply = -1 }
                remove_variable = riseandfall_story_collapse_pressure
            }
            else = {
                set_variable = { name = tmp_story_collapse_relief_pressure value = var:riseandfall_story_collapse_pressure }
                change_variable = { name = tmp_story_collapse_relief_pressure multiply = 0.5 }
                round_variable = { name = tmp_story_collapse_relief_pressure nearest = 1 }
                clamp_variable = { name = tmp_story_collapse_relief_pressure min = 0 max = 100 }
                set_variable = { name = riseandfall_story_collapse_gain_last value = var:riseandfall_story_collapse_pressure }
                change_variable = { name = riseandfall_story_collapse_gain_last multiply = -1 }
                change_variable = { name = riseandfall_story_collapse_gain_last add = var:tmp_story_collapse_relief_pressure }
                set_variable = { name = riseandfall_story_collapse_pressure value = var:tmp_story_collapse_relief_pressure }
                remove_variable = tmp_story_collapse_relief_pressure
            }
            if = {
                limit = { NOT = { var:riseandfall_story_collapse_pressure > 0 } }
                remove_variable = riseandfall_story_collapse_pressure
            }
        }
        riseandfall_store_story_collapse_on_primary_title_se = yes
    }
}

riseandfall_apply_successor_realm_grace_se = {
    # New regimes need breathing room after inheritance, palace coups, splits,
    # and other handoffs. Grace is visible stability support plus a cooldown so
    # the director does not immediately punish the realm it just helped create.
    if = {
        limit = { is_landed = yes }
        set_variable = { name = riseandfall_story_successor_grace value = 45 }
        set_variable = { name = riseandfall_story_successor_grace_years value = 12 }
        set_variable = { name = riseandfall_story_successor_grace_decay value = 4 }
        riseandfall_set_low_stability_cooldown_se = yes
        add_character_flag = { flag = rf_story_successor_grace days = 4380 }
        if = {
            limit = {
                has_variable = riseandfall_realm_stability_score
                NOT = { var:riseandfall_realm_stability_score >= 55 }
            }
            set_variable = { name = riseandfall_realm_stability_score value = 55 }
        }
    }
}

riseandfall_apply_palace_coup_successor_grace_se = {
    # Palace coup winners get the same scaffold as normal successors, slightly
    # stronger but faster-decaying because their legitimacy is more fragile.
    riseandfall_apply_successor_realm_grace_se = yes
    set_variable = { name = riseandfall_story_successor_grace value = 50 }
    set_variable = { name = riseandfall_story_successor_grace_decay value = 5 }
}

riseandfall_update_successor_realm_grace_se = {
    # Decay grace yearly. This creates a campaign beat: a successor has a window
    # to stabilize the realm, then the normal director logic starts judging them.
    if = {
        limit = { has_variable = riseandfall_story_successor_grace }
        if = {
            limit = { NOT = { has_variable = riseandfall_story_successor_grace_decay } }
            set_variable = { name = riseandfall_story_successor_grace_decay value = 3 }
        }
        if = {
            limit = { NOT = { has_variable = riseandfall_story_successor_grace_years } }
            set_variable = { name = riseandfall_story_successor_grace_years value = 1 }
        }
        set_variable = { name = tmp_story_successor_grace_decay value = var:riseandfall_story_successor_grace_decay }
        change_variable = { name = tmp_story_successor_grace_decay multiply = -1 }
        change_variable = { name = riseandfall_story_successor_grace add = var:tmp_story_successor_grace_decay }
        change_variable = { name = riseandfall_story_successor_grace_years add = -1 }
        if = {
            limit = {
                OR = {
                    NOT = { var:riseandfall_story_successor_grace > 0 }
                    NOT = { var:riseandfall_story_successor_grace_years > 0 }
                }
            }
            remove_variable = riseandfall_story_successor_grace
            remove_variable = riseandfall_story_successor_grace_years
            remove_variable = riseandfall_story_successor_grace_decay
            remove_variable = tmp_story_successor_grace_decay
            remove_character_flag = rf_story_successor_grace
        }
        else = {
            remove_variable = tmp_story_successor_grace_decay
        }
    }
}

riseandfall_mark_story_succession_year_se = {
    # Succession resets long-reign pressure. The director treats ruler turnover
    # as a natural release valve, not just as a generic stability shock.
    set_variable = { name = riseandfall_story_last_succession_year value = current_year }
    set_variable = { name = riseandfall_story_no_succession_years value = 0 }
    remove_variable = riseandfall_story_reign_tension
    remove_variable = riseandfall_story_stagnation_pressure
    remove_variable = riseandfall_story_ancient_regime
}

riseandfall_inherit_story_collapse_buildup_se = {
    # Collapse buildup is pressure attached to the realm's story, not only the
    # dying ruler. Preserve the predecessor's accumulated meter so inheritance
    # cannot wipe a long-running collapse arc.
    if = {
        limit = {
            exists = scope:predecessor
            OR = {
                has_game_rule = riseandfall_dynamic_story_mode_dynamic
                has_game_rule = riseandfall_dynamic_story_mode_forced
            }
        }
        if = {
            limit = {
                scope:predecessor = { has_variable = riseandfall_story_collapse_pressure }
                OR = {
                    NOT = { has_variable = riseandfall_story_collapse_pressure }
                    var:riseandfall_story_collapse_pressure < scope:predecessor.var:riseandfall_story_collapse_pressure
                }
            }
            set_variable = { name = riseandfall_story_collapse_pressure value = scope:predecessor.var:riseandfall_story_collapse_pressure }
            clamp_variable = { name = riseandfall_story_collapse_pressure min = 0 max = 100 }
        }
        # Preserve the last peacetime military reading if succession occurs
        # during a war, when live army strength is temporarily distorted.
        if = {
            limit = {
                is_at_war = yes
                scope:predecessor = { has_variable = riseandfall_story_strength_baseline }
            }
            set_variable = { name = riseandfall_story_strength_baseline value = scope:predecessor.var:riseandfall_story_strength_baseline }
        }
        if = {
            limit = { has_variable = riseandfall_story_collapse_pressure }
            set_variable = { name = riseandfall_story_collapse_gain_last value = 0 }
        }
    }
}

riseandfall_apply_dynamic_story_pressure_se = {
    # Per-ruler campaign director. This effect converts the global climate and
    # local realm story into a transparent stability component:
    # positive values protect fragile actors, negative values pressure isolated
    # oversized realms, and successor grace remains separately visible.
    set_variable = { name = riseandfall_rs_story_pressure_component value = 0 }
    set_variable = { name = riseandfall_story_recovery_component value = 0 }
    set_variable = { name = riseandfall_story_protection value = 0 }
    set_variable = { name = riseandfall_story_blob_pressure_base value = 0 }
    set_variable = { name = riseandfall_story_blob_pressure_scaled value = 0 }
    set_variable = { name = riseandfall_story_blob_pressure value = 0 }
    set_variable = { name = riseandfall_story_stagnation_pressure value = 0 }
    set_variable = { name = riseandfall_story_ancient_regime value = 0 }
    set_variable = { name = riseandfall_story_ruler_shield value = 0 }
    set_variable = { name = riseandfall_story_complacent_vassals value = 0 }
    set_variable = { name = riseandfall_story_complacent_vassal_pressure value = 0 }
    set_variable = { name = riseandfall_story_rival_count value = 0 }
    set_variable = { name = riseandfall_story_strongest_rival_pct value = 0 }
    set_variable = { name = riseandfall_story_external_rival_relief value = 0 }
    set_variable = { name = riseandfall_story_collapse_gain_last value = 0 }
    set_variable = { name = riseandfall_story_arc value = 0 }
    set_variable = { name = riseandfall_story_arc_phase value = 0 }

    # One-time compatibility cleanup for saves from the retired Legacy
    # Isolation system. Rival danger is now entirely a live yearly comparison.

    # Title-gain refreshes can run at game start before the yearly world pass
    # seeds Story Mode globals. Neutral pressure keeps those early reads safe.
    if = {
        limit = { NOT = { exists = global_var:riseandfall_story_world_pressure } }
        set_global_variable = { name = riseandfall_story_world_pressure value = 0 }
    }
    if = {
        limit = { NOT = { exists = global_var:riseandfall_story_world_climate } }
        set_global_variable = { name = riseandfall_story_world_climate value = 2 }
    }
    if = {
        # Fresh-lobby title gains can score rulers before the first world-climate pass.
        limit = { NOT = { exists = global_var:riseandfall_story_world_risky_pct } }
        set_global_variable = { name = riseandfall_story_world_risky_pct value = 0 }
    }

    if = {
        limit = { exists = global_var:riseandfall_story_world_climate }
        set_variable = { name = riseandfall_story_world_climate value = global_var:riseandfall_story_world_climate }
    }
    else = {
        set_variable = { name = riseandfall_story_world_climate value = 2 }
    }

    if = {
        limit = {
            OR = {
                has_game_rule = riseandfall_dynamic_story_mode_off
                NOT = {
                    OR = {
                        has_game_rule = riseandfall_dynamic_story_mode_dynamic
                        has_game_rule = riseandfall_dynamic_story_mode_forced
                    }
                }
            }
        }
        riseandfall_clear_story_director_vars_se = yes
    }
    else_if = {
        limit = {
            is_independent_ruler = yes
            primary_title.tier >= tier_county
        }
        # Restore title-bound pressure before assigning this ruler's campaign role.
        riseandfall_restore_story_collapse_from_primary_title_se = yes
        if = { limit = { NOT = { has_variable = riseandfall_story_role_years } } set_variable = { name = riseandfall_story_role_years value = 0 } }
        change_variable = { name = riseandfall_story_role_years add = 1 }

        # Use share of tracked world realm size instead of raw realm_size. Raw size varies too much between total conversion mods.
        set_variable = { name = tmp_story_world_total value = global_var:riseandfall_world_total }
        if = { limit = { var:tmp_story_world_total < 1 } set_variable = { name = tmp_story_world_total value = 1 } }
        set_variable = { name = tmp_story_world_development_total value = global_var:riseandfall_world_total_development }
        if = { limit = { var:tmp_story_world_development_total < 1 } set_variable = { name = tmp_story_world_development_total value = 1 } }
        set_variable = { name = tmp_story_realm_pct value = realm_size }
        change_variable = { name = tmp_story_realm_pct multiply = 100 }
        change_variable = { name = tmp_story_realm_pct divide = var:tmp_story_world_total }
        round_variable = { name = tmp_story_realm_pct nearest = 1 }
        if = {
            limit = { NOT = { has_variable = riseandfall_rs_total_development } }
            set_variable = { name = riseandfall_rs_total_development value = 0 }
            save_scope_as = ruler
            every_realm_county = {
                scope:ruler = {
                    change_variable = { name = riseandfall_rs_total_development add = prev.development_level }
                }
            }
        }
        set_variable = { name = tmp_story_development_pct value = var:riseandfall_rs_total_development }
        change_variable = { name = tmp_story_development_pct multiply = 100 }
        change_variable = { name = tmp_story_development_pct divide = var:tmp_story_world_development_total }
        round_variable = { name = tmp_story_development_pct nearest = 1 }
        set_variable = { name = riseandfall_rs_development_pct value = var:tmp_story_development_pct }
        set_variable = { name = tmp_story_stress_score value = 0 }
        set_variable = { name = tmp_story_blob_score value = 0 }
        set_variable = { name = tmp_story_below_unstable_target value = 0 }
        if = {
            limit = {
                has_game_rule = riseandfall_dynamic_story_mode_dynamic
                global_var:riseandfall_story_world_risky_pct < 10
            }
            set_variable = { name = tmp_story_below_unstable_target value = 1 }
        }
        else_if = {
            limit = {
                has_game_rule = riseandfall_dynamic_story_mode_forced
                global_var:riseandfall_story_world_risky_pct < 30
            }
            set_variable = { name = tmp_story_below_unstable_target value = 1 }
        }
        # Measure the strongest nearby non-allied kingdom+ realm against this
        # ruler's last peacetime strength. Wars temporarily distort live army
        # totals, so the baseline updates only while the ruler is at peace.
        set_variable = { name = tmp_story_ruler_strength value = max_military_strength }
        if = {
            limit = { is_at_war = no }
            set_variable = { name = riseandfall_story_strength_baseline value = var:tmp_story_ruler_strength }
        }
        else_if = {
            limit = { NOT = { has_variable = riseandfall_story_strength_baseline } }
            set_variable = { name = riseandfall_story_strength_baseline value = var:tmp_story_ruler_strength }
        }
        else_if = {
            limit = { is_at_war = yes }
            set_variable = { name = tmp_story_ruler_strength value = var:riseandfall_story_strength_baseline }
        }
        if = { limit = { var:tmp_story_ruler_strength < 1 } set_variable = { name = tmp_story_ruler_strength value = 1 } }
        save_scope_as = ruler

        # Local danger thresholds mirror the low-stability event curve. Story Mode
        # should not treat a hegemony at 48 stability as "fine" just because a
        # kingdom would not yet be below 40.
        set_variable = { name = tmp_story_low_threshold value = 40 }
        if = { limit = { primary_title.tier >= tier_empire } set_variable = { name = tmp_story_low_threshold value = 45 } }
        if = { limit = { primary_title.tier >= tier_hegemony } set_variable = { name = tmp_story_low_threshold value = 50 } }
        set_variable = { name = tmp_story_stable_threshold value = var:tmp_story_low_threshold }
        change_variable = { name = tmp_story_stable_threshold add = 25 }
        set_variable = { name = tmp_story_decline_threshold value = var:tmp_story_low_threshold }
        change_variable = { name = tmp_story_decline_threshold add = 20 }

        # Find the strongest nearby rival before assigning roles. Distant powers
        # and allies do not count; only a border or close across-water rival gives
        # vassals a reason to tolerate the imperial center.
        every_neighboring_and_across_water_top_liege_realm_owner = {
            limit = {
                is_landed = yes
                primary_title.tier >= tier_kingdom
                NOT = { this = scope:ruler }
                NOT = { is_allied_to = scope:ruler }
            }
            save_scope_as = story_rival_candidate
            scope:ruler = {
                change_variable = { name = riseandfall_story_rival_count add = 1 }
                set_variable = { name = tmp_story_candidate_rival_strength value = scope:story_rival_candidate.max_military_strength }
                # Apply the rival's own frozen peacetime baseline as well, so a
                # war on either side cannot skew the relative-strength reading.
                if = {
                    limit = {
                        scope:story_rival_candidate = {
                            is_at_war = yes
                            has_variable = riseandfall_story_strength_baseline
                        }
                    }
                    set_variable = { name = tmp_story_candidate_rival_strength value = scope:story_rival_candidate.var:riseandfall_story_strength_baseline }
                }
                set_variable = { name = tmp_story_candidate_rival_pct value = var:tmp_story_candidate_rival_strength }
                change_variable = { name = tmp_story_candidate_rival_pct multiply = 100 }
                change_variable = { name = tmp_story_candidate_rival_pct divide = var:tmp_story_ruler_strength }
                if = {
                    limit = { var:tmp_story_candidate_rival_pct > var:riseandfall_story_strongest_rival_pct }
                    set_variable = { name = riseandfall_story_strongest_rival_pct value = var:tmp_story_candidate_rival_pct }
                }
            }
        }
        clamp_variable = { name = riseandfall_story_strongest_rival_pct min = 0 max = 150 }
        round_variable = { name = riseandfall_story_strongest_rival_pct nearest = 1 }

        # Convert rival strength into yearly collapse-gain relief. This is a
        # pressure reducer, not immunity: 35% strength => about 1.8 relief/year,
        # 60% => 3, 100% => 5, and superior rivals cap at 7.5.
        set_variable = { name = riseandfall_story_external_rival_relief value = var:riseandfall_story_strongest_rival_pct }
        change_variable = { name = riseandfall_story_external_rival_relief divide = 20 }
        clamp_variable = { name = riseandfall_story_external_rival_relief min = 0 max = 7.5 }

        # Story Mode has three deliberate lanes: Declining Powers, nearby
        # Counterweights, and general crisis recovery. Old Anchor and Wildcard
        # labels were generic stability subsidies, so they are retired instead of
        # pretending to be distinct campaign roles. 2 counterweight, 3 declining,
        # 5 background.
        set_variable = { name = tmp_story_candidate_role value = 5 }
        set_variable = { name = tmp_story_declining_neighbor value = 0 }
        every_neighboring_and_across_water_top_liege_realm_owner = {
            limit = {
                is_landed = yes
                primary_title.tier >= tier_kingdom
                NOT = { this = scope:ruler }
                NOT = { is_allied_to = scope:ruler }
                has_character_flag = rf_story_decline_target
            }
            scope:ruler = { set_variable = { name = tmp_story_declining_neighbor value = 1 } }
        }
        if = {
            limit = { has_variable = riseandfall_story_role }
            set_variable = { name = tmp_story_previous_role value = var:riseandfall_story_role }
        }
        else = {
            set_variable = { name = tmp_story_previous_role value = 0 }
        }
        if = {
            limit = { has_variable = riseandfall_story_successor_grace }
            set_variable = { name = tmp_story_candidate_role value = 5 }
        }
        else_if = {
            limit = {
                has_character_flag = rf_story_decline_target
            }
            set_variable = { name = tmp_story_candidate_role value = 3 }
        }
        else_if = {
            limit = {
                has_variable = riseandfall_realm_stability_score
                var:tmp_story_declining_neighbor = 1
                primary_title.tier >= tier_kingdom
                NOT = { var:riseandfall_realm_stability_score >= 70 }
            }
            set_variable = { name = tmp_story_candidate_role value = 2 }
        }

        if = {
            limit = {
                has_variable = riseandfall_story_role
                var:riseandfall_story_role_years < 5
                OR = {
                    AND = {
                        var:riseandfall_story_role = 2
                        var:tmp_story_declining_neighbor = 1
                    }
                    AND = {
                        var:riseandfall_story_role = 3
                        has_character_flag = rf_story_decline_target
                    }
                }
                NOT = { has_variable = riseandfall_story_successor_grace }
                NOT = {
                    AND = {
                        has_variable = riseandfall_story_collapse_pressure
                        var:tmp_story_candidate_role = 3
                    }
                }
            }
            set_variable = { name = tmp_story_candidate_role value = var:riseandfall_story_role }
        }
        set_variable = { name = riseandfall_story_role value = var:tmp_story_candidate_role }
        if = {
            limit = { NOT = { var:riseandfall_story_role = var:tmp_story_previous_role } }
            set_variable = { name = riseandfall_story_role_years value = 0 }
        }

        if = {
            limit = { var:riseandfall_story_role = 2 }
            # A Counterweight receives enough support to remain relevant, but not
            # enough to replace normal realm stability or crisis recovery.
            if = { limit = { has_variable = riseandfall_realm_stability_score NOT = { var:riseandfall_realm_stability_score >= 35 } } set_variable = { name = riseandfall_story_protection value = 20 } }
            else_if = { limit = { has_variable = riseandfall_realm_stability_score NOT = { var:riseandfall_realm_stability_score >= 55 } } set_variable = { name = riseandfall_story_protection value = 12 } }
            else_if = { limit = { has_variable = riseandfall_realm_stability_score NOT = { var:riseandfall_realm_stability_score >= 70 } } set_variable = { name = riseandfall_story_protection value = 5 } }
            else = { set_variable = { name = riseandfall_story_protection value = 2 } }
        }

        # Give the selected Declining Power a cause before applying pressure.
        # 1 = noble challenge, 2 = identity revolt, 3 = succession fracture,
        # 4 = imperial fragmentation. The low-stability selector consumes this
        # only once the buildup reaches the crisis phases below.
        if = {
            limit = { has_character_flag = rf_story_decline_target }
            set_variable = { name = riseandfall_story_arc value = 4 }
            if = {
                limit = {
                    has_variable = riseandfall_rs_culture_faith_component
                    NOT = { var:riseandfall_rs_culture_faith_component >= -14 }
                }
                set_variable = { name = riseandfall_story_arc value = 2 }
            }
            else_if = {
                limit = {
                    OR = {
                        AND = {
                            has_variable = riseandfall_rs_strong_vassal_component
                            NOT = { var:riseandfall_rs_strong_vassal_component >= -9 }
                        }
                        AND = {
                            has_variable = riseandfall_rs_vassals_component
                            NOT = { var:riseandfall_rs_vassals_component >= -14 }
                        }
                    }
                }
                set_variable = { name = riseandfall_story_arc value = 1 }
            }
            else_if = {
                limit = {
                    has_variable = riseandfall_rs_succession_component
                    NOT = { var:riseandfall_rs_succession_component >= -9 }
                }
                set_variable = { name = riseandfall_story_arc value = 3 }
            }
        }

        if = {
            limit = { NOT = { has_variable = riseandfall_story_last_succession_year } }
            set_variable = { name = riseandfall_story_last_succession_year value = current_year }
            set_variable = { name = tmp_story_years_as_ruler value = years_as_ruler }
            change_variable = { name = tmp_story_years_as_ruler multiply = -1 }
            change_variable = { name = riseandfall_story_last_succession_year add = var:tmp_story_years_as_ruler }
            remove_variable = tmp_story_years_as_ruler
        }
        set_variable = { name = riseandfall_story_no_succession_years value = current_year }
        set_variable = { name = tmp_story_last_succession_year value = var:riseandfall_story_last_succession_year }
        change_variable = { name = tmp_story_last_succession_year multiply = -1 }
        change_variable = { name = riseandfall_story_no_succession_years add = var:tmp_story_last_succession_year }
        clamp_variable = { name = riseandfall_story_no_succession_years min = 0 max = 1000 }

        # Long-lived rulers accumulate institutional stagnation. Good rule slows it early, but cannot erase ancient-regime pressure forever.
        if = {
            limit = {
                years_as_ruler >= 50
                OR = {
                    primary_title.tier >= tier_empire
                    var:tmp_story_realm_pct >= 5
                    var:tmp_story_development_pct >= 5
                }
            }
            if = { limit = { NOT = { has_variable = riseandfall_story_reign_tension } } set_variable = { name = riseandfall_story_reign_tension value = 0 } }
            change_variable = { name = riseandfall_story_reign_tension add = 1 }
            if = { limit = { years_as_ruler >= 100 } change_variable = { name = riseandfall_story_reign_tension add = 1 } }
            if = { limit = { years_as_ruler >= 200 } change_variable = { name = riseandfall_story_reign_tension add = 2 } }
            if = { limit = { years_as_ruler >= 500 } change_variable = { name = riseandfall_story_reign_tension add = 4 } }
            if = { limit = { primary_title.tier >= tier_hegemony } change_variable = { name = riseandfall_story_reign_tension add = 1 } }
            if = { limit = { var:tmp_story_realm_pct >= 8 } change_variable = { name = riseandfall_story_reign_tension add = 1 } }
            if = { limit = { var:tmp_story_realm_pct >= 15 } change_variable = { name = riseandfall_story_reign_tension add = 1 } }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = riseandfall_story_reign_tension add = 2 } }

            if = {
                limit = {
                    has_variable = riseandfall_realm_stability_score
                    var:riseandfall_realm_stability_score >= 70
                }
                change_variable = { name = riseandfall_story_ruler_shield add = 2 }
            }
            if = {
                limit = {
                    has_variable = riseandfall_rs_stats_component
                    var:riseandfall_rs_stats_component >= 10
                }
                change_variable = { name = riseandfall_story_ruler_shield add = 1 }
            }
            if = {
                limit = {
                    has_variable = riseandfall_rs_legitimacy_component
                    var:riseandfall_rs_legitimacy_component >= 8
                }
                change_variable = { name = riseandfall_story_ruler_shield add = 1 }
            }
            if = {
                limit = {
                    has_variable = riseandfall_rs_vassals_component
                    var:riseandfall_rs_vassals_component >= 10
                }
                change_variable = { name = riseandfall_story_ruler_shield add = 1 }
            }
            if = {
                limit = {
                    years_as_ruler < 100
                    var:riseandfall_story_ruler_shield > 0
                }
                set_variable = { name = tmp_story_shield_decay value = var:riseandfall_story_ruler_shield }
                change_variable = { name = tmp_story_shield_decay multiply = -1 }
                change_variable = { name = riseandfall_story_reign_tension add = var:tmp_story_shield_decay }
            }
            else_if = {
                limit = {
                    years_as_ruler < 200
                    var:riseandfall_story_ruler_shield > 1
                }
                set_variable = { name = tmp_story_shield_decay value = var:riseandfall_story_ruler_shield }
                change_variable = { name = tmp_story_shield_decay divide = 2 }
                change_variable = { name = tmp_story_shield_decay multiply = -1 }
                change_variable = { name = riseandfall_story_reign_tension add = var:tmp_story_shield_decay }
            }
            if = { limit = { has_variable = tmp_story_shield_decay } remove_variable = tmp_story_shield_decay }
            clamp_variable = { name = riseandfall_story_reign_tension min = 0 max = 100 }
            if = {
                limit = { years_as_ruler >= 200 }
                set_variable = { name = riseandfall_story_ancient_regime value = 1 }
            }
            if = {
                limit = { years_as_ruler >= 500 }
                set_variable = { name = riseandfall_story_ancient_regime value = 2 }
            }
        }
        else_if = {
            limit = { has_variable = riseandfall_story_reign_tension }
            change_variable = { name = riseandfall_story_reign_tension add = -2 }
            if = { limit = { NOT = { var:riseandfall_story_reign_tension > 0 } } remove_variable = riseandfall_story_reign_tension }
        }

        if = { limit = { is_in_civil_war = yes } change_variable = { name = tmp_story_stress_score add = 3 } }
        if = { limit = { has_variable = riseandfall_war_penalty var:riseandfall_war_penalty >= 20 } change_variable = { name = tmp_story_stress_score add = 2 } }
        if = { limit = { has_variable = riseandfall_rs_legitimacy_component NOT = { var:riseandfall_rs_legitimacy_component >= -5 } } change_variable = { name = tmp_story_stress_score add = 1 } }
        if = { limit = { has_variable = riseandfall_rs_legitimacy_component NOT = { var:riseandfall_rs_legitimacy_component >= -15 } } change_variable = { name = tmp_story_stress_score add = 1 } }
        if = { limit = { has_variable = riseandfall_rs_culture_faith_component NOT = { var:riseandfall_rs_culture_faith_component >= -10 } } change_variable = { name = tmp_story_stress_score add = 2 } }
        if = { limit = { has_variable = riseandfall_rs_strong_vassal_component NOT = { var:riseandfall_rs_strong_vassal_component >= -10 } } change_variable = { name = tmp_story_stress_score add = 2 } }
        if = { limit = { has_variable = riseandfall_realm_stability_score NOT = { var:riseandfall_realm_stability_score >= 45 } } change_variable = { name = tmp_story_stress_score add = 2 } }
        if = { limit = { var:tmp_story_realm_pct >= 8 } change_variable = { name = tmp_story_stress_score add = 1 } }
        if = { limit = { var:tmp_story_realm_pct >= 15 } change_variable = { name = tmp_story_stress_score add = 1 } }
        if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 100 } change_variable = { name = tmp_story_stress_score add = 1 } }
        if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 200 } change_variable = { name = tmp_story_stress_score add = 1 } }

        # Blob score gates harsh Story Mode pressure. Realm share is sprawl;
        # development share is capacity and prize value. Dense powers count as
        # major actors, but land still carries the stronger overstretch signal.
        if = { limit = { primary_title.tier >= tier_empire } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { primary_title.tier >= tier_hegemony } change_variable = { name = tmp_story_blob_score add = 2 } }
        if = { limit = { var:tmp_story_realm_pct >= 5 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { var:tmp_story_realm_pct >= 8 } change_variable = { name = tmp_story_blob_score add = 2 } }
        if = { limit = { var:tmp_story_realm_pct >= 15 } change_variable = { name = tmp_story_blob_score add = 2 } }
        if = { limit = { var:tmp_story_realm_pct >= 25 } change_variable = { name = tmp_story_blob_score add = 2 } }
        if = { limit = { var:tmp_story_development_pct >= 5 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { var:tmp_story_development_pct >= 8 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { var:tmp_story_development_pct >= 15 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { global_var:riseandfall_story_world_pressure >= 2 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = {
            limit = {
                var:tmp_story_below_unstable_target = 1
                OR = {
                    primary_title.tier >= tier_empire
                    var:tmp_story_realm_pct >= 5
                    var:tmp_story_development_pct >= 5
                }
            }
            change_variable = { name = tmp_story_blob_score add = 1 }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = tmp_story_blob_score add = 1 } }
        }
        if = { limit = { has_variable = riseandfall_realm_stability_score var:riseandfall_realm_stability_score >= 80 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 100 } change_variable = { name = tmp_story_blob_score add = 1 } }
        if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 200 } change_variable = { name = tmp_story_blob_score add = 1 } }

        # Powerful non-allied vassals become a separate internal pressure source in old or oversized realms.
        if = {
            limit = {
                OR = {
                    years_as_ruler >= 50
                    AND = {
                        has_variable = riseandfall_story_no_succession_years
                        var:riseandfall_story_no_succession_years >= 50
                    }
                    var:tmp_story_realm_pct >= 8
                    primary_title.tier >= tier_empire
                }
            }
            every_powerful_vassal = {
                limit = {
                    is_landed = yes
                    NOT = { is_allied_to = scope:ruler }
                }
                scope:ruler = { change_variable = { name = riseandfall_story_complacent_vassals add = 1 } }
                if = {
                    limit = { years_as_ruler >= 30 }
                    scope:ruler = { change_variable = { name = riseandfall_story_complacent_vassals add = 1 } }
                }
                if = {
                    limit = { years_as_ruler >= 100 }
                    scope:ruler = { change_variable = { name = riseandfall_story_complacent_vassals add = 2 } }
                }
            }
            if = {
                limit = {
                    has_variable = riseandfall_rs_strong_vassal_count
                    var:riseandfall_rs_strong_vassal_count >= 2
                }
                change_variable = { name = riseandfall_story_complacent_vassals add = 2 }
            }
            if = {
                limit = {
                    has_variable = riseandfall_rs_strong_vassal_count
                    var:riseandfall_rs_strong_vassal_count >= 4
                }
                change_variable = { name = riseandfall_story_complacent_vassals add = 2 }
            }
            if = { limit = { years_as_ruler >= 100 } change_variable = { name = riseandfall_story_complacent_vassals add = 1 } }
            if = { limit = { years_as_ruler >= 200 } change_variable = { name = riseandfall_story_complacent_vassals add = 2 } }
            if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 100 } change_variable = { name = riseandfall_story_complacent_vassals add = 1 } }
            if = { limit = { has_variable = riseandfall_story_no_succession_years var:riseandfall_story_no_succession_years >= 200 } change_variable = { name = riseandfall_story_complacent_vassals add = 2 } }
            if = { limit = { var:tmp_story_realm_pct >= 8 } change_variable = { name = riseandfall_story_complacent_vassals add = 1 } }
            if = { limit = { var:tmp_story_realm_pct >= 15 } change_variable = { name = riseandfall_story_complacent_vassals add = 2 } }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = riseandfall_story_complacent_vassals add = 2 } }
            clamp_variable = { name = riseandfall_story_complacent_vassals min = 0 max = 40 }
            if = {
                limit = { var:riseandfall_story_complacent_vassals >= 3 }
                set_variable = { name = riseandfall_story_complacent_vassal_pressure value = var:riseandfall_story_complacent_vassals }
                change_variable = { name = riseandfall_story_complacent_vassal_pressure divide = 3 }
                if = { limit = { years_as_ruler >= 100 } change_variable = { name = riseandfall_story_complacent_vassal_pressure add = 1 } }
                if = { limit = { years_as_ruler >= 200 } change_variable = { name = riseandfall_story_complacent_vassal_pressure add = 2 } }
                if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = riseandfall_story_complacent_vassal_pressure add = 2 } }
                clamp_variable = { name = riseandfall_story_complacent_vassal_pressure min = 0 max = 18 }
            }
        }

        if = {
            limit = {
                has_variable = riseandfall_story_reign_tension
                var:riseandfall_story_reign_tension >= 15
                OR = {
                    var:tmp_story_stress_score >= 3
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    years_as_ruler >= 200
                }
            }
            set_variable = { name = riseandfall_story_stagnation_pressure value = var:riseandfall_story_reign_tension }
            change_variable = { name = riseandfall_story_stagnation_pressure divide = 8 }
            change_variable = { name = riseandfall_story_stagnation_pressure add = var:tmp_story_stress_score }
            if = { limit = { years_as_ruler >= 200 } change_variable = { name = riseandfall_story_stagnation_pressure add = 2 } }
            if = { limit = { years_as_ruler >= 500 } change_variable = { name = riseandfall_story_stagnation_pressure add = 4 } }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = riseandfall_story_stagnation_pressure add = 3 } }
            clamp_variable = { name = riseandfall_story_stagnation_pressure min = 0 max = 30 }
        }

        # Collapse pressure is an internal 0..100 meter. Accelerated preserves
        # the existing aggressive curve; Long Campaign targets a 200-300 year
        # path to full buildup while a realm remains a valid collapse target.
        if = {
            limit = {
                var:riseandfall_story_role = 3
                has_character_flag = rf_story_decline_target
                NOT = { has_variable = riseandfall_story_successor_grace }
                var:tmp_story_blob_score >= 2
            }
            if = { limit = { NOT = { has_variable = riseandfall_story_collapse_pressure } } set_variable = { name = riseandfall_story_collapse_pressure value = 0 } }
            set_variable = { name = tmp_story_collapse_gain value = 1 }
            if = { limit = { var:tmp_story_blob_score >= 4 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { var:tmp_story_blob_score >= 7 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { global_var:riseandfall_story_world_pressure >= 2 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { var:tmp_story_below_unstable_target = 1 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { primary_title.tier >= tier_hegemony } change_variable = { name = tmp_story_collapse_gain add = 2 } }
            if = { limit = { var:tmp_story_realm_pct >= 10 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { var:tmp_story_realm_pct >= 20 } change_variable = { name = tmp_story_collapse_gain add = 2 } }
            if = { limit = { var:tmp_story_development_pct >= 10 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = { limit = { var:tmp_story_development_pct >= 20 } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = {
                limit = { var:riseandfall_story_stagnation_pressure > 0 }
                set_variable = { name = tmp_story_scaled_stagnation value = var:riseandfall_story_stagnation_pressure }
                change_variable = { name = tmp_story_scaled_stagnation divide = 4 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_scaled_stagnation }
            }
            if = {
                limit = { var:riseandfall_story_complacent_vassal_pressure > 0 }
                set_variable = { name = tmp_story_scaled_vassal_pressure value = var:riseandfall_story_complacent_vassal_pressure }
                change_variable = { name = tmp_story_scaled_vassal_pressure divide = 3 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_scaled_vassal_pressure }
            }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = tmp_story_collapse_gain add = 2 } }
            if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    var:tmp_story_blob_score >= 6
                }
                change_variable = { name = tmp_story_collapse_gain add = 2 }
            }
            if = {
                limit = { var:riseandfall_story_external_rival_relief > 0 }
                set_variable = { name = tmp_story_external_rival_relief_negative value = var:riseandfall_story_external_rival_relief }
                change_variable = { name = tmp_story_external_rival_relief_negative multiply = -1 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_external_rival_relief_negative }
            }
            # Long Campaign gains 0.35-0.5 per qualifying year, reaching full
            # buildup in roughly 200-300 years. Accelerated keeps the former
            # Forced curve for a much shorter campaign arc.
            if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_dynamic
                    var:riseandfall_story_strongest_rival_pct < 75
                    var:tmp_story_collapse_gain > 0
                    var:tmp_story_collapse_gain < 0.35
                }
                set_variable = { name = tmp_story_collapse_gain value = 0.35 }
            }
            else_if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    var:riseandfall_story_strongest_rival_pct < 75
                    var:tmp_story_collapse_gain > 0
                    var:tmp_story_collapse_gain < 2
                }
                set_variable = { name = tmp_story_collapse_gain value = 2 }
            }
            if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_dynamic }
                clamp_variable = { name = tmp_story_collapse_gain min = -0.25 max = 0.5 }
            }
            else_if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_forced }
                clamp_variable = { name = tmp_story_collapse_gain min = -1 max = 3 }
            }
            # Store the net yearly meter change for the GUI. The director-note
            # rows show raw warning scores, but this value is what actually gets
            # added to collapse buildup after scaling, rival relief, and caps.
            set_variable = { name = riseandfall_story_collapse_gain_last value = var:tmp_story_collapse_gain }
            change_variable = { name = riseandfall_story_collapse_pressure add = var:tmp_story_collapse_gain }
            clamp_variable = { name = riseandfall_story_collapse_pressure min = 0 max = 100 }
        }
        else_if = {
            limit = {
                OR = {
                    var:riseandfall_story_stagnation_pressure > 0
                    var:riseandfall_story_complacent_vassal_pressure > 0
                }
                OR = {
                    var:riseandfall_story_strongest_rival_pct < 75
                    AND = {
                        var:riseandfall_story_complacent_vassal_pressure > 4
                        var:riseandfall_story_stagnation_pressure > 4
                    }
                }
                has_character_flag = rf_story_decline_target
                NOT = { has_variable = riseandfall_story_successor_grace }
                var:tmp_story_blob_score >= 2
            }
            if = { limit = { NOT = { has_variable = riseandfall_story_collapse_pressure } } set_variable = { name = riseandfall_story_collapse_pressure value = 0 } }
            set_variable = { name = tmp_story_collapse_gain value = 0 }
            if = {
                limit = { var:riseandfall_story_stagnation_pressure > 0 }
                set_variable = { name = tmp_story_scaled_stagnation value = var:riseandfall_story_stagnation_pressure }
                change_variable = { name = tmp_story_scaled_stagnation divide = 5 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_scaled_stagnation }
            }
            if = {
                limit = { var:riseandfall_story_complacent_vassal_pressure > 0 }
                set_variable = { name = tmp_story_scaled_vassal_pressure value = var:riseandfall_story_complacent_vassal_pressure }
                change_variable = { name = tmp_story_scaled_vassal_pressure divide = 4 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_scaled_vassal_pressure }
            }
            if = { limit = { has_game_rule = riseandfall_dynamic_story_mode_forced } change_variable = { name = tmp_story_collapse_gain add = 1 } }
            if = {
                limit = { var:riseandfall_story_external_rival_relief > 0 }
                set_variable = { name = tmp_story_external_rival_relief_negative value = var:riseandfall_story_external_rival_relief }
                change_variable = { name = tmp_story_external_rival_relief_negative multiply = -1 }
                change_variable = { name = tmp_story_collapse_gain add = var:tmp_story_external_rival_relief_negative }
            }
            # Preserve the former Forced branch's indirect-pressure floor.
            if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    var:riseandfall_story_strongest_rival_pct < 75
                    var:tmp_story_collapse_gain < 1
                }
                set_variable = { name = tmp_story_collapse_gain value = 1 }
            }
            # Same timeline split as above, but this indirect-pressure branch
            # remains softer than a fully selected Declining Power arc.
            if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_dynamic
                    var:riseandfall_story_strongest_rival_pct < 75
                    var:tmp_story_collapse_gain > 0
                    var:tmp_story_collapse_gain < 0.35
                }
                set_variable = { name = tmp_story_collapse_gain value = 0.35 }
            }
            else_if = {
                limit = {
                    has_game_rule = riseandfall_dynamic_story_mode_forced
                    var:riseandfall_story_strongest_rival_pct < 75
                    var:tmp_story_collapse_gain > 0
                    var:tmp_story_collapse_gain < 1.5
                }
                set_variable = { name = tmp_story_collapse_gain value = 1.5 }
            }
            if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_dynamic }
                clamp_variable = { name = tmp_story_collapse_gain min = -0.25 max = 0.5 }
            }
            else_if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_forced }
                clamp_variable = { name = tmp_story_collapse_gain min = -1 max = 2.5 }
            }
            # Store the softer indirect-pressure gain separately so the GUI can
            # explain why raw warnings like vassal ambition do not add 1:1.
            set_variable = { name = riseandfall_story_collapse_gain_last value = var:tmp_story_collapse_gain }
            change_variable = { name = riseandfall_story_collapse_pressure add = var:tmp_story_collapse_gain }
            clamp_variable = { name = riseandfall_story_collapse_pressure min = 0 max = 100 }
        }
        else_if = {
            limit = { has_variable = riseandfall_story_collapse_pressure }
            # Collapse buildup is institutional complacency, not a battlefield
            # morale value. Let it bleed off slowly so temporary army losses or
            # short-lived threats do not immediately reset the director's story.
            set_variable = { name = riseandfall_story_collapse_gain_last value = -1 }
            change_variable = { name = riseandfall_story_collapse_pressure add = -1 }
            if = { limit = { NOT = { var:riseandfall_story_collapse_pressure > 0 } } remove_variable = riseandfall_story_collapse_pressure }
        }

        # Convert internal collapse pressure into the visible stability penalty.
        # Long Campaign maps its slow buildup one-for-one; Accelerated keeps the
        # former Forced base penalty and one-for-one scaling.
        if = {
            limit = {
                has_character_flag = rf_story_decline_target
                has_variable = riseandfall_story_collapse_pressure
            }
            if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_dynamic }
                set_variable = { name = riseandfall_story_blob_pressure_base value = 0 }
                set_variable = { name = riseandfall_story_blob_pressure_scaled value = var:riseandfall_story_collapse_pressure }
                change_variable = { name = riseandfall_story_blob_pressure_scaled multiply = -1 }
                set_variable = { name = riseandfall_story_blob_pressure value = var:riseandfall_story_blob_pressure_base }
                change_variable = { name = riseandfall_story_blob_pressure add = var:riseandfall_story_blob_pressure_scaled }
                clamp_variable = { name = riseandfall_story_blob_pressure min = -100 max = 0 }
            }
            else_if = {
                limit = { has_game_rule = riseandfall_dynamic_story_mode_forced }
                set_variable = { name = riseandfall_story_blob_pressure_base value = -10 }
                set_variable = { name = riseandfall_story_blob_pressure_scaled value = var:riseandfall_story_collapse_pressure }
                change_variable = { name = riseandfall_story_blob_pressure_scaled multiply = -1 }
                set_variable = { name = riseandfall_story_blob_pressure value = var:riseandfall_story_blob_pressure_base }
                change_variable = { name = riseandfall_story_blob_pressure add = var:riseandfall_story_blob_pressure_scaled }
                # Accelerated is an explicit campaign-collapse setting, so a fully
                # built collapse arc may apply the complete -100 Story Mode pressure.
                clamp_variable = { name = riseandfall_story_blob_pressure min = -100 max = 0 }
            }
            else = {
                set_variable = { name = riseandfall_story_blob_pressure value = 0 }
            }
            clamp_variable = { name = riseandfall_story_blob_pressure min = -100 max = 0 }
        }

        # Expose a simple three-act structure for the event selector. Early
        # buildup only changes stability; crisis and fracture phases steer the
        # normal low-stability roll toward the arc's credible event type.
        if = {
            limit = {
                has_character_flag = rf_story_decline_target
                has_variable = riseandfall_story_collapse_pressure
            }
            set_variable = { name = riseandfall_story_arc_phase value = 1 }
            if = { limit = { var:riseandfall_story_collapse_pressure >= 25 } set_variable = { name = riseandfall_story_arc_phase value = 2 } }
            if = { limit = { var:riseandfall_story_collapse_pressure >= 55 } set_variable = { name = riseandfall_story_arc_phase value = 3 } }
        }

        # Write the final yearly meter to the title after every change. The title
        # is the durable campaign anchor when the ruler dies or is overthrown.
        riseandfall_store_story_collapse_on_primary_title_se = yes

        if = {
            limit = {
                global_var:riseandfall_story_world_pressure < 0
                has_variable = riseandfall_realm_stability_score
                NOT = { var:riseandfall_realm_stability_score >= 50 }
            }
            if = { limit = { NOT = { var:riseandfall_realm_stability_score >= 25 } } set_variable = { name = riseandfall_story_recovery_component value = 25 } }
            else_if = { limit = { NOT = { var:riseandfall_realm_stability_score >= 40 } } set_variable = { name = riseandfall_story_recovery_component value = 18 } }
            else = { set_variable = { name = riseandfall_story_recovery_component value = 8 } }
        }

        # Collapse targets should not receive Story Mode help from another
        # director lane. Once buildup exists, or while the realm is explicitly a
        # Declining Power, only the negative collapse pressure should apply.
        if = {
            limit = {
                OR = {
                    has_variable = riseandfall_story_collapse_pressure
                    var:riseandfall_story_role = 3
                }
            }
            set_variable = { name = riseandfall_story_protection value = 0 }
            set_variable = { name = riseandfall_story_recovery_component value = 0 }
        }

        set_variable = { name = riseandfall_rs_story_pressure_component value = 0 }
        change_variable = { name = riseandfall_rs_story_pressure_component add = var:riseandfall_story_protection }
        change_variable = { name = riseandfall_rs_story_pressure_component add = var:riseandfall_story_recovery_component }
        change_variable = { name = riseandfall_rs_story_pressure_component add = var:riseandfall_story_blob_pressure }
        if = {
            limit = {
                has_variable = riseandfall_realm_stability_score
                var:riseandfall_realm_stability_score >= 70
                var:riseandfall_rs_story_pressure_component > 0
            }
            set_variable = { name = riseandfall_rs_story_pressure_component value = 0 }
        }
        clamp_variable = { name = riseandfall_rs_story_pressure_component min = -100 max = 35 }

        remove_variable = tmp_story_world_total
        remove_variable = tmp_story_world_development_total
        remove_variable = tmp_story_realm_pct
        remove_variable = tmp_story_development_pct
        remove_variable = tmp_story_stress_score
        remove_variable = tmp_story_blob_score
        remove_variable = tmp_story_below_unstable_target
        remove_variable = tmp_story_ruler_strength
        if = { limit = { has_variable = tmp_story_candidate_rival_strength } remove_variable = tmp_story_candidate_rival_strength }
        if = { limit = { has_variable = tmp_story_candidate_rival_pct } remove_variable = tmp_story_candidate_rival_pct }
        remove_variable = tmp_story_low_threshold
        remove_variable = tmp_story_stable_threshold
        remove_variable = tmp_story_decline_threshold
        remove_variable = tmp_story_candidate_role
        remove_variable = tmp_story_previous_role
        remove_variable = tmp_story_declining_neighbor
        if = { limit = { has_variable = tmp_story_external_rival_relief_negative } remove_variable = tmp_story_external_rival_relief_negative }
        if = { limit = { has_variable = tmp_story_collapse_gain } remove_variable = tmp_story_collapse_gain }
        if = { limit = { has_variable = tmp_story_scaled_stagnation } remove_variable = tmp_story_scaled_stagnation }
        if = { limit = { has_variable = tmp_story_scaled_vassal_pressure } remove_variable = tmp_story_scaled_vassal_pressure }
        remove_variable = tmp_story_last_succession_year
    }
    else = {
        riseandfall_clear_story_director_vars_se = yes
    }
}
