﻿riseandfall_ai_title_handout_se = {
    # Called from a yearly on_action when the AI kingdom handout rule is enabled.
    # Randomly select one de jure kingdom in the realm where the holder (AI emperor) is not de jure for that kingdom
    # AND the emperor's capital is not within that kingdom's territory,
    # and try to hand the title to a random de jure vassal under the EMPEROR.
    # CRITICAL: Only grant if the emperor (current scope) is the current holder of the kingdom title.

    # Save the current emperor scope for reference
    save_scope_as = emperor

    # Only attempt kingdom handouts if the saved ruler actually outranks kingdoms.
    if = {
        limit = { scope:emperor = { primary_title.tier >= tier_empire } }
        every_realm_de_jure_kingdom = {
        # Iterate every de-jure kingdom. Check each one to see if the emperor is the current holder.
        limit = { 
            exists = this 
            holder = scope:emperor
            # Never hand out a title at the ruler's own primary rank.
            # A king granting a kingdom makes the recipient independent.
            tier < scope:emperor.primary_title.tier
        }
        save_scope_as = target_title

        # CRITICAL: Verify that emperor still holds the target kingdom.
        # This prevents the bug where vassals become independent or the title changes hands every year.
        if = {
            limit = { 
                scope:target_title = {
                    holder = scope:emperor
                    tier < scope:emperor.primary_title.tier
                }
            }

            # Now we're in the emperor scope. Check whether the kingdom is not de jure to the emperor
            # AND the emperor's capital is not within this kingdom's de jure territory.
            # We only want to hand out kingdoms that are NOT de jure under their primary title
            # AND don't contain the emperor's capital.
            if = { 
                limit = { 
                    NOT = { 
                        scope:emperor = { primary_title = { de_jure_liege = scope:target_title } }
                    }
                    NOT = {
                        scope:target_title = { any_de_jure_county = { this = scope:emperor.capital_province.county } }
                    }
                }

                # Debug: log entry with title and holder

                # Look for a de jure vassal holder of THIS KINGDOM (including sub-vassals in the hierarchy).
                # This iterates through all characters who hold de jure vassal titles under target_kingdom.
                scope:target_title = {
                    # Prioritize dukes first, then counts, then (last) kings when choosing a de jure vassal
                    # who will receive the kingdom. This avoids handing kingdoms to low-tier holders
                    # when a higher-tier duke is available.
                    random_dejure_vassal_title_holder = {
                        limit = {
                            is_landed = yes
                            highest_held_title_tier >= tier_duchy
                            any_liege_or_above = { this = scope:emperor }
                            NOT = { this = scope:emperor }
                        }
                        save_scope_as = chosen_vassal
                    }

                    # If no duke found, fall back to county-level holders
                    if = {
                        limit = { NOT = { exists = scope:chosen_vassal } }
                        random_dejure_vassal_title_holder = {
                            limit = {
                                    is_landed = yes
                                    highest_held_title_tier >= tier_county
                                    any_liege_or_above = { this = scope:emperor }
                                    NOT = { this = scope:emperor }
                                }
                            save_scope_as = chosen_vassal
                        }
                    }

                    # If still nothing found, as a last resort allow king-level vassals
                    if = {
                        limit = { NOT = { exists = scope:chosen_vassal } }
                        random_dejure_vassal_title_holder = {
                            limit = {
                                    is_landed = yes
                                    highest_held_title_tier >= tier_kingdom
                                    any_liege_or_above = { this = scope:emperor }
                                    NOT = { this = scope:emperor }
                                }
                            save_scope_as = chosen_vassal
                        }
                    }
                }

                # Debug: log whether we found a chosen_vassal
                if = { limit = { NOT = { exists = scope:chosen_vassal } } }

                # If we have a chosen_vassal, perform the transfer.
                # Double-check they are ultimately a vassal of the emperor (including sub-vassals) before granting.
                if = {
                    limit = { 
                        exists = scope:chosen_vassal 
                        scope:chosen_vassal = { any_liege_or_above = { this = scope:emperor } }
                        scope:chosen_vassal = { is_landed = yes }
                        # Don't grant to theocratic vassals unless emperor is also theocratic
                        OR = {
                            NOT = { scope:chosen_vassal = { government_has_flag = government_is_theocracy } }
                            scope:emperor = { government_has_flag = government_is_theocracy }
                        }
                    }
                    # Create the transfer change and apply it to the saved target title
                    # Skip granting if the target title has the giveaway-block variable AND the emperor is a human player.
                    if = {
                        limit = { NOT = { AND = { scope:target_title = { has_variable = Riseandfall_giveaway_blocked } scope:emperor = { is_ai = no } } } }
                        scope:chosen_vassal = {
                            hidden_effect = {
                                add_opinion = {
                                    target = scope:emperor
                                    modifier = received_title_kingdom
                                }
                            }
                        }
                        create_title_and_vassal_change = { type = granted save_scope_as = change }
                        scope:target_title = {
                            change_title_holder_include_vassals = { holder = scope:chosen_vassal change = scope:change take_baronies = no }
                        }
                        resolve_title_and_vassal_change = scope:change
                    }
                }
                else = {
                    # Debug: grant failed - check why
                }
            }
            else = {
                # Debug: kingdom contains emperor's capital or is de jure to emperor
            }
        }
        else = {
            # The emperor no longer holds this kingdom title, skip it.
        }
        }
    }
    else = {
        # Not an empire-tier holder; skip kingdom handout to avoid accidental grants
    }
}

riseandfall_ai_advanced_grant_target_kingdom_se = {
    # Expected scope: emperor/liege character.
    # Required saved scopes: scope:target_title = kingdom, scope:rf_advanced_chosen_vassal = recipient.
    save_scope_as = emperor

    if = {
        limit = {
            is_ai = yes
            primary_title.tier >= tier_empire
            exists = scope:target_title
            exists = scope:rf_advanced_chosen_vassal
            scope:target_title = {
                tier = tier_kingdom
                holder = scope:emperor
                # The liege must outrank the title being granted, or the grant
                # can split the recipient out as an independent ruler.
                tier < scope:emperor.primary_title.tier
                any_dejure_vassal_title_holder = {
                    this = scope:rf_advanced_chosen_vassal
                }
            }
            scope:rf_advanced_chosen_vassal = {
                is_landed = yes
                highest_held_title_tier >= tier_county
                any_liege_or_above = { this = scope:emperor }
                NOT = { this = scope:emperor }
                is_adult = yes
                is_imprisoned = no
                NOT = { has_trait = incapable }
                NOT = { has_trait = infirm }
                NOT = { has_trait = warlord }
                NOT = { has_trait = disloyal }
                NOT = { is_at_war_with = scope:emperor }
                NOT = { has_relation_rival = scope:emperor }
                OR = {
                    opinion = { target = scope:emperor value >= -20 }
                    has_trait = loyal
                    has_trait = trusting
                    has_trait = content
                }
                OR = {
                    NOT = { government_has_flag = government_is_theocracy }
                    scope:emperor = { government_has_flag = government_is_theocracy }
                }
            }
        }

        scope:rf_advanced_chosen_vassal = {
            hidden_effect = {
                add_opinion = {
                    target = scope:emperor
                    modifier = received_title_kingdom
                }
            }
        }

        create_title_and_vassal_change = { type = granted save_scope_as = rf_advanced_kingdom_change }
        scope:target_title = {
            change_title_holder_include_vassals = {
                holder = scope:rf_advanced_chosen_vassal
                change = scope:rf_advanced_kingdom_change
                take_baronies = no
            }
        }
        resolve_title_and_vassal_change = scope:rf_advanced_kingdom_change

        set_variable = { name = riseandfall_ai_advanced_title_action_cooldown value = yes years = 5 }

        # If the emperor personally holds duchies inside the granted kingdom, move them too.
        scope:target_title = {
            every_direct_de_jure_vassal_title = {
                limit = {
                    tier = tier_duchy
                    holder = scope:emperor
                    NOT = { holder = scope:rf_advanced_chosen_vassal }
                }
                scope:emperor = {
                    create_title_and_vassal_change = { type = granted save_scope_as = rf_advanced_duchy_change }
                }
                change_title_holder_include_vassals = {
                    holder = scope:rf_advanced_chosen_vassal
                    change = scope:rf_advanced_duchy_change
                    take_baronies = no
                }
                scope:emperor = { resolve_title_and_vassal_change = scope:rf_advanced_duchy_change }
            }
        }
    }
}

riseandfall_ai_advanced_grant_target_duchy_se = {
    # Expected scope: king/liege character.
    # Required saved scopes: scope:target_title = duchy, scope:rf_advanced_chosen_vassal = recipient.
    save_scope_as = king

    if = {
        limit = {
            is_ai = yes
            exists = scope:target_title
            exists = scope:rf_advanced_chosen_vassal
            scope:target_title = {
                tier = tier_duchy
                holder = scope:king
                # Do not grant a title at the liege's own primary rank.
                tier < scope:king.primary_title.tier
                any_dejure_vassal_title_holder = {
                    this = scope:rf_advanced_chosen_vassal
                }
            }
            scope:rf_advanced_chosen_vassal = {
                is_landed = yes
                highest_held_title_tier >= tier_county
                highest_held_title_tier < tier_duchy
                any_liege_or_above = { this = scope:king }
                NOT = { this = scope:king }
                is_adult = yes
                is_imprisoned = no
                NOT = { has_trait = incapable }
                NOT = { has_trait = infirm }
                NOT = { has_trait = warlord }
                NOT = { has_trait = disloyal }
                NOT = { is_at_war_with = scope:king }
                NOT = { has_relation_rival = scope:king }
                OR = {
                    opinion = { target = scope:king value >= -20 }
                    has_trait = loyal
                    has_trait = trusting
                    has_trait = content
                }
                OR = {
                    NOT = { government_has_flag = government_is_theocracy }
                    scope:king = { government_has_flag = government_is_theocracy }
                }
            }
        }

        scope:rf_advanced_chosen_vassal = {
            hidden_effect = {
                add_opinion = {
                    target = scope:king
                    modifier = received_title_duchy
                }
            }
        }

        create_title_and_vassal_change = { type = granted save_scope_as = rf_advanced_duchy_grant_change }
        scope:target_title = {
            change_title_holder_include_vassals = {
                holder = scope:rf_advanced_chosen_vassal
                change = scope:rf_advanced_duchy_grant_change
                take_baronies = no
            }
        }
        resolve_title_and_vassal_change = scope:rf_advanced_duchy_grant_change

        set_variable = { name = riseandfall_ai_advanced_title_action_cooldown value = yes years = 5 }
    }
}

riseandfall_ai_advanced_destroy_unwanted_titles_se = {
    # Advanced mode should not let AI rulers hoard spare kingdom/empire/hegemony titles.
    # Duchies are intentionally ignored here.
    save_scope_as = rf_advanced_cleanup_ruler

    if = {
        limit = {
            is_ai = yes
            is_landed = yes
            is_independent_ruler = yes
            exists = primary_title
            primary_title.tier >= tier_kingdom
            # Vassals retain secondary crowns; Warlords retain crowns they create.
            NOT = { riseandfall_is_any_warlord_trigger = yes }
        }

        # Do not try to demote empire-tier primary titles by swapping to a
        # kingdom/duchy/county primary. CK3 rejects lower-tier primary swaps,
        # so this cleanup only destroys extra non-primary titles below.

        # Remove every eligible unwanted crown during the January cleanup pass.
        every_held_title = {
            limit = {
                OR = {
                    AND = {
                        tier = tier_kingdom
                        scope:rf_advanced_cleanup_ruler = { primary_title.tier >= tier_kingdom }
                    }
                    AND = {
                        tier = tier_empire
                        # Never destroy an empire merely because its holder is
                        # beneath a hegemon; that can restructure another realm.
                        scope:rf_advanced_cleanup_ruler = { primary_title.tier >= tier_empire }
                    }
                    AND = {
                        tier = tier_hegemony
                        scope:rf_advanced_cleanup_ruler = { primary_title.tier >= tier_hegemony }
                    }
                }
                NOT = { this = scope:rf_advanced_cleanup_ruler.primary_title }
                # Clerical regions are religious offices, not spare secular crowns.
                has_clerical_region = no
                is_landless_type_title = no
                NOT = { is_head_of_faith = yes }
                NOT = { is_nomad_title = yes }
                NOT = { is_noble_family_title = yes }
                NOT = { is_holy_order = yes }
                NOT = { is_figurehead_title = yes }
                # Partition rulers may retain ordinary secondary crowns for
                # succession, but titular crowns have no de-jure inheritance
                # role and should still be retired by advanced management.
                OR = {
                    is_titular = yes
                    scope:rf_advanced_cleanup_ruler = {
                        NOT = {
                            OR = {
                                has_realm_law = confederate_partition_succession_law # gavelkind
                                has_realm_law = partition_succession_law
                                has_realm_law = high_partition_succession_law
                            }
                        }
                    }
                }
                # France and Aquitaine are deliberately kept together until
                # the holder can take the unification decision.
                NOT = { this = title:k_france }
                NOT = { this = title:k_aquitaine }
            }
            save_scope_as = rf_advanced_unwanted_title

            scope:rf_advanced_cleanup_ruler = {
                if = {
                    limit = {
                        exists = scope:rf_advanced_unwanted_title
                        scope:rf_advanced_unwanted_title = {
                            holder = scope:rf_advanced_cleanup_ruler
                            NOT = { this = scope:rf_advanced_cleanup_ruler.primary_title }
                        }
                    }
                    destroy_title = scope:rf_advanced_unwanted_title
                }
            }
        }
    }
}

riseandfall_ai_advanced_title_handout_se = {
    # Advanced mode: king-rank rulers relieve pressure with duchies first.
    # Emperor/hegemony rulers only grant a kingdom after exceeding their vassal
    # limit by at least three; the tax and levy loss makes this a last resort.
    # Spare-crown cleanup runs separately on the January yearly pulse.
    save_scope_as = emperor

    if = {
        limit = {
            is_ai = yes
            highest_held_title_tier >= tier_kingdom
            vassal_limit_percentage >= 0.95
            NOT = { has_variable = riseandfall_ai_advanced_title_action_cooldown }
        }

        ordered_realm_de_jure_duchy = {
            order_by = tier
            max = 1
            check_range_bounds = no
            limit = {
                exists = this
                holder = scope:emperor
                # Same-rank grants break vassalage, so only lower-tier titles
                # are eligible for advanced title handouts.
                tier < scope:emperor.primary_title.tier
                NOT = { any_de_jure_county = { this = scope:emperor.capital_province.county } }
                any_dejure_vassal_title_holder = {
                    is_landed = yes
                    highest_held_title_tier >= tier_county
                    highest_held_title_tier < tier_duchy
                    any_liege_or_above = { this = scope:emperor }
                    NOT = { this = scope:emperor }
                    is_adult = yes
                    is_imprisoned = no
                    NOT = { has_trait = incapable }
                    NOT = { has_trait = infirm }
                    NOT = { has_trait = warlord }
                    NOT = { has_trait = disloyal }
                    NOT = { is_at_war_with = scope:emperor }
                    NOT = { has_relation_rival = scope:emperor }
                    OR = {
                        opinion = { target = scope:emperor value >= -20 }
                        has_trait = loyal
                        has_trait = trusting
                        has_trait = content
                    }
                    OR = {
                        NOT = { government_has_flag = government_is_theocracy }
                        scope:emperor = { government_has_flag = government_is_theocracy }
                    }
                }
            }
            save_scope_as = target_title

            scope:target_title = {
                ordered_dejure_vassal_title_holder = {
                    limit = {
                        is_landed = yes
                        highest_held_title_tier >= tier_county
                        highest_held_title_tier < tier_duchy
                        any_liege_or_above = { this = scope:emperor }
                        NOT = { this = scope:emperor }
                        is_adult = yes
                        is_imprisoned = no
                        NOT = { has_trait = incapable }
                        NOT = { has_trait = infirm }
                        NOT = { has_trait = warlord }
                        NOT = { has_trait = disloyal }
                        NOT = { is_at_war_with = scope:emperor }
                        NOT = { has_relation_rival = scope:emperor }
                        OR = {
                            opinion = { target = scope:emperor value >= -20 }
                            has_trait = loyal
                            has_trait = trusting
                            has_trait = content
                        }
                        OR = {
                            NOT = { government_has_flag = government_is_theocracy }
                            scope:emperor = { government_has_flag = government_is_theocracy }
                        }
                    }
                    order_by = riseandfall_ai_advanced_title_grant_score_value
                    max = 1
                    check_range_bounds = no
                    save_scope_as = rf_advanced_chosen_vassal
                }
            }

            if = {
                limit = {
                    exists = scope:rf_advanced_chosen_vassal
                    scope:target_title = {
                        holder = scope:emperor
                        tier < scope:emperor.primary_title.tier
                        any_dejure_vassal_title_holder = {
                            this = scope:rf_advanced_chosen_vassal
                        }
                    }
                }
                scope:emperor = { riseandfall_ai_advanced_grant_target_duchy_se = yes }
            }
        }
    }

    if = {
        limit = {
            is_ai = yes
            primary_title.tier >= tier_empire
            NOT = { has_variable = riseandfall_ai_advanced_title_action_cooldown }
        }

        ordered_realm_de_jure_kingdom = {
            order_by = riseandfall_ai_advanced_kingdom_pressure_value
            max = 1
            check_range_bounds = no
            limit = {
                exists = this
                holder = scope:emperor
                # Same-rank grants break vassalage, so only lower-tier titles
                # are eligible for advanced title handouts.
                tier < scope:emperor.primary_title.tier
                NOT = { any_de_jure_county = { this = scope:emperor.capital_province.county } }
                any_dejure_vassal_title_holder = {
                    is_landed = yes
                    highest_held_title_tier >= tier_county
                    any_liege_or_above = { this = scope:emperor }
                    NOT = { this = scope:emperor }
                    is_adult = yes
                    is_imprisoned = no
                    NOT = { has_trait = incapable }
                    NOT = { has_trait = infirm }
                    NOT = { has_trait = warlord }
                    NOT = { has_trait = disloyal }
                    NOT = { is_at_war_with = scope:emperor }
                    NOT = { has_relation_rival = scope:emperor }
                    OR = {
                        opinion = { target = scope:emperor value >= -20 }
                        has_trait = loyal
                        has_trait = trusting
                        has_trait = content
                    }
                    OR = {
                        NOT = { government_has_flag = government_is_theocracy }
                        scope:emperor = { government_has_flag = government_is_theocracy }
                    }
                }
                scope:emperor = { vassal_limit_available < -2 }
            }
            save_scope_as = target_title

            # If this kingdom is most of the realm, do not create a super-vassal.
            # The cleanup below can destroy the title instead.
            if = {
                limit = {
                    NOT = {
                        scope:emperor = {
                            any_sub_realm_county = {
                                percent >= 0.75
                                de_jure_liege = {
                                    de_jure_liege = {
                                        this = scope:target_title
                                    }
                                }
                            }
                        }
                    }
                }

                scope:target_title = {
                    ordered_dejure_vassal_title_holder = {
                        limit = {
                            is_landed = yes
                            highest_held_title_tier >= tier_county
                            any_liege_or_above = { this = scope:emperor }
                            NOT = { this = scope:emperor }
                            is_adult = yes
                            is_imprisoned = no
                            NOT = { has_trait = incapable }
                            NOT = { has_trait = infirm }
                            NOT = { has_trait = warlord }
                            NOT = { has_trait = disloyal }
                            NOT = { is_at_war_with = scope:emperor }
                            NOT = { has_relation_rival = scope:emperor }
                            OR = {
                                opinion = { target = scope:emperor value >= -20 }
                                has_trait = loyal
                                has_trait = trusting
                                has_trait = content
                            }
                            OR = {
                                NOT = { government_has_flag = government_is_theocracy }
                                scope:emperor = { government_has_flag = government_is_theocracy }
                            }
                        }
                        order_by = riseandfall_ai_advanced_title_grant_score_value
                        max = 1
                        check_range_bounds = no
                        save_scope_as = rf_advanced_chosen_vassal
                    }
                }

                if = {
                    limit = {
                        exists = scope:rf_advanced_chosen_vassal
                        scope:target_title = {
                            holder = scope:emperor
                            tier < scope:emperor.primary_title.tier
                            any_dejure_vassal_title_holder = {
                                this = scope:rf_advanced_chosen_vassal
                            }
                        }
                    }
                    scope:emperor = { riseandfall_ai_advanced_grant_target_kingdom_se = yes }
                }
            }
        }
    }

}

############################################################
# Rise and Fall: Grant counties scripted effect
# Grants actor-owned de jure counties to suitable courtiers, preferring the
# county's culture and faith, and generates a matching character only when no
# eligible courtier is available. Excludes counties in the AI liege's capital kingdom.
############################################################

riseandfall_grant_counties_se = {
    # Expecting root scope to be the liege (ruler) who clicked the decision.
    save_scope_as = liege
    # Use a courtier-safe version of the Advanced AI trait and loyalty score.
    save_scope_as = emperor

    # County rulers cannot safely create a subordinate county vassal.
    if = {
        limit = { is_landed = yes primary_title.tier >= tier_duchy }

    # Save the de jure kingdom that contains the liege's capital province
    scope:liege = {
        capital_province = {
            county = {
                de_jure_liege = {
                    de_jure_liege = {
                        save_scope_as = capital_dejure_kingdom
                    }
                }
            }
        }
    }

    # Iterate de-jure duchies in the liege's realm, then examine each duchy's direct de-jure vassal titles
    # for county-tier titles held by the liege (this is a supported iterator pattern and covers normal
    # county->duchy hierarchies). Exclude counties that belong to the de jure kingdom containing the liege's capital.
    scope:liege = {
        every_realm_de_jure_duchy = {
            limit = { exists = this }
            save_scope_as = duchy

            scope:duchy = {
                every_direct_de_jure_vassal_title = {
                    limit = {
                        tier = tier_county
                        holder = scope:liege
                        # Never grant the liege's capital county.
                        NOT = { this = scope:liege.capital_province.county }
                        # Allow player lieges to grant counties that are de jure to the capital's kingdom.
                        # For AI lieges, continue to exclude counties that belong to the de jure kingdom
                        # containing the liege's capital.
                        OR = {
                            scope:liege = { is_ai = no }
                            NOT = {
                                AND = {
                                    exists = scope:capital_dejure_kingdom
                                    de_jure_liege = {
                                        de_jure_liege = {
                                            this = scope:capital_dejure_kingdom
                                        }
                                    }
                                }
                            }
                        }
                    }
                    save_scope_as = target_county

                    # Prefer a qualified local courtier from the liege's own court.
                    # The Advanced AI-equivalent courtier score promotes
                    # loyal, trusting, content, humble, patient, just, and honest
                    # recipients while penalizing dangerous personality traits.
                    # Clear this per county so a prior recipient cannot be reused.
                    clear_saved_scope = county_grant_recipient
                    scope:liege = {
                        ordered_courtier = {
                            limit = {
                                is_alive = yes
                                is_adult = yes
                                is_ruler = no
                                is_imprisoned = no
                                is_incapable = no
                                NOT = { has_trait = warlord }
                                NOT = { has_trait = disloyal }
                                culture = scope:target_county.culture
                                faith = scope:target_county.faith
                            }
                            order_by = riseandfall_county_grant_courtier_score_value
                            max = 1
                            check_range_bounds = no
                            save_scope_as = county_grant_recipient
                        }
                    }

                    # If the ruler has no local candidate, borrow a matching
                    # courtier from a random vassal court that has one.
                    if = {
                        limit = { NOT = { exists = scope:county_grant_recipient } }
                        scope:liege = {
                            random_vassal_or_below = {
                                limit = {
                                    is_landed = yes
                                    any_courtier = {
                                        is_alive = yes
                                        is_adult = yes
                                        is_ruler = no
                                        is_imprisoned = no
                                        is_incapable = no
                                        NOT = { has_trait = warlord }
                                        NOT = { has_trait = disloyal }
                                        culture = scope:target_county.culture
                                        faith = scope:target_county.faith
                                    }
                                }
                                ordered_courtier = {
                                    limit = {
                                        is_alive = yes
                                        is_adult = yes
                                        is_ruler = no
                                        is_imprisoned = no
                                        is_incapable = no
                                        NOT = { has_trait = warlord }
                                        NOT = { has_trait = disloyal }
                                        culture = scope:target_county.culture
                                        faith = scope:target_county.faith
                                    }
                                    order_by = riseandfall_county_grant_courtier_score_value
                                    max = 1
                                    check_range_bounds = no
                                    save_scope_as = county_grant_recipient
                                }
                            }
                        }
                    }

                    # No matching courtier exists anywhere in the realm: create
                    # a local-culture, local-faith adult in the liege's court.
                    if = {
                        limit = { NOT = { exists = scope:county_grant_recipient } }
                        scope:liege = {
                            create_character = {
                                culture = scope:target_county.culture
                                faith = scope:target_county.faith
                                age = { 18 35 }
                                gender = male
                                employer = scope:liege
                                save_scope_as = county_grant_recipient
                            }
                        }
                    }

                    # Grant the county to the selected or generated recipient.
                    # Skip granting if the target county/title has the giveaway-block variable AND the liege is a human player.
                    scope:target_county = {
                        if = {
                            limit = {
                                exists = scope:county_grant_recipient
                                NOT = { AND = { has_variable = Riseandfall_giveaway_blocked scope:liege = { is_ai = no } } }
                            }
                            scope:county_grant_recipient = {
                                hidden_effect = {
                                    add_opinion = {
                                        target = scope:liege
                                        modifier = received_title_county
                                    }
                                }
                            }
                            create_title_and_vassal_change = { type = granted save_scope_as = change }
                            change_title_holder_include_vassals = { holder = scope:county_grant_recipient change = scope:change take_baronies = no }
                            resolve_title_and_vassal_change = scope:change
                            # Notify the liege with the county name granted (post-action popup)
                            scope:liege = {
                                send_interface_message = {
                                    type = send_interface_message_good
                                    title = riseandfall_grant_county_popup_title
                                    custom_tooltip = { text = riseandfall_grant_county_popup_desc subject = scope:target_county }
                                    left_icon = scope:county_grant_recipient
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    }
}
