﻿#################################################################################
# Player-side automatic title automanagement scripted effects
# These mirror the AI automation logic but are gated by character flags
# (set/cleared by player decisions). They are invoked from the yearly global
# pulse on_action registered in `common/on_action/riseandfall_ai_title.txt`.
#################################################################################

# Player: auto-create kingdom titles when the ruler has the toggle modifier
riseandfall_player_create_kingdoms_se = {
    # Called for a specific ruler (the caller should iterate every_ruler is_ai = no).
    save_scope_as = acting_ruler

    # Only proceed for rulers who are landed (manual create behavior)
    if = {
        limit = { is_landed = yes }

        ordered_alert_creatable_title = {
            order_by = tier
            check_range_bounds = no
            max = 99

            limit = {
                tier = tier_kingdom
                scope:acting_ruler = {
                    OR = {
                        primary_title.tier = tier_empire
                        government_has_mechanic = administrative
                        has_realm_law = partition_succession_law
                        has_realm_law = confederate_partition_succession_law
                        has_realm_law = high_partition_succession_law
                    }
                }
                NOT = { tier = scope:acting_ruler.primary_title.tier }
            }

            save_scope_as = target_title

            scope:acting_ruler = {
                create_title_and_vassal_change = { type = created save_scope_as = title_change add_claim_on_loss = no }

                prev = { change_title_holder = { holder = scope:acting_ruler change = scope:title_change } }

                resolve_title_and_vassal_change = scope:title_change

                if = {
                    limit = { primary_title.tier = tier_kingdom }
                    if = {
                        limit = {
                            prev = { holder = { monthly_character_income > scope:acting_ruler.primary_title.holder.monthly_character_income } }
                        }
                        set_primary_title_to = prev
                    }
                }
            }
        }
    }
}

# Player: transfer eligible direct vassals to their rightful de jure liege.
riseandfall_player_transfer_rightful_vassals_se = {
    # CONTRACT
    # Inputs: current ruler scope with direct landed vassals.
    # Outputs: eligible direct vassals are reassigned to their de jure holder or that holder's direct liege.
    # Data shape: character liege changes via create_title_and_vassal_change / change_liege / resolve_title_and_vassal_change.
    # Error modes: missing de jure holders, wars, rank mismatches, or government edge cases skip the transfer.

    save_scope_as = actor

    if = {
        limit = { is_landed = yes }

        every_vassal = {
            limit = {
                liege = scope:actor
                highest_held_title_tier >= tier_county
                exists = primary_title
                exists = primary_title.de_jure_liege
                primary_title.de_jure_liege.holder != liege
                NOT = { is_at_war_with = scope:actor }
                NOT = {
                    any_vassal_or_below = {
                        is_at_war_with = scope:actor
                    }
                }
                NAND = {
                    is_house_head = yes
                    house.house_confederation.leading_house = house
                }
            }

            save_temporary_scope_as = vassal_to_transfer

            if = {
                limit = {
                    exists = primary_title.de_jure_liege.holder
                    primary_title.de_jure_liege.holder = {
                        liege = scope:actor
                        highest_held_title_tier > scope:vassal_to_transfer.highest_held_title_tier
                        NOR = {
                            is_at_war_with = scope:actor
                            is_at_war_with = scope:vassal_to_transfer
                        }
                    }
                    NAND = {
                        primary_title.de_jure_liege.holder.liege ?= { has_government = japan_administrative_government }
                        primary_title.de_jure_liege.holder ?= { has_government = japan_administrative_government }
                        has_government = japan_feudal_government
                    }
                }

                primary_title.de_jure_liege.holder = { save_temporary_scope_as = transfer_recipient }

                scope:actor = {
                    create_title_and_vassal_change = {
                        type = granted
                        save_scope_as = change
                        add_claim_on_loss = no
                    }
                }

                change_liege = {
                    liege = scope:transfer_recipient
                    change = scope:change
                }

                scope:actor = { resolve_title_and_vassal_change = scope:change }

                scope:transfer_recipient = {
                    add_opinion = {
                        target = scope:actor
                        modifier = granted_vassal
                    }
                }
            }
            else_if = {
                limit = {
                    exists = primary_title.de_jure_liege.holder.liege
                    primary_title.de_jure_liege.holder.liege = {
                        this != scope:actor
                        liege = scope:actor
                        highest_held_title_tier > scope:vassal_to_transfer.highest_held_title_tier
                        NOR = {
                            is_at_war_with = scope:actor
                            is_at_war_with = scope:vassal_to_transfer
                        }
                    }
                    NAND = {
                        primary_title.de_jure_liege.holder.liege ?= { has_government = japan_administrative_government }
                        primary_title.de_jure_liege.holder ?= { has_government = japan_administrative_government }
                        has_government = japan_feudal_government
                    }
                }

                primary_title.de_jure_liege.holder.liege = { save_temporary_scope_as = transfer_recipient }

                scope:actor = {
                    create_title_and_vassal_change = {
                        type = granted
                        save_scope_as = change
                        add_claim_on_loss = no
                    }
                }

                change_liege = {
                    liege = scope:transfer_recipient
                    change = scope:change
                }

                scope:actor = { resolve_title_and_vassal_change = scope:change }

                scope:transfer_recipient = {
                    add_opinion = {
                        target = scope:actor
                        modifier = granted_vassal
                    }
                }
            }
        }
    }
}

# Assign a suitable court guardian to one child, respecting the two-ward limit.
# This helper is called with each child already saved as rf_guardian_child.
riseandfall_assign_best_guardian_to_child_se = {
    clear_saved_scope = rf_guardian_candidate

    # Search the ruler's court explicitly; the current scope is the child.
    scope:rf_guardian_actor = {
        ordered_courtier = {
            limit = {
                is_physically_able_adult = yes
                is_imprisoned = no
                NOT = { has_trait = incapable }
                num_of_relation_ward < 2
            }
            order_by = riseandfall_guardian_candidate_score_value
            max = 1
            check_range_bounds = no
            save_scope_as = rf_guardian_candidate
        }
    }

    # A court with no eligible adult can still use the player ruler.
    if = {
        limit = {
            NOT = { exists = scope:rf_guardian_candidate }
            scope:rf_guardian_actor = {
                is_physically_able_adult = yes
                is_imprisoned = no
                NOT = { has_trait = incapable }
                num_of_relation_ward < 2
            }
        }
        scope:rf_guardian_actor = { save_scope_as = rf_guardian_candidate }
    }

    if = {
        limit = {
            exists = scope:rf_guardian_candidate
            scope:rf_guardian_candidate = {
                num_of_relation_ward < 2
                NOT = { has_relation_ward = scope:rf_guardian_child }
            }
        }
        scope:rf_guardian_candidate = { save_scope_as = guardian }
        scope:rf_guardian_child = { save_scope_as = ward }
        scope:rf_guardian_actor = { save_scope_as = ward_liege }
        scope:rf_guardian_actor = { save_scope_as = guardian_liege }

        # Use vanilla's relationship path for children already in this court.
        educate_child_event_effect = yes
    }

    clear_saved_scope = rf_guardian_candidate
    clear_saved_scope = rf_guardian_child
}

# Player: assign guardians to primary-title heirs in succession order first,
# then assign the remaining unguarded house children in the ruler's court.
riseandfall_player_automate_house_child_guardians_se = {
    save_scope_as = rf_guardian_actor

    if = {
        limit = { exists = primary_title }
        primary_title = {
            # ordered_title_heir follows the title's actual succession line.
            ordered_title_heir = {
                limit = {
                    is_adult = no
                    is_available_child_allow_travel = yes
                    num_of_relation_guardian = 0
                    exists = house
                    house = scope:rf_guardian_actor.house
                    is_courtier_of = scope:rf_guardian_actor
                }
                max = 99
                check_range_bounds = no

                add_to_temporary_list = rf_guardian_succession_children
                save_scope_as = rf_guardian_child
                riseandfall_assign_best_guardian_to_child_se = yes
            }
        }
    }

    # Preserve coverage for eligible house children who are not heirs to the
    # primary title, after succession-order children receive first choice.
    scope:rf_guardian_actor = {
        ordered_courtier = {
            limit = {
                is_adult = no
                is_available_child_allow_travel = yes
                num_of_relation_guardian = 0
                exists = house
                house = scope:rf_guardian_actor.house
                NOT = { is_in_list = rf_guardian_succession_children }
            }
            order_by = riseandfall_guardian_child_priority_value
            max = 99
            check_range_bounds = no

            save_scope_as = rf_guardian_child
            riseandfall_assign_best_guardian_to_child_se = yes
        }
    }
}
# Player: auto-create duchies when the ruler/character has the toggle modifier
riseandfall_player_create_duchies_se = {
    # Called for a specific ruler (the caller should iterate every_ruler is_ai = no).
    save_scope_as = acting_count

    if = {
        limit = { is_landed = yes }

        ordered_alert_creatable_title = {
            order_by = tier
            check_range_bounds = no
            max = 99

            limit = { tier = tier_duchy }

            save_scope_as = target_title

            scope:acting_count = {
                create_title_and_vassal_change = { type = created save_scope_as = title_change add_claim_on_loss = no }

                prev = { change_title_holder = { holder = scope:acting_count change = scope:title_change } }

                resolve_title_and_vassal_change = scope:title_change

                if = { limit = { primary_title.tier = tier_county } set_primary_title_to = prev }
            }
        }
    }
}

# Warlord: create every uncreated de jure duchy, kingdom, and empire where the
# warlord holds a majority of the relevant de jure land. Warlord creation intentionally uses
# the scripted path so government restrictions do not hide or block it.
# Duchies/kingdoms/empires are created in ascending
# tier order so duchy titles exist before kingdom titles are claimed.
riseandfall_warlord_create_realm_titles_se = {
    save_scope_as = acting_warlord

    if = {
        limit = {
            is_landed = yes
            riseandfall_is_any_warlord_trigger = yes
        }

        # Duchies first (tier_duchy), then kingdoms, then empires.
        every_realm_de_jure_duchy = {
            limit = {
                is_title_created = no
                any_de_jure_county = {
                    percent > 0.5
                    holder = {
                        OR = {
                            this = scope:acting_warlord
                            any_liege_or_above = { this = scope:acting_warlord }
                        }
                    }
                }
            }
            save_scope_as = target_title

            scope:acting_warlord = {
                create_title_and_vassal_change = { type = created save_scope_as = title_change add_claim_on_loss = no }
                scope:target_title = { change_title_holder = { holder = scope:acting_warlord change = scope:title_change } }
                resolve_title_and_vassal_change = scope:title_change
                if = { limit = { primary_title.tier = tier_county } set_primary_title_to = scope:target_title }
            }
        }

        every_realm_de_jure_kingdom = {
            limit = {
                is_title_created = no
                any_de_jure_county = {
                    percent > 0.5
                    holder = {
                        OR = {
                            this = scope:acting_warlord
                            any_liege_or_above = { this = scope:acting_warlord }
                        }
                    }
                }
            }
            save_scope_as = target_title

            scope:acting_warlord = {
                create_title_and_vassal_change = { type = created save_scope_as = title_change add_claim_on_loss = no }
                scope:target_title = { change_title_holder = { holder = scope:acting_warlord change = scope:title_change } }
                resolve_title_and_vassal_change = scope:title_change
                if = { limit = { scope:target_title.tier > primary_title.tier } set_primary_title_to = scope:target_title }
            }
        }

        every_realm_de_jure_empire = {
            limit = {
                is_title_created = no
                any_de_jure_county = {
                    percent > 0.5
                    holder = {
                        OR = {
                            this = scope:acting_warlord
                            any_liege_or_above = { this = scope:acting_warlord }
                        }
                    }
                }
            }
            save_scope_as = target_title

            scope:acting_warlord = {
                create_title_and_vassal_change = { type = created save_scope_as = title_change add_claim_on_loss = no }
                scope:target_title = { change_title_holder = { holder = scope:acting_warlord change = scope:title_change } }
                resolve_title_and_vassal_change = scope:title_change
                if = { limit = { scope:target_title.tier > primary_title.tier } set_primary_title_to = scope:target_title }
            }
        }
    }
}

# Player: auto-grant duchy titles to de jure vassals (uses Advanced AI recipient logic).
riseandfall_player_grant_duchies_se = {
    # Expects to be called in a ruler scope (the caller should iterate every_ruler is_ai = no).
    save_scope_as = actor
    # The shared Advanced AI score value reads this scope for opinion, culture,
    # faith, and dynasty comparisons; for manual grants it is the player ruler.
    save_scope_as = emperor

    # Do not grant duchies at the actor's own rank: recipients would leave the realm.
    if = { limit = { is_landed = yes primary_title.tier > tier_duchy }

        # Iterate de-jure duchies in the realm
        every_realm_de_jure_duchy = {
            limit = { exists = this holder = scope:actor }
            save_scope_as = target_title

            if = {
                limit = { scope:target_title = { holder = scope:actor } }

                # Don't hand out duchies that contain the actor's capital
                if = {
                    limit = { NOT = { scope:target_title = { any_de_jure_county = { this = scope:actor.capital_province.county } } } }

                    scope:target_title = {
                        # Match Advanced AI: choose the safest, best-qualified
                        # county vassal instead of a random de jure holder.
                        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:actor }
                                NOT = { this = scope:actor }
                                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:actor }
                                NOT = { has_relation_rival = scope:actor }
                                OR = {
                                    opinion = { target = scope:actor value >= -20 }
                                    has_trait = loyal
                                    has_trait = trusting
                                    has_trait = content
                                }
                                OR = {
                                    NOT = { government_has_flag = government_is_theocracy }
                                    scope:actor = { government_has_flag = government_is_theocracy }
                                }
                            }
                            order_by = riseandfall_ai_advanced_title_grant_score_value
                            max = 1
                            check_range_bounds = no
                            save_scope_as = chosen_vassal
                        }
                    }

                    if = {
                        limit = {
                            exists = scope:chosen_vassal
                            scope:chosen_vassal = { any_liege_or_above = { this = scope:actor } }
                            OR = {
                                NOT = { scope:chosen_vassal = { government_has_flag = government_is_theocracy } }
                                scope:actor = { government_has_flag = government_is_theocracy }
                            }
                        }

                        # Don't grant titles that have giveaway blocked when the actor is a human player.
                        if = {
                            limit = { NOT = { AND = { scope:target_title = { has_variable = Riseandfall_giveaway_blocked } scope:actor = { is_ai = no } } } }
                            scope:chosen_vassal = {
                                hidden_effect = {
                                    add_opinion = {
                                        target = scope:actor
                                        modifier = received_title_duchy
                                    }
                                }
                            }
                            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 = {
                        if = {
                            limit = {
                                exists = scope:chosen_vassal
                                scope:chosen_vassal = { government_has_flag = government_is_theocracy }
                                NOT = { scope:actor = { government_has_flag = government_is_theocracy } }
                            }
                        }
                    }
                }
            }
        }
    }
}

# Player: auto-grant kingdoms when the ruler has the toggle (same adaptation pattern as AI)
riseandfall_player_grant_kingdoms_se = {
    # Expects to be called in a ruler scope (the caller should iterate every_ruler is_ai = no).
    save_scope_as = actor
    # The shared Advanced AI score value reads this scope for recipient ranking.
    save_scope_as = emperor

    # Do not grant kingdoms at the actor's own rank: recipients would leave the realm.
    if = { limit = { is_landed = yes primary_title.tier > tier_kingdom }

        every_realm_de_jure_kingdom = {
            limit = { exists = this holder = scope:actor }
            save_scope_as = target_title

            if = {
                limit = { scope:target_title = { holder = scope:actor } }

                if = {
                    limit = {
                        NOT = { scope:actor = { primary_title = { de_jure_liege = scope:target_title } } }
                        NOT = { scope:target_title = { any_de_jure_county = { this = scope:actor.capital_province.county } } }
                    }

                    scope:target_title = {
                        # Match Advanced AI: rank all safe de jure vassals by
                        # loyalty, character traits, realm fit, and diplomacy.
                        ordered_dejure_vassal_title_holder = {
                            limit = {
                                is_landed = yes
                                highest_held_title_tier >= tier_county
                                any_liege_or_above = { this = scope:actor }
                                NOT = { this = scope:actor }
                                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:actor }
                                NOT = { has_relation_rival = scope:actor }
                                OR = {
                                    opinion = { target = scope:actor value >= -20 }
                                    has_trait = loyal
                                    has_trait = trusting
                                    has_trait = content
                                }
                                OR = {
                                    NOT = { government_has_flag = government_is_theocracy }
                                    scope:actor = { government_has_flag = government_is_theocracy }
                                }
                            }
                            order_by = riseandfall_ai_advanced_title_grant_score_value
                            max = 1
                            check_range_bounds = no
                            save_scope_as = chosen_vassal
                        }
                    }

                    if = {
                        limit = {
                            exists = scope:chosen_vassal
                            scope:chosen_vassal = { any_liege_or_above = { this = scope:actor } }
                            OR = {
                                NOT = { scope:chosen_vassal = { government_has_flag = government_is_theocracy } }
                                scope:actor = { government_has_flag = government_is_theocracy }
                            }
                        }

                        # Skip granting if the target title has the giveaway-block variable AND the actor is a human player.
                        if = {
                            limit = { NOT = { AND = { scope:target_title = { has_variable = Riseandfall_giveaway_blocked } scope:actor = { is_ai = no } } } }
                            scope:chosen_vassal = {
                                hidden_effect = {
                                    add_opinion = {
                                        target = scope:actor
                                        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

                            # Transfer de jure duchies under the granted kingdom to the new holder
                            scope:target_title = {
                                    every_direct_de_jure_vassal_title = {
                                        limit = { tier = tier_duchy holder != scope:chosen_vassal }
                                        create_title_and_vassal_change = { type = granted save_scope_as = duchy_change }
                                        change_title_holder_include_vassals = { holder = scope:chosen_vassal change = scope:duchy_change take_baronies = no }
                                        resolve_title_and_vassal_change = scope:duchy_change
                                    }
                            }
                        }
                    }
                }
            }
        }
    }
}

# Player: grant empire titles only from a hegemony-tier primary title, so the
# recipient remains a vassal. Uses the same qualified de jure recipient logic
# as manual duchy and kingdom grants.
riseandfall_player_grant_empires_se = {
    save_scope_as = actor
    # The shared Advanced AI score value reads this scope for recipient ranking.
    save_scope_as = emperor

    if = {
        limit = {
            is_landed = yes
            primary_title.tier > tier_empire
        }

        every_realm_de_jure_empire = {
            limit = {
                exists = this
                holder = scope:actor
            }
            save_scope_as = target_title

            if = {
                limit = {
                    scope:target_title = {
                        holder = scope:actor
                        # Never grant a same-rank title: it creates independence.
                        tier < scope:actor.primary_title.tier
                    }
                }

                # Keep the empire containing the ruler's capital and the
                # de jure empire of the primary title under the player.
                if = {
                    limit = {
                        NOT = { scope:actor = { primary_title = { de_jure_liege = scope:target_title } } }
                        NOT = { scope:target_title = { any_de_jure_county = { this = scope:actor.capital_province.county } } }
                    }

                    # Clear this per empire so a recipient from an earlier
                    # iteration cannot be reused when this empire has none.
                    clear_saved_scope = chosen_vassal
                    scope:target_title = {
                        ordered_dejure_vassal_title_holder = {
                            limit = {
                                is_landed = yes
                                highest_held_title_tier >= tier_county
                                any_liege_or_above = { this = scope:actor }
                                NOT = { this = scope:actor }
                                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:actor }
                                NOT = { has_relation_rival = scope:actor }
                                OR = {
                                    opinion = { target = scope:actor value >= -20 }
                                    has_trait = loyal
                                    has_trait = trusting
                                    has_trait = content
                                }
                                OR = {
                                    NOT = { government_has_flag = government_is_theocracy }
                                    scope:actor = { government_has_flag = government_is_theocracy }
                                }
                            }
                            order_by = riseandfall_ai_advanced_title_grant_score_value
                            max = 1
                            check_range_bounds = no
                            save_scope_as = chosen_vassal
                        }
                    }

                    if = {
                        limit = {
                            exists = scope:chosen_vassal
                            scope:chosen_vassal = { any_liege_or_above = { this = scope:actor } }
                            scope:target_title = {
                                any_dejure_vassal_title_holder = { this = scope:chosen_vassal }
                            }
                            OR = {
                                NOT = { scope:chosen_vassal = { government_has_flag = government_is_theocracy } }
                                scope:actor = { government_has_flag = government_is_theocracy }
                            }
                        }

                        # Respect player title-level giveaway blocks.
                        if = {
                            limit = { NOT = { scope:target_title = { has_variable = Riseandfall_giveaway_blocked } } }
                            scope:chosen_vassal = {
                                hidden_effect = {
                                    add_opinion = {
                                        target = scope:actor
                                        modifier = received_title_empire
                                    }
                                }
                            }
                            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

                            # Consolidate personally held de jure kingdoms under
                            # the new empire holder without disturbing other rulers.
                            scope:target_title = {
                                every_direct_de_jure_vassal_title = {
                                    limit = {
                                        tier = tier_kingdom
                                        holder = scope:actor
                                        NOT = { holder = scope:chosen_vassal }
                                    }
                                    create_title_and_vassal_change = { type = granted save_scope_as = kingdom_change }
                                    change_title_holder_include_vassals = {
                                        holder = scope:chosen_vassal
                                        change = scope:kingdom_change
                                        take_baronies = no
                                    }
                                    resolve_title_and_vassal_change = scope:kingdom_change
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
