namespace = qyv_ai_brain

# ============================================================
# ORGANIC AI BRAIN - Central coordinator pulse
# Runs yearly, evaluates situation, sets strategic priority flags
# ============================================================

character_event = {
    id = qyv_ai_brain.0010
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_organic_ai_enabled = root
    }

    mean_time_to_happen = { months = 12 }

    immediate = {
        # Clear all strategy flags first
        remove_character_flag = qyv_strat_survival
        remove_character_flag = qyv_strat_consolidation
        remove_character_flag = qyv_strat_stability
        remove_character_flag = qyv_strat_expansion
        remove_character_flag = qyv_strat_diplomacy
        remove_character_flag = qyv_strat_vassalization
        remove_character_flag = qyv_strat_development

        # GREAT POWER SUCCESSION SECURITY
        # Empires with partition succession fragment on the ruler's death.
        # Switch to primogeniture before expanding further - this is the
        # single biggest stability lever for large realms.
        if = {
            limit = {
                qyv_ai_is_great_power = root
                NOT = { has_crown_law = primogeniture_succession }
                NOT = { has_crown_law = primogeniture }
            }
            set_crown_law = primogeniture_succession
        }
        if = {
            limit = {
                qyv_ai_is_major_power = root
                NOT = { has_crown_law = primogeniture_succession }
                NOT = { has_crown_law = primogeniture }
                realm_size >= 40
            }
            set_crown_law = primogeniture_succession
        }

        # STRATEGIC DEPTH: Reactive - only survival, consolidation
        if = {
            limit = { qyv_ai_strategic_reactive = root }
            if = {
                limit = { qyv_ai_priority_survival = root }
                set_character_flag = qyv_strat_survival
                if = {
                    limit = {
                        qyv_ai_has_existential_threat = root
                        qyv_ai_can_send_tribute = root
                        NOT = { has_character_flag = qyv_paying_tribute_to_target }
                    }
                    qyv_send_tribute = yes
                }
            }
            else_if = {
                limit = { qyv_ai_priority_consolidation = root }
                set_character_flag = qyv_strat_consolidation
                set_character_flag = qyv_prioritize_consolidation
            }
            else_if = {
                limit = { qyv_ai_priority_stability = root }
                set_character_flag = qyv_strat_stability
                qyv_subsidize_vassals = yes
            }
            else = {
                set_character_flag = qyv_strat_consolidation
            }
        }

        # STRATEGIC DEPTH: Adaptive - full priority chain (DEFAULT)
        else_if = {
            limit = { qyv_ai_strategic_adaptive = root }
            if = {
                limit = { qyv_ai_priority_survival = root }
                set_character_flag = qyv_strat_survival
                if = {
                    limit = {
                        qyv_ai_has_existential_threat = root
                        qyv_ai_can_send_tribute = root
                        NOT = { has_character_flag = qyv_paying_tribute_to_target }
                    }
                    qyv_send_tribute = yes
                }
                if = {
                    limit = {
                        qyv_ai_has_existential_threat = root
                        qyv_should_seek_vassalization = root
                    }
                    trigger_event = { id = qyv_ai_gso.1 days = 5 scope:small = root scope:big = scope:existential_threat }
                }
                # Minor powers with a strong neighbor seek vassalization even
                # without an existential threat - survival trumps expansion
                if = {
                    limit = {
                        qyv_ai_is_minor_power = root
                        qyv_should_seek_vassalization = root
                        qyv_ai_has_strong_threat = root
                    }
                    trigger_event = { id = qyv_ai_gso.1 days = 5 scope:small = root scope:big = scope:strong_threat }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_consolidation = root }
                set_character_flag = qyv_strat_consolidation
                set_character_flag = qyv_prioritize_consolidation
            }
            else_if = {
                limit = { qyv_ai_priority_stability = root }
                set_character_flag = qyv_strat_stability
                qyv_subsidize_vassals = yes
                any_vassal = {
                    limit = { opinion_of_liege < -50 }
                    add_opinion = { target = root modifier = qyv_received_subsidy years = 3 }
                }
                # Great powers: build opinion buildings and revoke hostile
                # titles when factions are forming - cheaper than fighting
                qyv_ai_build_vassal_opinion_buildings = yes
                qyv_ai_revoke_hostile_vassal_titles = yes
                qyv_ai_great_power_counter_intelligence = yes
            }
            else_if = {
                limit = { qyv_ai_priority_vassalization = root }
                set_character_flag = qyv_strat_vassalization
            }
            else_if = {
                limit = { qyv_ai_priority_expansion = root }
                set_character_flag = qyv_strat_expansion
                if = {
                    limit = {
                        qyv_ai_can_expand_contiguous = root
                        gold >= 500
                        prestige >= 150
                        NOT = { has_character_flag = ai_claims_spammed }
                    }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                NOT = { is_allied_to = root }
                                NOT = { has_truce_with = root }
                                military_strength < root.military_strength * 1.2
                                OR = {
                                    qyv_claim_creates_contiguous = { target_province = scope:neighbor }
                                    qyv_claim_same_de_jure = { target_province = scope:neighbor }
                                    qyv_claim_same_culture = { target_province = scope:neighbor }
                                    qyv_claim_same_faith = { target_province = scope:neighbor }
                                }
                            }
                            save_scope_as = expansion_target
                        }
                    }
                    if = {
                        limit = { exists = scope:expansion_target }
                        fabricate_claim_on = scope:expansion_target
                        set_character_flag = ai_claims_spammed
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_diplomacy = root }
                set_character_flag = qyv_strat_diplomacy
                if = {
                    limit = {
                        qyv_ai_can_form_confederation = root
                        has_game_rule = { qyv_west_latinate_confed option = on }
                    }
                    trigger_event = { id = qyv_ai_gso.20 days = 30 }
                }
                if = {
                    limit = {
                        qyv_ai_can_send_gift = root
                        gold >= 500
                    }
                    qyv_send_diplomatic_gift = yes
                }
            }
            else_if = {
                limit = { qyv_ai_priority_development = root }
                set_character_flag = qyv_strat_development
                if = {
                    limit = { gold >= 300 }
                    capital_province = { add_development = 1 }
                    add_gold = -300
                }
            }
            # EXTENDED PRIORITY CHAIN (v1.20.5)
            else_if = {
                limit = { qyv_ai_priority_collapse = root }
                set_character_flag = qyv_strat_collapse
                if = {
                    limit = {
                        qyv_ai_can_send_tribute = root
                        gold >= 200
                    }
                    qyv_send_tribute = yes
                }
            }
            else_if = {
                limit = { qyv_ai_priority_heir_security = root }
                set_character_flag = qyv_strat_heir_security
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_ultimogeniture = root } set_crown_law = ultimogeniture_succession }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_crisis_management = root }
                set_character_flag = qyv_strat_crisis_management
                qyv_subsidize_vassals = yes
            }
            else_if = {
                limit = { qyv_ai_priority_recovery = root }
                set_character_flag = qyv_strat_recovery
                if = {
                    limit = { gold >= 300 }
                    capital_province = { add_development = 1 }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_preemptive = root }
                set_character_flag = qyv_strat_preemptive
                if = {
                    limit = { qyv_ai_can_expand_contiguous = root gold >= 500 prestige >= 150 }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                NOT = { is_allied_to = root }
                                has_active_scheme = scheme_fabricate_claim
                                military_strength < root.military_strength * 1.2
                            }
                            save_scope_as = preempt_target
                        }
                    }
                    if = { limit = { exists = scope:preempt_target } fabricate_claim_on = scope:preempt_target }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_opportunistic_strike = root }
                set_character_flag = qyv_strat_opportunistic
                if = {
                    limit = { qyv_ai_can_expand_contiguous = root gold >= 500 prestige >= 150 }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                is_at_war = yes
                                NOT = { is_allied_to = root }
                                military_strength < root.military_strength * 1.5
                            }
                            save_scope_as = opp_target
                        }
                    }
                    if = { limit = { exists = scope:opp_target } fabricate_claim_on = scope:opp_target }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_spy_network = root }
                set_character_flag = qyv_strat_spy_network
                qyv_ai_build_spy_network = yes
            }
            else_if = {
                limit = { qyv_ai_priority_holy_war = root }
                set_character_flag = qyv_strat_holy_war
            }
            else_if = {
                limit = { qyv_ai_priority_deterrence = root }
                set_character_flag = qyv_strat_deterrence
                if = {
                    limit = { gold >= 1000 }
                    any_neighbor_independent_ruler = {
                        limit = { NOT = { is_allied_to = root } opinion_of_self < 30 }
                        qyv_send_diplomatic_gift = { gift_target = scope:neighbor }
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_legacy = root }
                set_character_flag = qyv_strat_legacy
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_resource_pivot = root }
                set_character_flag = qyv_strat_resource_pivot
                if = {
                    limit = { qyv_ai_is_struggling = root }
                    any_men_at_arms = {
                        limit = { maintenance > 50 }
                        disband_men_at_arms = yes
                    }
                }
            }
            # TIER 2 PRIORITIES (v1.20.6)
            else_if = {
                limit = { qyv_ai_priority_heir_security = root }
                set_character_flag = qyv_strat_heir_security
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_ultimogeniture = root } set_crown_law = ultimogeniture_succession }
                }
                qyv_ai_appoint_regent_effect = yes
            }
            else_if = {
                limit = { qyv_ai_priority_legacy = root }
                set_character_flag = qyv_strat_legacy
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                }
                qyv_ai_designate_successor_effect = yes
            }
            else_if = {
                limit = { qyv_ai_priority_resource_pivot = root }
                set_character_flag = qyv_strat_resource_pivot
                if = {
                    limit = { qyv_ai_is_struggling = root }
                    any_men_at_arms = {
                        limit = { maintenance > 50 }
                        disband_men_at_arms = yes
                    }
                }
                qyv_ai_demobilize_maa_effect = yes
            }
            else_if = {
                limit = { qyv_ai_should_tighten_contracts = root }
                set_character_flag = qyv_strat_contract_tightening
                qyv_ai_tighten_vassal_contracts_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_poor_vassal = root }
                set_character_flag = qyv_strat_contract_loosening
                qyv_ai_loosen_vassal_contracts_effect = yes
            }
            else_if = {
                limit = { qyv_ai_dread_high = root }
                set_character_flag = qyv_strat_dread_rule
                qyv_ai_reduce_subsidies_for_dread_effect = yes
            }
            else_if = {
                limit = { qyv_ai_stressed = root }
                set_character_flag = qyv_strat_delegation
                qyv_ai_delegate_stressed_effect = yes
            }
            else_if = {
                limit = { qyv_ai_newly_conquered = root }
                set_character_flag = qyv_strat_fortification
                qyv_ai_fortify_new_conquest_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_multiple_heirs = root }
                set_character_flag = qyv_strat_elective_switch
                qyv_ai_switch_to_elective_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_single_heir = root }
                set_character_flag = qyv_strat_primogeniture_lock
                qyv_ai_lock_primogeniture_effect = yes
            }
            else_if = {
                limit = { qyv_ai_neighbor_at_war = root }
                set_character_flag = qyv_strat_raiding
                qyv_ai_raid_neighbor_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_excess_gold = root }
                set_character_flag = qyv_strat_prestige_dump
                qyv_ai_spend_excess_gold_effect = yes
            }
            else = {
                set_character_flag = qyv_strat_development
            }
        }

        # STRATEGIC DEPTH: Calculating - deeper evaluation, multi-plan
        else_if = {
            limit = { qyv_ai_strategic_calculating = root }
            # Same as adaptive but with extra behaviors
            if = {
                limit = { qyv_ai_priority_survival = root }
                set_character_flag = qyv_strat_survival
                if = {
                    limit = {
                        qyv_ai_has_existential_threat = root
                        qyv_ai_can_send_tribute = root
                        NOT = { has_character_flag = qyv_paying_tribute_to_target }
                    }
                    qyv_send_tribute = yes
                }
                if = {
                    limit = {
                        qyv_ai_has_existential_threat = root
                        qyv_should_seek_vassalization = root
                    }
                    trigger_event = { id = qyv_ai_gso.1 days = 5 scope:small = root scope:big = scope:existential_threat }
                }
                # Calculating: minor powers with a strong neighbor seek
                # vassalization even without an existential threat
                if = {
                    limit = {
                        qyv_ai_is_minor_power = root
                        qyv_should_seek_vassalization = root
                        qyv_ai_has_strong_threat = root
                    }
                    trigger_event = { id = qyv_ai_gso.1 days = 5 scope:small = root scope:big = scope:strong_threat }
                }
                # Calculating: also prepare contingency tribute to secondary threats
                if = {
                    limit = {
                        qyv_ai_has_strong_threat = root
                        NOT = { scope:strong_threat = scope:existential_threat }
                        gold >= 800
                    }
                    qyv_send_tribute = { threat = scope:strong_threat }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_consolidation = root }
                set_character_flag = qyv_strat_consolidation
                set_character_flag = qyv_prioritize_consolidation
                # Calculating: also optimize succession
                if = {
                    limit = { qyv_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_ultimogeniture = root } set_crown_law = ultimogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_house_seniority = root } set_crown_law = house_seniority }
                    else_if = { limit = { qyv_ai_wants_elective = root } set_crown_law = feudal_elective_succession }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_stability = root }
                set_character_flag = qyv_strat_stability
                qyv_subsidize_vassals = yes
                any_vassal = {
                    limit = { opinion_of_liege < -50 }
                    add_opinion = { target = root modifier = qyv_received_subsidy years = 3 }
                }
                # Calculating: preemptive gift to wavering vassals
                if = {
                    limit = { gold >= 800 }
                    any_vassal = {
                        limit = { opinion_of_liege < -25 opinion_of_liege > -50 }
                        qyv_send_diplomatic_gift = { gift_target = scope:vassal }
                    }
                }
                # Calculating: great powers also build opinion buildings and
                # revoke hostile titles when factions are forming
                qyv_ai_build_vassal_opinion_buildings = yes
                qyv_ai_revoke_hostile_vassal_titles = yes
                qyv_ai_great_power_counter_intelligence = yes
            }
            else_if = {
                limit = { qyv_ai_priority_vassalization = root }
                set_character_flag = qyv_strat_vassalization
            }
            else_if = {
                limit = { qyv_ai_priority_expansion = root }
                set_character_flag = qyv_strat_expansion
                if = {
                    limit = {
                        qyv_ai_can_expand_contiguous = root
                        gold >= 500
                        prestige >= 150
                        NOT = { has_character_flag = ai_claims_spammed }
                    }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                NOT = { is_allied_to = root }
                                NOT = { has_truce_with = root }
                                military_strength < root.military_strength * 1.2
                                OR = {
                                    qyv_claim_creates_contiguous = { target_province = scope:neighbor }
                                    qyv_claim_same_de_jure = { target_province = scope:neighbor }
                                    qyv_claim_same_culture = { target_province = scope:neighbor }
                                    qyv_claim_same_faith = { target_province = scope:neighbor }
                                }
                            }
                            save_scope_as = expansion_target
                        }
                    }
                    if = {
                        limit = { exists = scope:expansion_target }
                        fabricate_claim_on = scope:expansion_target
                        set_character_flag = ai_claims_spammed
                    }
                }
                # Calculating: also raise counter-MaA
                if = {
                    limit = { gold >= 1500 NOT = { is_at_war = yes } }
                    if = {
                        limit = {
                            any_neighbor_independent_ruler = {
                                limit = { NOT = { is_allied_to = root } any_men_at_arms = { type = heavy_infantry } }
                            }
                        }
                        raise_men_at_arms = { type = men_at_arms_pikemen }
                    }
                    else_if = {
                        limit = {
                            any_neighbor_independent_ruler = {
                                limit = { NOT = { is_allied_to = root } any_men_at_arms = { type = cavalry } }
                            }
                        }
                        raise_men_at_arms = { type = men_at_arms_crossbowmen }
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_diplomacy = root }
                set_character_flag = qyv_strat_diplomacy
                if = {
                    limit = {
                        qyv_ai_can_form_confederation = root
                        has_game_rule = { qyv_west_latinate_confed option = on }
                    }
                    trigger_event = { id = qyv_ai_gso.20 days = 30 }
                }
                if = {
                    limit = { qyv_ai_can_send_gift = root gold >= 500 }
                    qyv_send_diplomatic_gift = yes
                }
                # Calculating: alliance web building
                if = {
                    limit = { gold >= 1000 }
                    any_neighbor_independent_ruler = {
                        limit = {
                            NOT = { is_allied_to = root }
                            NOT = { has_truce_with = root }
                            opinion_of_self >= 10
                            OR = { same_faith_as = root same_culture_as = root }
                        }
                    }
                    add_alliance = scope:neighbor
                }
                # Minor powers build alliance networks as deterrence even
                # with less gold - facing a strong threat, allies are survival
                if = {
                    limit = {
                        qyv_ai_is_minor_power = root
                        qyv_ai_has_strong_threat = root
                        gold >= 200
                    }
                    any_neighbor_independent_ruler = {
                        limit = {
                            NOT = { is_allied_to = root }
                            NOT = { has_truce_with = root }
                            opinion_of_self >= 10
                        }
                        add_alliance = scope:neighbor
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_development = root }
                set_character_flag = qyv_strat_development
                if = { limit = { gold >= 300 } capital_province = { add_development = 1 } add_gold = -300 }
                # Calculating: also build buildings
                if = {
                    limit = { gold >= 800 }
                    any_owned_province = {
                        limit = { holding = { can_build = yes } }
                        holding = { build_random_building = yes }
                    }
                }
            }
            # EXTENDED PRIORITY CHAIN (v1.20.5) - Calculating depth
            else_if = {
                limit = { qyv_ai_priority_collapse = root }
                set_character_flag = qyv_strat_collapse
                if = {
                    limit = {
                        qyv_ai_can_send_tribute = root
                        gold >= 200
                    }
                    qyv_send_tribute = yes
                }
                if = {
                    limit = { qyv_ai_should_seek_vassalization = root }
                    trigger_event = { id = qyv_ai_gso.1 days = 5 scope:small = root scope:big = scope:existential_threat }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_heir_security = root }
                set_character_flag = qyv_strat_heir_security
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_ultimogeniture = root } set_crown_law = ultimogeniture_succession }
                }
                # Calculating: also designate a better heir if one exists
                if = {
                    limit = { qyv_has_better_spare = root }
                    any_child = {
                        limit = {
                            is_heir = no
                            age >= 8
                            NOT = { is_married = yes }
                            OR = {
                                has_trait = intelligent has_trait = quick has_trait = genius
                                has_trait = attractive has_trait = handsome has_trait = beautiful
                                has_trait = hale has_trait = robust
                            }
                        }
                        designate_heir = yes
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_crisis_management = root }
                set_character_flag = qyv_strat_crisis_management
                qyv_subsidize_vassals = yes
                qyv_ai_build_vassal_opinion_buildings = yes
                qyv_ai_great_power_counter_intelligence = yes
            }
            else_if = {
                limit = { qyv_ai_priority_recovery = root }
                set_character_flag = qyv_strat_recovery
                if = {
                    limit = { gold >= 300 }
                    capital_province = { add_development = 1 }
                }
                if = {
                    limit = { gold >= 800 }
                    any_owned_province = {
                        limit = { holding = { can_build = yes } }
                        holding = { build_random_building = yes }
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_preemptive = root }
                set_character_flag = qyv_strat_preemptive
                if = {
                    limit = { qyv_ai_can_expand_contiguous = root gold >= 500 prestige >= 150 }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                NOT = { is_allied_to = root }
                                has_active_scheme = scheme_fabricate_claim
                                military_strength < root.military_strength * 1.2
                            }
                            save_scope_as = preempt_target
                        }
                    }
                    if = { limit = { exists = scope:preempt_target } fabricate_claim_on = scope:preempt_target }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_opportunistic_strike = root }
                set_character_flag = qyv_strat_opportunistic
                if = {
                    limit = { qyv_ai_can_expand_contiguous = root gold >= 500 prestige >= 150 }
                    random_owned_province = {
                        any_neighbor_province = {
                            limit = {
                                is_independent_ruler = yes
                                is_at_war = yes
                                NOT = { is_allied_to = root }
                                military_strength < root.military_strength * 1.5
                            }
                            save_scope_as = opp_target
                        }
                    }
                    if = { limit = { exists = scope:opp_target } fabricate_claim_on = scope:opp_target }
                }
                # Calculating: also raise counter-MaA for the expected fight
                if = {
                    limit = { gold >= 1500 NOT = { is_at_war = yes } }
                    if = {
                        limit = {
                            any_neighbor_independent_ruler = {
                                limit = { NOT = { is_allied_to = root } any_men_at_arms = { type = cavalry } }
                            }
                        }
                        raise_men_at_arms = { type = men_at_arms_pikemen }
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_spy_network = root }
                set_character_flag = qyv_strat_spy_network
                qyv_ai_build_spy_network = yes
            }
            else_if = {
                limit = { qyv_ai_priority_holy_war = root }
                set_character_flag = qyv_strat_holy_war
            }
            else_if = {
                limit = { qyv_ai_priority_deterrence = root }
                set_character_flag = qyv_strat_deterrence
                if = {
                    limit = { gold >= 1000 }
                    any_neighbor_independent_ruler = {
                        limit = { NOT = { is_allied_to = root } opinion_of_self < 30 }
                        qyv_send_diplomatic_gift = { gift_target = scope:neighbor }
                    }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_legacy = root }
                set_character_flag = qyv_strat_legacy
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                }
            }
            else_if = {
                limit = { qyv_ai_priority_resource_pivot = root }
                set_character_flag = qyv_strat_resource_pivot
                if = {
                    limit = { qyv_ai_is_struggling = root }
                    any_men_at_arms = {
                        limit = { maintenance > 50 }
                        disband_men_at_arms = yes
                    }
                }
            }
            # TIER 2 PRIORITIES (v1.20.6) - Calculating depth
            else_if = {
                limit = { qyv_ai_priority_heir_security = root }
                set_character_flag = qyv_strat_heir_security
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                    else_if = { limit = { qyv_ai_wants_ultimogeniture = root } set_crown_law = ultimogeniture_succession }
                }
                qyv_ai_appoint_regent_effect = yes
            }
            else_if = {
                limit = { qyv_ai_priority_legacy = root }
                set_character_flag = qyv_strat_legacy
                if = {
                    limit = { qyv_ai_should_switch_succession = root }
                    if = { limit = { qyv_ai_wants_primogeniture = root } set_crown_law = primogeniture_succession }
                }
                qyv_ai_designate_successor_effect = yes
            }
            else_if = {
                limit = { qyv_ai_priority_resource_pivot = root }
                set_character_flag = qyv_strat_resource_pivot
                if = {
                    limit = { qyv_ai_is_struggling = root }
                    any_men_at_arms = {
                        limit = { maintenance > 50 }
                        disband_men_at_arms = yes
                    }
                }
                qyv_ai_demobilize_maa_effect = yes
            }
            else_if = {
                limit = { qyv_ai_should_tighten_contracts = root }
                set_character_flag = qyv_strat_contract_tightening
                qyv_ai_tighten_vassal_contracts_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_poor_vassal = root }
                set_character_flag = qyv_strat_contract_loosening
                qyv_ai_loosen_vassal_contracts_effect = yes
            }
            else_if = {
                limit = { qyv_ai_dread_high = root }
                set_character_flag = qyv_strat_dread_rule
                qyv_ai_reduce_subsidies_for_dread_effect = yes
            }
            else_if = {
                limit = { qyv_ai_stressed = root }
                set_character_flag = qyv_strat_delegation
                qyv_ai_delegate_stressed_effect = yes
            }
            else_if = {
                limit = { qyv_ai_newly_conquered = root }
                set_character_flag = qyv_strat_fortification
                qyv_ai_fortify_new_conquest_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_multiple_heirs = root }
                set_character_flag = qyv_strat_elective_switch
                qyv_ai_switch_to_elective_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_single_heir = root }
                set_character_flag = qyv_strat_primogeniture_lock
                qyv_ai_lock_primogeniture_effect = yes
            }
            else_if = {
                limit = { qyv_ai_neighbor_at_war = root }
                set_character_flag = qyv_strat_raiding
                qyv_ai_raid_neighbor_effect = yes
            }
            else_if = {
                limit = { qyv_ai_has_excess_gold = root }
                set_character_flag = qyv_strat_prestige_dump
                qyv_ai_spend_excess_gold_effect = yes
            }
            else = {
                set_character_flag = qyv_strat_development
            }
        }

        # DEFAULT (Off) - minimal behavior
        else = {
            if = {
                limit = { qyv_ai_priority_survival = root }
                set_character_flag = qyv_strat_survival
            }
            else_if = {
                limit = { qyv_ai_priority_consolidation = root }
                set_character_flag = qyv_strat_consolidation
                set_character_flag = qyv_prioritize_consolidation
            }
            else = {
                set_character_flag = qyv_strat_consolidation
            }
        }
    }

    option = { name = "OK" }
}

# ============================================================
# HEIR & SUCCESSION MANAGEMENT (Quarterly)
# ============================================================

character_event = {
    id = qyv_ai_brain.0100
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_heir_ai_enabled = root
        qyv_organic_ai_enabled = root
    }

    mean_time_to_happen = { months = 3 }

    immediate = {
        # 1. Evaluate heir quality
        if = {
            limit = { qyv_has_bad_heir = root }
            set_character_flag = qyv_heir_crisis
            # Disinherit if possible
            if = {
                limit = {
                    any_child = {
                        is_heir = yes
                        OR = { has_trait = stupid has_trait = imbecile has_trait = incapable }
                    }
                    has_crown_law = { law = partition }
                }
                any_child = {
                    limit = { is_heir = yes }
                    disinherit = yes
                }
            }
        }

        # 2. Designate better heir if spare exists
        if = {
            limit = { qyv_has_better_spare = root }
            set_character_flag = qyv_switching_heir
            any_child = {
                limit = {
                    is_heir = no
                    age >= 8
                    NOT = { is_married = yes }
                    OR = {
                        has_trait = intelligent
                        has_trait = quick
                        has_trait = genius
                        has_trait = attractive
                        has_trait = handsome
                        has_trait = beautiful
                        has_trait = hale
                        has_trait = robust
                    }
                    NOT = { has_trait = slow }
                    NOT = { has_trait = stupid }
                    NOT = { has_trait = weak }
                    NOT = { has_trait = sickly }
                }
                designate_heir = yes
            }
        }

        # 3. Optimize succession law
        if = {
            limit = { qyv_should_switch_succession = root }
            if = {
                limit = { qyv_ai_wants_primogeniture = root }
                set_crown_law = primogeniture_succession
            }
            else_if = {
                limit = { qyv_ai_wants_ultimogeniture = root }
                set_crown_law = ultimogeniture_succession
            }
            else_if = {
                limit = { qyv_ai_wants_house_seniority = root }
                set_crown_law = house_seniority
            }
            else_if = {
                limit = { qyv_ai_wants_elective = root }
                set_crown_law = feudal_elective_succession
            }
        }

        # 4. Education focus for children
        any_realm_courtier = {
            limit = {
                is_child = yes
                NOT = { has_education_focus = yes }
                age >= 6
            }
            if = {
                limit = { qyv_ai_education_focus_martial = scope:ward }
                set_education_focus = martial_education
            }
            else_if = {
                limit = { qyv_ai_education_focus_stewardship = scope:ward }
                set_education_focus = stewardship_education
            }
            else_if = {
                limit = { qyv_ai_education_focus_diplomacy = scope:ward }
                set_education_focus = diplomacy_education
            }
            else_if = {
                limit = { qyv_ai_education_focus_intrigue = scope:ward }
                set_education_focus = intrigue_education
            }
            else_if = {
                limit = { qyv_ai_education_focus_learning = scope:ward }
                set_education_focus = learning_education
            }
        }
    }

    option = { name = "OK" }
}

# ============================================================
# MARRIAGE & GUARDIANSHIP COORDINATION
# ============================================================

character_event = {
    id = qyv_ai_brain.0200
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_marriage_ai_enabled = root
        qyv_organic_ai_enabled = root
    }

    mean_time_to_happen = { months = 6 }

    immediate = {
        # Set marriage goal based on strategy
        if = {
            limit = { qyv_strat_expansion = root }
            set_character_flag = qyv_marriage_goal_alliance
        }
        else_if = {
            limit = { qyv_strat_survival = root }
            set_character_flag = qyv_marriage_goal_genetics
        }
        else_if = {
            limit = { qyv_strat_diplomacy = root }
            set_character_flag = qyv_marriage_goal_alliance
        }
        else = {
            set_character_flag = qyv_marriage_goal_genetics
        }

        # Trigger existing marriage event
        trigger_event = { id = qyv_marriage.0100 days = 1 }
    }

    option = { name = "OK" }
}

character_event = {
    id = qyv_ai_brain.0300
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_guardian_ai_enabled = root
        qyv_organic_ai_enabled = root
    }

    mean_time_to_happen = { months = 6 }

    immediate = {
        # Trigger existing guardian event
        trigger_event = { id = qyv_guardian.0100 days = 1 }
    }

    option = { name = "OK" }
}

# ============================================================
# TRIBUTE & GIFT COORDINATION
# ============================================================

character_event = {
    id = qyv_ai_brain.0400
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_tribute_ai_enabled = root
        qyv_organic_ai_enabled = root
    }

    mean_time_to_happen = { months = 6 }

    immediate = {
        # Renew tribute if paying
        if = {
            limit = { has_character_flag = qyv_paying_tribute_to_target }
            qyv_renew_tribute = yes
        }

        # Consider new tribute if threatened
        if = {
            limit = {
                qyv_ai_should_pay_tribute = root
                NOT = { has_character_flag = qyv_paying_tribute_to_target }
                qyv_ai_can_send_tribute = root
            }
            qyv_send_tribute = yes
        }

        # Send gifts to hostile peers
        if = {
            limit = {
                qyv_ai_can_send_gift = root
                gold >= 500
            }
            qyv_send_diplomatic_gift = yes
        }
    }

    option = { name = "OK" }
}

# ============================================================
# MILITARY & MENARMS OPTIMIZATION
# ============================================================

character_event = {
    id = qyv_ai_brain.0500
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_organic_ai_enabled = root
        gold >= 1000
    }

    mean_time_to_happen = { months = 24 }

    immediate = {
        # Disband expensive MaA if struggling
        if = {
            limit = { qyv_ai_is_struggling = root }
            any_men_at_arms = {
                limit = { maintenance > 50 }
                disband_men_at_arms = yes
            }
        }

        # Raise quality MaA if wealthy and at peace
        if = {
            limit = {
                qyv_ai_is_wealthy = root
                NOT = { is_at_war = yes }
                NOT = { qyv_ai_has_strong_threat = root }
            }
            # Prioritize counter units based on neighbors
            if = {
                limit = {
                    any_neighbor_independent_ruler = {
                        limit = {
                            NOT = { is_allied_to = root }
                            any_men_at_arms = { type = heavy_infantry }
                        }
                    }
                }
                raise_men_at_arms = { type = men_at_arms_pikemen }
            }
            else_if = {
                limit = {
                    any_neighbor_independent_ruler = {
                        limit = {
                            NOT = { is_allied_to = root }
                            any_men_at_arms = { type = cavalry }
                        }
                    }
                }
                raise_men_at_arms = { type = men_at_arms_crossbowmen }
            }
            else_if = {
                limit = {
                    any_neighbor_independent_ruler = {
                        limit = {
                            NOT = { is_allied_to = root }
                            any_men_at_arms = { type = skirmishers }
                        }
                    }
                }
                raise_men_at_arms = { type = men_at_arms_heavy_infantry }
            }
        }
    }

    option = { name = "OK" }
}

# ============================================================
# INVESTMENT & ECONOMIC DECISIONS
# ============================================================

character_event = {
    id = qyv_ai_brain.0600
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_organic_ai_full = root
        qyv_ai_can_afford_investment = root
    }

    mean_time_to_happen = { months = 18 }

    immediate = {
        # Invest in development
        if = {
            limit = {
                capital_province = { development < 30 }
                gold >= 500
            }
            capital_province = { add_development = 1 }
            add_gold = -500
        }

        # Build buildings
        if = {
            limit = {
                any_owned_province = {
                    holding = { can_build = yes }
                }
            }
            random_owned_province = {
                limit = {
                    holding = { can_build = yes }
                }
                holding = { build_random_building = yes }
            }
        }
    }

    option = { name = "OK" }
}

# ============================================================
# PERFORMANCE MODE MANAGEMENT
# ============================================================

character_event = {
    id = qyv_ai_brain.0700
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_ai_performance_mode_check = root
    }

    mean_time_to_happen = { months = 6 }

    immediate = {
        qyv_ai_enable_performance_mode = yes
    }

    option = { name = "OK" }
}

character_event = {
    id = qyv_ai_brain.0701
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_ai_performance_mode_active = root
        NOT = { qyv_ai_performance_mode_check = root }
    }

    mean_time_to_happen = { months = 12 }

    immediate = {
        qyv_ai_disable_performance_mode = yes
    }

    option = { name = "OK" }
}

# ============================================================
# DEBUG DECISION
# ============================================================

character_event = {
    id = qyv_ai_brain.0800
    hidden = no
    is_triggered_only = yes

    trigger = {
        is_ruler = yes
        is_human = yes
        qyv_ai_debug_mode = root
    }

    title = qyv_debug_brain_title
    desc = qyv_debug_brain_desc
    picture = GFX_evt_technology

    option = {
        name = qyv_debug_print_state
        effects = {
            qyv_ai_debug_print_brain_state = yes
        }
    }
    option = {
        name = qyv_debug_toggle_performance
        effects = {
            qyv_ai_toggle_performance_mode = yes
        }
    }
    option = {
        name = qyv_debug_close
    }
}

# ============================================================
# COUNTER-INTELLIGENCE (Quarterly)
# ============================================================

character_event = {
    id = qyv_ai_brain.0900
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_ai_should_counter_intelligence = root
    }

    mean_time_to_happen = { months = 3 }

    immediate = {
        qyv_ai_counter_intelligence = yes
    }

    option = { name = "OK" }
}

# ============================================================
# SCHEME TIMING OPTIMIZATION (Monthly)
# ============================================================

character_event = {
    id = qyv_ai_brain.1000
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
    }

    mean_time_to_happen = { months = 1 }

    immediate = {
        # Scheme before war
        if = {
            limit = { qyv_ai_should_scheme_before_war = root }
            qyv_ai_scheme_before_war = yes
        }

        # Scheme during succession crisis
        if = {
            limit = { qyv_ai_should_scheme_during_succession_crisis = root }
            qyv_ai_scheme_during_succession_crisis = yes
        }
    }

    option = { name = "OK" }
}

# ============================================================
# MULTI-SCHEME COORDINATION (Monthly)
# ============================================================

character_event = {
    id = qyv_ai_brain.1100
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        qyv_ai_should_run_parallel_schemes = root
    }

    mean_time_to_happen = { months = 1 }

    immediate = {
        qyv_ai_run_parallel_schemes = yes
    }

    option = { name = "OK" }
}

# ============================================================
# PERFORMANCE MODE TOGGLE (Yearly)
# ============================================================

character_event = {
    id = qyv_ai_brain.1200
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
    }

    mean_time_to_happen = { months = 12 }

    immediate = {
        qyv_ai_toggle_performance_mode = yes
    }

    option = { name = "OK" }
}

# ============================================================
# DIFFICULTY SYSTEM (Yearly) (v1.20.7)
# Runs after the main strategy chain. Hard/brutal rulers take
# extra actions: preemptive wars, opportunistic raids, anti-player
# alliances, player targeting, no-mercy war demands, parallel schemes.
# ============================================================

character_event = {
    id = qyv_ai_brain.1300
    hidden = yes
    is_triggered_only = no

    trigger = {
        is_ai = yes
        is_ruler = yes
        is_independent_ruler = yes
    }

    mean_time_to_happen = { months = 12 }

    immediate = {
        # Preemptive wars: strike first when neighbor is fabricating
        qyv_ai_preemptive_war_effect = yes

        # Opportunistic raids: strike distracted neighbors
        qyv_ai_raid_hard_effect = yes

        # Aggressive diplomacy: form alliances against the player
        qyv_ai_form_anti_player_alliance_effect = yes

        # Player targeting: focus on the player when they are strong
        qyv_ai_target_player_effect = yes

        # No mercy: never white peace, always demand annexation
        qyv_ai_no_mercy_war_effect = yes
        qyv_ai_demand_annexation_effect = yes

        # Brutal: run parallel schemes and prepare even at peace
        qyv_ai_brutal_parallel_schemes_effect = yes
        qyv_ai_brutal_preparation_effect = yes

        # ============================================================
        # CHALLENGE SYSTEMS (v1.20.8)
        # These make the PLAYER's life harder without touching AI stats.
        # All gated behind game rules so the player can disable them.
        # ============================================================

        # Resource scarcity: raid for resources, demand tribute when weak
        qyv_ai_raid_for_resources_effect = yes
        qyv_ai_demand_tribute_when_weak_effect = yes

        # Vassal volatility: stir faction trouble, sow discontent
        qyv_ai_stir_faction_trouble_effect = yes
        qyv_ai_sow_discontent_effect = yes

        # Succession fragility: target heirs of aging rulers, target succession crises
        qyv_ai_target_heir_of_weak_ruler_effect = yes
        qyv_ai_target_succession_crisis_effect = yes

        # External pressure: create claimant threats, encourage rebellion
        qyv_ai_create_claimant_threat_effect = yes
        qyv_ai_encourage_rebellion_effect = yes

        # Economic pressure: squeeze wealthy neighbors, block trade routes
        qyv_ai_squeeze_economy_effect = yes
        qyv_ai_block_trade_effect = yes

        # ============================================================
        # ELITE AI BEHAVIOURS (v1.20.10)
        # Layered, parallel, proactive — how the best CK3 players play.
        # ============================================================

        # War chaining: while in war 1, prepare claims for war 2
        qyv_ai_chain_war_claims_effect = yes

        # Truce-aware expansion: treat truces as temporary, expand around them
        qyv_ai_expand_around_truces_effect = yes

        # Dread economy: build dread preemptively when secure and at peace
        qyv_ai_build_dread_preemptively_effect = yes

        # CB cost evaluation: pick the cheapest viable CB for each target
        qyv_ai_evaluate_cb_cost_effect = yes

        # Succession timing: switch to primogeniture BEFORE inheritance
        qyv_ai_time_succession_switch_effect = yes

        # Layered building: economy first, military second, prestige third
        qyv_ai_build_economy_first_effect = yes
        qyv_ai_build_military_second_effect = yes
        qyv_ai_build_prestige_third_effect = yes

        # ============================================================
        # GRANDMASTER AI (v1.20.11)
        # 4 systems that make the AI feel like it reads your mind.
        # ============================================================

        # Player-behaviour prediction: track the player's active fronts
        qyv_ai_predict_player_front_effect = yes
        qyv_ai_preempt_player_front_effect = yes

        # Destabilization as a weapon: create crises for fragile rivals
        qyv_ai_destabilize_rival_effect = yes
        qyv_ai_destabilize_faction_trouble_effect = yes

        # Information as currency: trade secrets, use hooks as leverage
        qyv_ai_trade_information_effect = yes
        qyv_ai_use_hook_as_leverage_effect = yes

        # Truce-timing warfare: schedule declarations around truce end dates
        qyv_ai_time_truce_expiry_effect = yes
        qyv_ai_prepare_for_truce_expiry_effect = yes
    }

    option = { name = "OK" }
}

on_actions = {
    on_game_start = {
        events = { qyv_ai_brain.0010 qyv_ai_brain.0800 }
    }

    on_yearly_pulse = {
        events = { qyv_ai_brain.0010 qyv_ai_brain.0400 qyv_ai_brain.0500 qyv_ai_brain.0600 qyv_ai_brain.1200 qyv_ai_brain.1300 }
    }

    on_quarterly_pulse = {
        events = { qyv_ai_brain.0100 qyv_ai_brain.0200 qyv_ai_brain.0300 qyv_ai_brain.0900 }
    }

    on_monthly_pulse = {
        events = { qyv_ai_brain.1000 qyv_ai_brain.1100 }
    }
}