﻿apply_dynamic_duchy_offset_effect = {
    # 1. Clear old values from vassals
    every_vassal = {
        if = {
            limit = {
                has_opinion_modifier = {
                    modifier = dynamic_duchy_offset_opinion
                    target = root
                }
            }
            remove_opinion = {
                modifier = dynamic_duchy_offset_opinion
                target = root
            }
        }
    }

    # 2. Check for Innovation
    if = {
        limit = {
            culture = { has_innovation = innovation_ordonnances_royales }
        }

        # 3. Count Duchies using set_variable math
        set_variable = {
            name = current_duchy_count
            value = 0
        }
        every_held_title = {
            limit = { tier = tier_duchy }
            root = {
                set_variable = {
                    name = current_duchy_count
                    value = {
                        value = var:current_duchy_count
                        add = 1
                    }
                }
            }
        }

        # 4. Calculate Offset: (Duchies - 2) * 15
        save_scope_value_as = {
            name = calculated_duchy_offset
            value = {
                value = var:current_duchy_count
                subtract = 2
                multiply = 15
            }
        }
        
        remove_variable = current_duchy_count

        # 5. Apply to all vassals
        if = {
            limit = { scope:calculated_duchy_offset > 0 }
            every_vassal = {
                add_opinion = {
                    modifier = dynamic_duchy_offset_opinion
                    target = root
                    opinion = {
                        value = scope:calculated_duchy_offset
                    }
                }
            }
        }
    }
}