﻿
# Ensure passive power modifier tracks the trait on old/new saves.
domcom_human_ai_sync_power_effect = {
    # 2.6.2: powers are native to the fame trait. Retain this marker solely for old-save/UI
    # compatibility; it intentionally carries no statistics.
    if = {
        limit = {
            has_trait = domcom_human_among_ai_trait
            NOT = { has_character_modifier = domcom_human_ai_contained_modifier }
            NOT = { has_character_modifier = domcom_human_ai_godsbane_modifier }
        }
        if = {
            limit = { NOT = { has_character_modifier = domcom_human_among_ai_power_modifier } }
            add_character_modifier = { modifier = domcom_human_among_ai_power_modifier }
        }
    }
    else = { remove_character_modifier = domcom_human_among_ai_power_modifier }
}

# One of the three frozen-time exemptions is consumed only by Dominion's explicitly coercive superhuman
# actions. Those actions normally carry diplomatic consequences; while time is stopped, they do not.
domcom_human_ai_consume_time_charge_effect = {
    if = {
        limit = { has_variable = domcom_human_ai_time_charges var:domcom_human_ai_time_charges > 0 }
        change_variable = { name = domcom_human_ai_time_charges subtract = 1 }
        if = {
            limit = { var:domcom_human_ai_time_charges <= 0 }
            remove_variable = domcom_human_ai_time_charges
            remove_character_modifier = domcom_human_ai_time_frozen_modifier
        }
    }
}

# Script-only outcomes used by the yearly Human Among AI political response. Keeping the war in a
# scripted effect, with the CB itself marked ai = no, prevents CK3's generic AI war planner from
# selecting the containment CB independently of Dominion's pacing rules.
domcom_human_ai_capitulation_response_effect = {
    scope:domcom_human_ai_responder = {
        add_opinion = { target = scope:domcom_human_ai_patron modifier = domcom_human_ai_awe_opinion }
    }
    start_tributary_interaction_effect = { TRIBUTARY = scope:domcom_human_ai_responder SUZERAIN = scope:domcom_human_ai_patron }
    send_interface_toast = { type = event_toast_effect_good title = DOMCOM_HUMAN_AI_CAPITULATION_TOAST left_icon = scope:domcom_human_ai_responder right_icon = scope:domcom_human_ai_patron }
}

domcom_human_ai_containment_response_effect = {
    # One containment war is enough to represent the political response for a long time. A scripted
    # war result also has to pass a final sanity gate: the responder must be at peace and at least as
    # strong as the Human Among AI ruler. A weak or already-committed AI simply declines escalation.
    if = {
        limit = {
            scope:domcom_human_ai_responder = {
                is_alive = yes
                is_landed = yes
                is_at_war = no
                current_military_strength >= scope:domcom_human_ai_patron.current_military_strength
                NOT = { has_character_flag = domcom_human_ai_recent_containment_attacker }
            }
        }
        add_character_flag = { flag = domcom_human_ai_containment_cooldown years = 10 }
        scope:domcom_human_ai_responder = {
            add_character_flag = { flag = domcom_human_ai_recent_containment_attacker years = 15 }
            start_war = { cb = domcom_human_ai_containment_war target = scope:domcom_human_ai_patron }
        }
    }
}

# Annual political response to a player who is visibly beyond ordinary rulers. The existing AI Activity
# rule now controls military escalation too instead of only relationship activity. Even Chaotic is capped
# by ten/fifteen-year cooldowns; Standard makes containment wars uncommon and Conservative nearly removes
# them. Tributary submission remains available at the same rate across settings.
domcom_human_ai_yearly_threat_effect = {
    save_scope_as = domcom_human_ai_patron
    domcom_human_ai_sync_power_effect = yes
    if = {
        limit = { has_trait = domcom_human_among_ai_trait is_alive = yes is_landed = yes is_independent_ruler = yes
            NOT = { has_character_modifier = domcom_human_ai_contained_modifier }
            NOT = { has_character_modifier = domcom_human_ai_godsbane_modifier }
            NOT = { has_character_flag = domcom_human_ai_containment_cooldown }
        }
        random_ruler = {
            limit = {
                domcom_human_ai_independent_threat_target_trigger = yes
                NOT = { is_at_war_with = scope:domcom_human_ai_patron }
                NOT = { has_character_flag = domcom_human_ai_recent_containment_attacker }
            }
            save_scope_as = domcom_human_ai_responder
        }
        if = {
            limit = { exists = scope:domcom_human_ai_responder }
            if = {
                limit = { has_game_rule = domcom_ai_activity_conservative }
                random_list = {
                    74 = { }
                    25 = { domcom_human_ai_capitulation_response_effect = yes }
                    1 = { domcom_human_ai_containment_response_effect = yes }
                }
            }
            else_if = {
                limit = { has_game_rule = domcom_ai_activity_aggressive }
                random_list = {
                    65 = { }
                    25 = { domcom_human_ai_capitulation_response_effect = yes }
                    10 = { domcom_human_ai_containment_response_effect = yes }
                }
            }
            else_if = {
                limit = { has_game_rule = domcom_ai_activity_chaotic }
                random_list = {
                    60 = { }
                    25 = { domcom_human_ai_capitulation_response_effect = yes }
                    15 = { domcom_human_ai_containment_response_effect = yes }
                }
            }
            else = {
                # Standard/default: a containment war is a rare annual outcome, not a background war generator.
                random_list = {
                    70 = { }
                    25 = { domcom_human_ai_capitulation_response_effect = yes }
                    5 = { domcom_human_ai_containment_response_effect = yes }
                }
            }
        }
    }
}

# One click searches the current diplomatic range. Invitations are automatic, but acceptance is not literally
# guaranteed; strategic/genetic candidates are heavily inclined to accept a being carrying this trait.
domcom_human_ai_invite_apex_breed_effect = {
    save_scope_as = domcom_human_ai_patron
    clear_variable_list = domcom_human_ai_apex_queue
    set_variable = { name = domcom_human_ai_apex_invited value = 0 }
    set_variable = { name = domcom_human_ai_apex_accepted value = 0 }

    # 2.6.3: invitations are mass; conceptions are deliberately batched later. Do not create twenty
    # vanilla Lover relations at once: this is a breeding program, not an automatic love affair.
    every_living_character = {
        limit = { domcom_human_ai_apex_woman_trigger = yes }
        save_temporary_scope_as = domcom_human_ai_apex_candidate
        scope:domcom_human_ai_patron = { change_variable = { name = domcom_human_ai_apex_invited add = 1 } }
        random_list = {
            85 = {
                scope:domcom_human_ai_patron = {
                    change_variable = { name = domcom_human_ai_apex_accepted add = 1 }
                }
                # Recruitment/court movement is age-agnostic. Reproductive state is not attached until
                # the recruit is an adult and visibly fertile.
                if = {
                    limit = { age >= 18 is_visibly_fertile = yes is_pregnant = no }
                    scope:domcom_human_ai_patron = {
                        add_to_variable_list = { name = domcom_human_ai_apex_queue target = scope:domcom_human_ai_apex_candidate }
                        add_to_variable_list = { name = domcom_human_ai_apex_partners target = scope:domcom_human_ai_apex_candidate }
                    }
                    set_variable = { name = domcom_human_ai_apex_patron value = scope:domcom_human_ai_patron }
                    add_character_flag = domcom_human_ai_apex_partner
                }
                if = {
                    limit = { is_landed = no NOT = { employer = scope:domcom_human_ai_patron } }
                    set_employer = scope:domcom_human_ai_patron
                }
            }
            15 = { }
        }
    }
    send_interface_toast = { type = event_toast_effect_good title = DOMCOM_HUMAN_AI_APEX_RESULT_TOAST left_icon = root }
}

# Process at most two accepted Apex partners per simulated month. This intentionally spreads vanilla
# pregnancy and later birth notifications over time instead of creating a single enormous popup burst.
domcom_human_ai_process_apex_queue_effect = {
    if = {
        limit = {
            is_ai = no
            is_alive = yes
            age >= 18
            has_trait = domcom_human_among_ai_trait
            NOT = { has_character_modifier = domcom_human_ai_contained_modifier }
            NOT = { has_character_modifier = domcom_human_ai_godsbane_modifier }
            is_male = yes
            is_visibly_fertile = yes
            has_variable_list = domcom_human_ai_apex_queue
        }
        save_scope_as = domcom_human_ai_patron
        set_variable = { name = domcom_human_ai_apex_conceived_this_month value = 0 }
        ordered_in_list = {
            variable = domcom_human_ai_apex_queue
            limit = {
                is_alive = yes
                age >= 18
                is_female = yes
                is_visibly_fertile = yes
                is_pregnant = no
                has_variable = domcom_human_ai_apex_patron
                var:domcom_human_ai_apex_patron = scope:domcom_human_ai_patron
                NOT = { has_character_flag = domcom_human_ai_apex_program_complete }
            }
            order_by = domcom_human_ai_apex_queue_priority_value
            max = 2
            check_range_bounds = no
            save_temporary_scope_as = domcom_human_ai_apex_candidate
            make_pregnant = { father = scope:domcom_human_ai_patron number_of_children = 1 known_bastard = no }
            add_character_flag = domcom_human_ai_apex_program_complete
            scope:domcom_human_ai_patron = {
                change_variable = { name = domcom_human_ai_apex_conceived_this_month add = 1 }
            }
        }
    }
}



# -----------------------------------------------------------------------------
# 2.6.5 — POWER TRIP
# -----------------------------------------------------------------------------
# Called after the activity physically reaches the selected realm capital. The same stored percentage
# is shown to the player and used for the actual roll. It is intentionally world-state driven and
# clamped to 85–99% while the Human Amongst AI character is fully powered.
domcom_power_trip_prepare_effect = {
    set_variable = { name = domcom_power_trip_success_chance value = 99 }
    set_variable = { name = domcom_power_trip_godsbane_chance value = 2 }

    scope:domcom_power_trip_target = {
        # Military readiness relative to the superhuman's actual current forces.
        if = {
            limit = { current_military_strength > scope:domcom_power_trip_actor.current_military_strength }
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 2 } }
        }
        if = {
            limit = { current_military_strength >= scope:domcom_power_trip_actor.fifty_percent_more_of_current_military_strength }
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 2 } }
        }
        if = {
            limit = {
                any_ally = { current_military_strength > scope:domcom_power_trip_actor.current_military_strength }
            }
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
        }

        # Realm complexity and physical depth — never static troop thresholds.
        if = { limit = { realm_size >= 20 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = { limit = { realm_size >= 50 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = { limit = { realm_size >= 100 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = { limit = { primary_title.tier >= tier_kingdom } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = { limit = { primary_title.tier >= tier_empire } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }

        # Leadership and elite resistance.
        if = { limit = { martial >= scope:domcom_power_trip_actor.martial } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = { limit = { prowess >= 35 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } } }
        if = {
            limit = { any_courtier_or_guest = { count >= 5 age >= 18 prowess >= 25 } }
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
        }
        if = {
            limit = { any_courtier_or_guest = { count >= 10 age >= 18 prowess >= 20 } }
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
        }

        # Developed capitals are better able to coordinate resistance and research counters.
        if = { limit = { capital_county.development_level >= 25 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }
        if = { limit = { capital_county.development_level >= 50 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }

        # The world learns from previous encounters instead of getting an arbitrary "trip number" malus.
        if = { limit = { has_variable = domcom_power_trip_knowledge var:domcom_power_trip_knowledge >= 1 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 1 } } }
        if = { limit = { has_variable = domcom_power_trip_knowledge var:domcom_power_trip_knowledge >= 3 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }
        if = { limit = { has_variable = domcom_power_trip_knowledge var:domcom_power_trip_knowledge >= 6 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 3 } } }
        if = { limit = { has_variable = domcom_power_trip_knowledge var:domcom_power_trip_knowledge >= 9 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_success_chance subtract = 1 } change_variable = { name = domcom_power_trip_godsbane_chance add = 3 } } }

        # Godsbane research is a failure-only roll, but its projected chance is derived now for the UI.
        if = { limit = { learning >= 15 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }
        if = { limit = { learning >= 25 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }
        if = { limit = { learning >= 35 } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 2 } } }
        if = { limit = { any_courtier_or_guest = { count >= 1 age >= 18 learning >= 25 } } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 3 } } }
        if = { limit = { any_courtier_or_guest = { count >= 1 age >= 18 learning >= 35 } } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 3 } } }
        if = { limit = { primary_title.tier >= tier_kingdom } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 1 } } }
        if = { limit = { primary_title.tier >= tier_empire } scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_godsbane_chance add = 1 } } }
    }

    # Current condition matters. A wounded, stressed superhuman can still be overwhelming, just less perfect.
    if = { limit = { stress >= 100 } change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
    if = { limit = { stress >= 200 } change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
    if = { limit = { has_trait = wounded_1 } change_variable = { name = domcom_power_trip_success_chance subtract = 1 } }
    else_if = { limit = { has_trait = wounded_2 } change_variable = { name = domcom_power_trip_success_chance subtract = 2 } }
    else_if = { limit = { has_trait = wounded_3 } change_variable = { name = domcom_power_trip_success_chance subtract = 3 } }

    # Very exceptional player builds can claw back some lost probability but never exceed 99%.
    if = { limit = { prowess >= 150 } change_variable = { name = domcom_power_trip_success_chance add = 1 } }
    if = { limit = { prowess >= 200 } change_variable = { name = domcom_power_trip_success_chance add = 1 } }
    if = { limit = { martial >= 50 } change_variable = { name = domcom_power_trip_success_chance add = 1 } }

    clamp_variable = { name = domcom_power_trip_success_chance min = 85 max = 99 }
    clamp_variable = { name = domcom_power_trip_godsbane_chance min = 0 max = 25 }
}

# Permanent Dominion loyalty state used by successful Power Trips. The generic obedience refresh also
# recognizes this flag, so ordinary relationship decay cannot pull these survivors below 1000.
domcom_power_trip_bind_woman_effect = {
    set_variable = { name = domcom_obedience_patron value = scope:domcom_power_trip_actor }
    set_variable = { name = domcom_obedience value = 1000 }
    add_character_flag = domcom_power_trip_obedience_lock
    add_opinion = { target = scope:domcom_power_trip_actor modifier = domcom_power_trip_bound_opinion }
}

# Knowledge is attached to actual rulers who have learned from what happened. Nearby independent rulers
# receive less knowledge than the target/successor, so adaptation is geographically and politically emergent.
domcom_power_trip_spread_knowledge_effect = {
    every_independent_ruler = {
        limit = {
            is_alive = yes
            is_ai = yes
            this != scope:domcom_power_trip_actor
            in_diplomatic_range = scope:domcom_power_trip_actor
        }
        if = { limit = { NOT = { has_variable = domcom_power_trip_knowledge } } set_variable = { name = domcom_power_trip_knowledge value = 0 } }
        change_variable = { name = domcom_power_trip_knowledge add = 1 }
        clamp_variable = { name = domcom_power_trip_knowledge min = 0 max = 10 }
    }
}

domcom_power_trip_spread_failure_knowledge_effect = {
    every_independent_ruler = {
        limit = {
            is_alive = yes
            is_ai = yes
            this != scope:domcom_power_trip_actor
            in_diplomatic_range = scope:domcom_power_trip_actor
        }
        if = { limit = { NOT = { has_variable = domcom_power_trip_knowledge } } set_variable = { name = domcom_power_trip_knowledge value = 0 } }
        change_variable = { name = domcom_power_trip_knowledge add = 2 }
        clamp_variable = { name = domcom_power_trip_knowledge min = 0 max = 10 }
    }
}

# Select the new Apex political head and distribute additional counties before subordinating the new realm.
# This intentionally reuses vanilla title/vassal changes rather than fake Dominion-only landed states.
domcom_power_trip_install_apex_rulers_effect = {
    # Pick the strongest Apex survivor; if none exists, fall back to the strongest surviving adult
    # from the protected sex so a tributary/replacement regime is never built around somebody about to die.
    if = {
        limit = { has_variable_list = domcom_power_trip_apex_list }
        ordered_in_list = {
            variable = domcom_power_trip_apex_list
            limit = { is_alive = yes age >= 18 }
            order_by = domcom_power_trip_apex_ruler_value
            max = 1
            check_range_bounds = no
            save_scope_as = domcom_power_trip_apex_regent
        }
    }
    if = {
        limit = { NOT = { exists = scope:domcom_power_trip_apex_regent } has_variable_list = domcom_power_trip_survivor_list }
        ordered_in_list = {
            variable = domcom_power_trip_survivor_list
            limit = { is_alive = yes age >= 18 }
            order_by = domcom_power_trip_apex_ruler_value
            max = 1
            check_range_bounds = no
            save_scope_as = domcom_power_trip_apex_regent
        }
    }

    if = {
        limit = { exists = scope:domcom_power_trip_target_primary_title }
        # Default / chosen "vassalize" result. If the target is below the player's rank, preserve
        # it as an Apex-headed vassal realm. If it is equal or higher, absorb the top title into the
        # player's realm instead of silently falling back to tributary status.
        if = {
            limit = { var:domcom_power_trip_political_outcome = 1 }
            if = {
                limit = {
                    exists = scope:domcom_power_trip_apex_regent
                    scope:domcom_power_trip_actor.primary_title.tier > scope:domcom_power_trip_target_primary_title.tier
                }
                create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_regime_change add_claim_on_loss = no }
                scope:domcom_power_trip_target_primary_title = {
                    change_title_holder = {
                        holder = scope:domcom_power_trip_apex_regent
                        change = scope:domcom_power_trip_regime_change
                        take_baronies = no
                    }
                }
                resolve_title_and_vassal_change = scope:domcom_power_trip_regime_change
                create_title_and_vassal_change = { type = swear_fealty save_scope_as = domcom_power_trip_subject_change add_claim_on_loss = no }
                scope:domcom_power_trip_apex_regent = { change_liege = { liege = scope:domcom_power_trip_actor change = scope:domcom_power_trip_subject_change } }
                resolve_title_and_vassal_change = scope:domcom_power_trip_subject_change
            }
            else = {
                create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_absorb_change add_claim_on_loss = no }
                scope:domcom_power_trip_target_primary_title = {
                    change_title_holder = {
                        holder = scope:domcom_power_trip_actor
                        change = scope:domcom_power_trip_absorb_change
                        take_baronies = no
                    }
                }
                resolve_title_and_vassal_change = scope:domcom_power_trip_absorb_change
            }
        }
        # Optional tributary result. A protected survivor is installed first where possible, so the
        # tributary relationship is not immediately destroyed by the decimation succession cascade.
        else_if = {
            limit = { var:domcom_power_trip_political_outcome = 2 }
            if = {
                limit = { exists = scope:domcom_power_trip_apex_regent }
                create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_regime_change add_claim_on_loss = no }
                scope:domcom_power_trip_target_primary_title = {
                    change_title_holder = {
                        holder = scope:domcom_power_trip_apex_regent
                        change = scope:domcom_power_trip_regime_change
                        take_baronies = no
                    }
                }
                resolve_title_and_vassal_change = scope:domcom_power_trip_regime_change
                if = {
                    limit = { scope:domcom_power_trip_apex_regent = { is_independent_ruler = yes } }
                    start_tributary_interaction_effect = { TRIBUTARY = scope:domcom_power_trip_apex_regent SUZERAIN = scope:domcom_power_trip_actor }
                }
            }
            else_if = {
                limit = { scope:domcom_power_trip_target = { is_alive = yes is_independent_ruler = yes } }
                start_tributary_interaction_effect = { TRIBUTARY = scope:domcom_power_trip_target SUZERAIN = scope:domcom_power_trip_actor }
            }
        }
    }

    # Preserve the target's full top-tier crown, not only its primary title. Partition can otherwise
    # split secondary kingdoms/empires the instant a targeted ruler dies. The crown-title list was
    # snapshotted on arrival and all same-tier titles follow the political outcome chosen above.
    if = {
        limit = { has_variable_list = domcom_power_trip_target_crown_titles }
        scope:domcom_power_trip_actor = {
            every_in_list = {
                variable = domcom_power_trip_target_crown_titles
                limit = { this != scope:domcom_power_trip_target_primary_title exists = holder }
                save_temporary_scope_as = domcom_power_trip_extra_crown_title
                if = {
                    limit = {
                        scope:domcom_power_trip_actor = { var:domcom_power_trip_political_outcome = 1 }
                        exists = scope:domcom_power_trip_apex_regent
                        scope:domcom_power_trip_actor.primary_title.tier > scope:domcom_power_trip_target_primary_title.tier
                    }
                    scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_extra_crown_change add_claim_on_loss = no } }
                    scope:domcom_power_trip_extra_crown_title = { change_title_holder = { holder = scope:domcom_power_trip_apex_regent change = scope:domcom_power_trip_extra_crown_change take_baronies = no } }
                    scope:domcom_power_trip_actor = { resolve_title_and_vassal_change = scope:domcom_power_trip_extra_crown_change }
                }
                else_if = {
                    limit = { scope:domcom_power_trip_actor = { var:domcom_power_trip_political_outcome = 1 } }
                    scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_extra_crown_change add_claim_on_loss = no } }
                    scope:domcom_power_trip_extra_crown_title = { change_title_holder = { holder = scope:domcom_power_trip_actor change = scope:domcom_power_trip_extra_crown_change take_baronies = no } }
                    scope:domcom_power_trip_actor = { resolve_title_and_vassal_change = scope:domcom_power_trip_extra_crown_change }
                }
                else_if = {
                    limit = { scope:domcom_power_trip_actor = { var:domcom_power_trip_political_outcome = 2 } exists = scope:domcom_power_trip_apex_regent }
                    scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = conquest save_scope_as = domcom_power_trip_extra_crown_change add_claim_on_loss = no } }
                    scope:domcom_power_trip_extra_crown_title = { change_title_holder = { holder = scope:domcom_power_trip_apex_regent change = scope:domcom_power_trip_extra_crown_change take_baronies = no } }
                    scope:domcom_power_trip_actor = { resolve_title_and_vassal_change = scope:domcom_power_trip_extra_crown_change }
                }
            }
        }
    }

    # Put the replacement elite in positions of power using counties that belonged to the target
    # realm at arrival. This avoids sacrificing the player's old core domain when an equal-rank realm
    # is absorbed directly.
    if = {
        limit = { has_variable_list = domcom_power_trip_apex_list has_variable_list = domcom_power_trip_target_counties }

        # If absorption made the chosen regent landless, give them the first available target county.
        # The title list belongs to the Power Trip actor, so all list draws are explicitly executed in
        # actor scope; otherwise nested ordered-list scopes can accidentally look for the list on the
        # Apex candidate instead.
        if = {
            limit = { exists = scope:domcom_power_trip_apex_regent scope:domcom_power_trip_apex_regent = { is_landed = no } }
            scope:domcom_power_trip_actor = {
                random_in_list = {
                    variable = domcom_power_trip_target_counties
                    limit = { exists = holder }
                    save_temporary_scope_as = domcom_power_trip_regent_county
                    create_title_and_vassal_change = { type = granted save_scope_as = domcom_power_trip_county_change add_claim_on_loss = no }
                    change_title_holder = {
                        holder = scope:domcom_power_trip_apex_regent
                        change = scope:domcom_power_trip_county_change
                        take_baronies = yes
                        government_base = scope:domcom_power_trip_actor
                    }
                    resolve_title_and_vassal_change = scope:domcom_power_trip_county_change
                    # A regent who only received a county because the target crown was absorbed belongs
                    # directly under the superhuman rather than emerging as an accidental independent count.
                    scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = swear_fealty save_scope_as = domcom_power_trip_regent_liege_change add_claim_on_loss = no } }
                    scope:domcom_power_trip_apex_regent = { change_liege = { liege = scope:domcom_power_trip_actor change = scope:domcom_power_trip_regent_liege_change } }
                    scope:domcom_power_trip_actor = {
                        resolve_title_and_vassal_change = scope:domcom_power_trip_regent_liege_change
                        remove_list_variable = { name = domcom_power_trip_target_counties target = scope:domcom_power_trip_regent_county }
                    }
                }
            }
        }

        ordered_in_list = {
            variable = domcom_power_trip_apex_list
            limit = { is_alive = yes age >= 18 is_landed = no NOT = { this = scope:domcom_power_trip_apex_regent } }
            order_by = domcom_power_trip_apex_ruler_value
            max = 12
            check_range_bounds = no
            save_temporary_scope_as = domcom_power_trip_apex_grantee
            scope:domcom_power_trip_actor = {
                random_in_list = {
                    variable = domcom_power_trip_target_counties
                    limit = { exists = holder holder != scope:domcom_power_trip_apex_grantee }
                    save_temporary_scope_as = domcom_power_trip_grant_county
                    create_title_and_vassal_change = { type = granted save_scope_as = domcom_power_trip_county_change add_claim_on_loss = no }
                    change_title_holder = {
                        holder = scope:domcom_power_trip_apex_grantee
                        change = scope:domcom_power_trip_county_change
                        take_baronies = yes
                        government_base = scope:domcom_power_trip_actor
                    }
                    resolve_title_and_vassal_change = scope:domcom_power_trip_county_change
                    # Keep every replacement count inside the reconstructed target instead of relying
                    # on CK3 to infer a liege from whichever previous holder owned the county.
                    if = {
                        limit = {
                            exists = scope:domcom_power_trip_apex_regent
                            scope:domcom_power_trip_target_primary_title.holder = scope:domcom_power_trip_apex_regent
                        }
                        scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = swear_fealty save_scope_as = domcom_power_trip_apex_liege_change add_claim_on_loss = no } }
                        scope:domcom_power_trip_apex_grantee = { change_liege = { liege = scope:domcom_power_trip_apex_regent change = scope:domcom_power_trip_apex_liege_change } }
                        scope:domcom_power_trip_actor = { resolve_title_and_vassal_change = scope:domcom_power_trip_apex_liege_change }
                    }
                    else = {
                        scope:domcom_power_trip_actor = { create_title_and_vassal_change = { type = swear_fealty save_scope_as = domcom_power_trip_apex_liege_change add_claim_on_loss = no } }
                        scope:domcom_power_trip_apex_grantee = { change_liege = { liege = scope:domcom_power_trip_actor change = scope:domcom_power_trip_apex_liege_change } }
                        scope:domcom_power_trip_actor = { resolve_title_and_vassal_change = scope:domcom_power_trip_apex_liege_change }
                    }
                    scope:domcom_power_trip_actor = {
                        remove_list_variable = { name = domcom_power_trip_target_counties target = scope:domcom_power_trip_grant_county }
                    }
                }
            }
        }
    }

}

# Complete-success path. Children are never targets. In the default male-decimation path, adult Apex women
# are preserved, loyalty-locked, queued for staggered adult conception, and used to rebuild the political order.
domcom_power_trip_success_effect = {
    set_variable = { name = domcom_power_trip_eligible value = 0 }
    set_variable = { name = domcom_power_trip_killed value = 0 }
    set_variable = { name = domcom_power_trip_enslaved value = 0 }
    clear_variable_list = domcom_power_trip_apex_list
    clear_variable_list = domcom_power_trip_survivor_list
    clear_variable_list = domcom_power_trip_victim_list
    clear_variable_list = domcom_power_trip_target_counties
    clear_variable_list = domcom_power_trip_target_crown_titles

    # Snapshot every same-tier crown title held by the original target. This prevents secondary
    # kingdoms/empires from partitioning away when the old ruling class is killed.
    if = {
        limit = { exists = scope:domcom_power_trip_target exists = scope:domcom_power_trip_target_primary_title }
        scope:domcom_power_trip_target = {
            every_held_title = {
                limit = {
                    OR = {
                        AND = { scope:domcom_power_trip_target_primary_title.tier = tier_duchy tier = tier_duchy }
                        AND = { scope:domcom_power_trip_target_primary_title.tier = tier_kingdom tier = tier_kingdom }
                        AND = { scope:domcom_power_trip_target_primary_title.tier = tier_empire tier = tier_empire }
                        AND = { scope:domcom_power_trip_target_primary_title.tier = tier_hegemony tier = tier_hegemony }
                    }
                }
                save_temporary_scope_as = domcom_power_trip_crown_title
                scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_target_crown_titles target = scope:domcom_power_trip_crown_title } }
            }
        }
    }

    # Snapshot target-realm counties too, so reconstructed Apex rulers receive land from the country
    # being remade rather than accidentally being handed the superhuman's home counties.
    every_living_character = {
        limit = { is_alive = yes is_landed = yes top_liege = scope:domcom_power_trip_target }
        every_held_title = {
            limit = { tier = tier_county }
            save_temporary_scope_as = domcom_power_trip_target_county
            scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_target_counties target = scope:domcom_power_trip_target_county } }
        }
    }

    # Snapshot the original realm before title changes or deaths. This keeps succession from shrinking
    # the target pool halfway through the campaign.
    if = {
        limit = { var:domcom_power_trip_mode = 1 }
        every_living_character = {
            limit = { is_alive = yes age >= 18 is_female = yes top_liege = scope:domcom_power_trip_target this != scope:domcom_power_trip_actor }
            save_temporary_scope_as = domcom_power_trip_survivor_candidate
            scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_survivor_list target = scope:domcom_power_trip_survivor_candidate } }
            if = {
                limit = { domcom_power_trip_apex_woman_trigger = yes }
                scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_apex_list target = scope:domcom_power_trip_survivor_candidate } }
            }
        }
        every_living_character = {
            limit = { is_alive = yes age >= 18 is_male = yes top_liege = scope:domcom_power_trip_target this != scope:domcom_power_trip_actor }
            save_temporary_scope_as = domcom_power_trip_victim_candidate
            scope:domcom_power_trip_actor = {
                add_to_variable_list = { name = domcom_power_trip_victim_list target = scope:domcom_power_trip_victim_candidate }
                change_variable = { name = domcom_power_trip_eligible add = 1 }
            }
        }
        # Consolidate/install the post-trip regime before killing the old political class. This stops
        # CK3 succession from fragmenting the realm and only afterwards trying to stitch it back together.
        domcom_power_trip_install_apex_rulers_effect = yes
    }
    else_if = {
        limit = { var:domcom_power_trip_mode = 2 }
        every_living_character = {
            limit = { is_alive = yes age >= 18 is_male = yes top_liege = scope:domcom_power_trip_target this != scope:domcom_power_trip_actor }
            save_temporary_scope_as = domcom_power_trip_survivor_candidate
            scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_survivor_list target = scope:domcom_power_trip_survivor_candidate } }
            if = {
                limit = { domcom_power_trip_apex_man_trigger = yes }
                scope:domcom_power_trip_actor = { add_to_variable_list = { name = domcom_power_trip_apex_list target = scope:domcom_power_trip_survivor_candidate } }
            }
        }
        every_living_character = {
            limit = { is_alive = yes age >= 18 is_female = yes top_liege = scope:domcom_power_trip_target this != scope:domcom_power_trip_actor }
            save_temporary_scope_as = domcom_power_trip_victim_candidate
            scope:domcom_power_trip_actor = {
                add_to_variable_list = { name = domcom_power_trip_victim_list target = scope:domcom_power_trip_victim_candidate }
                change_variable = { name = domcom_power_trip_eligible add = 1 }
            }
        }
        domcom_power_trip_install_apex_rulers_effect = yes
    }
    else_if = {
        limit = { var:domcom_power_trip_mode = 3 domcom_csr_living_market_available_trigger = yes }
        # The bridge uses CSR's own enslavement effect with drama suppressed to avoid hundreds of popups.
        domcom_csr_power_trip_enslave_realm_effect = yes
        # Political restructuring comes after the population has been enslaved so the original realm
        # scope remains intact for the bridge scan.
        domcom_power_trip_install_apex_rulers_effect = yes
    }

    if = {
        limit = { OR = { var:domcom_power_trip_mode = 1 var:domcom_power_trip_mode = 2 } }
        every_in_list = {
            variable = domcom_power_trip_victim_list
            limit = { is_alive = yes age >= 18 }
            save_temporary_scope_as = domcom_power_trip_victim
            scope:domcom_power_trip_actor = { change_variable = { name = domcom_power_trip_killed add = 1 } }
            death = { death_reason = death_murder killer = scope:domcom_power_trip_actor }
        }

        # Every protected adult survivor is obedience-locked. Mode 1 protects women; mode 2 protects men.
        if = {
            limit = { has_variable_list = domcom_power_trip_survivor_list }
            every_in_list = {
                variable = domcom_power_trip_survivor_list
                limit = { is_alive = yes age >= 18 }
                domcom_power_trip_bind_woman_effect = yes
            }
        }
    }

    # Default lineage-replacement path: stagger conceptions through the existing 2/month Apex queue.
    if = {
        limit = { var:domcom_power_trip_mode = 1 is_male = yes age >= 18 is_visibly_fertile = yes has_variable_list = domcom_power_trip_apex_list }
        ordered_in_list = {
            variable = domcom_power_trip_apex_list
            limit = { is_alive = yes age >= 18 is_female = yes is_pregnant = no is_visibly_fertile = yes }
            order_by = domcom_power_trip_apex_ruler_value
            max = 100
            check_range_bounds = no
            save_temporary_scope_as = domcom_power_trip_apex_candidate
            add_to_variable_list = { name = domcom_human_ai_apex_queue target = scope:domcom_power_trip_apex_candidate }
            add_to_variable_list = { name = domcom_human_ai_apex_partners target = scope:domcom_power_trip_apex_candidate }
            scope:domcom_power_trip_apex_candidate = {
                set_variable = { name = domcom_human_ai_apex_patron value = scope:domcom_power_trip_actor }
                add_character_flag = domcom_human_ai_apex_partner
                add_character_flag = domcom_power_trip_apex_mother
                remove_character_flag = domcom_human_ai_apex_program_complete
            }
        }
    }

    # Resolve the post-trip political head for result portraits / future knowledge.
    if = {
        limit = { exists = scope:domcom_power_trip_target_primary_title.holder }
        scope:domcom_power_trip_target_primary_title.holder.top_liege = { save_scope_as = domcom_power_trip_post_target }
    }

    add_character_modifier = { modifier = domcom_power_trip_sated_modifier years = 3 }
    add_prestige = 500
    domcom_power_trip_spread_knowledge_effect = yes
}

# Failure still devastates the selected target pool. Severity is weighted by the actual projected odds:
# the closer the realm pushed the superhuman toward the 85% floor, the more likely a bad failure becomes.
domcom_power_trip_failure_effect = {
    set_variable = { name = domcom_power_trip_failure_severity value = 1 }
    if = {
        limit = { var:domcom_power_trip_success_chance >= 95 }
        random_list = { 60 = { set_variable = { name = domcom_power_trip_failure_severity value = 1 } } 30 = { set_variable = { name = domcom_power_trip_failure_severity value = 2 } } 10 = { set_variable = { name = domcom_power_trip_failure_severity value = 3 } } }
    }
    else_if = {
        limit = { var:domcom_power_trip_success_chance >= 90 }
        random_list = { 35 = { set_variable = { name = domcom_power_trip_failure_severity value = 1 } } 45 = { set_variable = { name = domcom_power_trip_failure_severity value = 2 } } 20 = { set_variable = { name = domcom_power_trip_failure_severity value = 3 } } }
    }
    else = {
        random_list = { 20 = { set_variable = { name = domcom_power_trip_failure_severity value = 1 } } 45 = { set_variable = { name = domcom_power_trip_failure_severity value = 2 } } 35 = { set_variable = { name = domcom_power_trip_failure_severity value = 3 } } }
    }

    set_variable = { name = domcom_power_trip_failure_kill_percent value = 65 }
    set_variable = { name = domcom_power_trip_capture_chance value = 5 }
    if = { limit = { var:domcom_power_trip_failure_severity = 2 } set_variable = { name = domcom_power_trip_failure_kill_percent value = 50 } set_variable = { name = domcom_power_trip_capture_chance value = 15 } }
    if = { limit = { var:domcom_power_trip_failure_severity = 3 } set_variable = { name = domcom_power_trip_failure_kill_percent value = 35 } set_variable = { name = domcom_power_trip_capture_chance value = 30 } }

    set_variable = { name = domcom_power_trip_eligible value = 0 }
    set_variable = { name = domcom_power_trip_killed value = 0 }
    set_variable = { name = domcom_power_trip_enslaved value = 0 }
    clear_variable_list = domcom_power_trip_victim_list

    if = {
        limit = { var:domcom_power_trip_mode = 3 domcom_csr_living_market_available_trigger = yes }
        domcom_csr_power_trip_partial_enslave_effect = yes
        # Reuse the subdued count for resistance math below; result text uses the dedicated enslaved variable.
        set_variable = { name = domcom_power_trip_killed value = var:domcom_power_trip_enslaved }
    }
    else = {
        # Snapshot before deaths for the same reason as complete success: succession cannot shrink the pool halfway through.
        every_living_character = {
            limit = {
                is_alive = yes
                top_liege = scope:domcom_power_trip_target
                this != scope:domcom_power_trip_actor
                OR = {
                    AND = { scope:domcom_power_trip_actor = { var:domcom_power_trip_mode = 1 } is_male = yes }
                    AND = { scope:domcom_power_trip_actor = { var:domcom_power_trip_mode = 2 } is_female = yes }
                }
            }
            save_temporary_scope_as = domcom_power_trip_failure_victim
            scope:domcom_power_trip_actor = {
                add_to_variable_list = { name = domcom_power_trip_victim_list target = scope:domcom_power_trip_failure_victim }
                change_variable = { name = domcom_power_trip_eligible add = 1 }
            }
        }

        every_in_list = {
            variable = domcom_power_trip_victim_list
            limit = { is_alive = yes }
            save_temporary_scope_as = domcom_power_trip_failure_victim
            scope:domcom_power_trip_actor = {
                random = {
                    chance = var:domcom_power_trip_failure_kill_percent
                    change_variable = { name = domcom_power_trip_killed add = 1 }
                    scope:domcom_power_trip_failure_victim = { death = { death_reason = death_murder killer = scope:domcom_power_trip_actor } }
                }
            }
        }
    }

    # What actually survived matters, not just the pre-trip projection. A resistance that leaves more of
    # the selected population standing is more likely to maim or capture the superhuman.
    set_variable = { name = domcom_power_trip_survivors value = var:domcom_power_trip_eligible }
    change_variable = { name = domcom_power_trip_survivors subtract = var:domcom_power_trip_killed }
    set_variable = { name = domcom_power_trip_survivor_percent value = 0 }
    if = {
        limit = { var:domcom_power_trip_eligible > 0 }
        set_variable = { name = domcom_power_trip_survivor_percent value = var:domcom_power_trip_survivors }
        change_variable = { name = domcom_power_trip_survivor_percent multiply = 100 }
        change_variable = { name = domcom_power_trip_survivor_percent divide = var:domcom_power_trip_eligible }
    }
    if = {
        limit = { var:domcom_power_trip_survivor_percent >= 60 }
        change_variable = { name = domcom_power_trip_failure_severity add = 1 }
        change_variable = { name = domcom_power_trip_capture_chance add = 10 }
    }
    if = {
        limit = { var:domcom_power_trip_survivor_percent >= 75 }
        change_variable = { name = domcom_power_trip_capture_chance add = 10 }
    }
    clamp_variable = { name = domcom_power_trip_failure_severity min = 1 max = 3 }

    add_stress = 200

    # Injury follows both projected resistance and the actual number of survivors. Maiming is rare on a
    # narrow failure but becomes a serious risk when the target still has a large resistance base left.
    if = {
        limit = { var:domcom_power_trip_failure_severity = 1 }
        random_list = { 73 = { add_trait_force_tooltip = wounded_1 } 22 = { add_trait_force_tooltip = wounded_2 } 4 = { add_trait_force_tooltip = wounded_3 } 1 = { add_trait_force_tooltip = maimed } }
    }
    else_if = {
        limit = { var:domcom_power_trip_failure_severity = 2 }
        random_list = { 20 = { add_trait_force_tooltip = wounded_1 } 50 = { add_trait_force_tooltip = wounded_2 } 23 = { add_trait_force_tooltip = wounded_3 } 7 = { add_trait_force_tooltip = maimed } }
    }
    else = {
        random_list = { 5 = { add_trait_force_tooltip = wounded_1 } 25 = { add_trait_force_tooltip = wounded_2 } 45 = { add_trait_force_tooltip = wounded_3 } 25 = { add_trait_force_tooltip = maimed } }
    }

    if = {
        limit = { exists = scope:domcom_power_trip_target_primary_title.holder }
        scope:domcom_power_trip_target_primary_title.holder.top_liege = { save_scope_as = domcom_power_trip_post_target }
    }

    # Strong surviving leadership increases the chance that failure becomes actual capture.
    if = { limit = { exists = scope:domcom_power_trip_post_target scope:domcom_power_trip_post_target = { prowess >= 35 } } change_variable = { name = domcom_power_trip_capture_chance add = 5 } }
    if = { limit = { exists = scope:domcom_power_trip_post_target scope:domcom_power_trip_post_target = { martial >= 35 } } change_variable = { name = domcom_power_trip_capture_chance add = 5 } }
    clamp_variable = { name = domcom_power_trip_capture_chance min = 0 max = 50 }

    # The failure-only Godsbane roll. Discovery permanently suppresses the trait's supernatural package
    # without deleting the public Fame trait; future recovery can therefore be a proper Dominion story chain.
    set_variable = { name = domcom_power_trip_godsbane_found value = 0 }
    random = {
        chance = var:domcom_power_trip_godsbane_chance
        set_variable = { name = domcom_power_trip_godsbane_found value = 1 }
        remove_character_modifier = domcom_human_ai_contained_modifier
        remove_character_modifier = domcom_human_among_ai_power_modifier
        add_character_modifier = { modifier = domcom_human_ai_godsbane_modifier }
        add_character_flag = domcom_human_ai_godsbane
    }

    set_variable = { name = domcom_power_trip_captured value = 0 }
    if = {
        limit = { exists = scope:domcom_power_trip_post_target }
        random = {
            chance = var:domcom_power_trip_capture_chance
            set_variable = { name = domcom_power_trip_captured value = 1 }
            scope:domcom_power_trip_post_target = { imprison = { target = scope:domcom_power_trip_actor type = dungeon } }
            if = {
                limit = { scope:domcom_power_trip_actor = { NOT = { has_character_modifier = domcom_human_ai_godsbane_modifier } } }
                scope:domcom_power_trip_actor = { add_character_modifier = { modifier = domcom_human_ai_contained_modifier years = 3 } }
            }
        }
    }

    domcom_power_trip_spread_failure_knowledge_effect = yes
    if = {
        limit = { exists = scope:domcom_power_trip_post_target }
        scope:domcom_power_trip_post_target = {
            if = { limit = { NOT = { has_variable = domcom_power_trip_knowledge } } set_variable = { name = domcom_power_trip_knowledge value = 0 } }
            change_variable = { name = domcom_power_trip_knowledge add = 3 }
            clamp_variable = { name = domcom_power_trip_knowledge min = 0 max = 10 }
        }
    }
}
domcom_power_trip_resolve_effect = {
    set_variable = { name = domcom_power_trip_roll_success value = 0 }
    random = { chance = var:domcom_power_trip_success_chance set_variable = { name = domcom_power_trip_roll_success value = 1 } }
    if = { limit = { var:domcom_power_trip_roll_success = 1 } domcom_power_trip_success_effect = yes }
    else = { domcom_power_trip_failure_effect = yes }
}

