// priority: 999999
//此文件用于配置士兵招募,默认武器,可用武器
let RECRUIT_CONFIGS = {
    'snk_recruit_militia': {                       //名字等于FTB自定义奖励标签
        entityId: "hundred_years_war:militia",     //士兵ID
        displayName: '民兵',                       //仅用于提示时显示的名字
        costAmount: 10,                            //招募和转职的价格
        costItem: 'minecraft:amethyst_shard',      //货币ID（通常是紫水晶碎片）
        ProvideWeapons: false,                     //是否需要玩家提供武器装备
        occupation: 1,                             //远征占用值
        type: 'militia'                            //标签，用于识别士兵 
    },
    'snk_recruit_hunter': {
        entityId: "hundred_years_war:archer",
        displayName: '猎户',
        costAmount: 10,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 1,
        type: 'hunter'
    },
    'snk_recruit_spike_man': {
        entityId: "hundred_years_war:spear_man",
        displayName: '长矛兵',
        costAmount: 40,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 2,
        type: 'spear_man'
    },
    'snk_recruit_scroll_warrior': {
        entityId: "hundred_years_war:warrior",
        displayName: '战士',
        costAmount: 40,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 2,
        type: 'warrior'
    },
    'snk_recruit_scroll_sword_dancer': {
        entityId: "hundred_years_war:warrior",
        displayName: '剑舞者',
        costAmount: 80,
        costItem: 'minecraft:amethyst_shard',
        costAmount2: 5,
        costItem2: 'minecraft:enchanted_book',
        weaponEnchantments: [
            { id: 'jlme:parry', lvl: 1 }
        ],
        weaponOffhandEnchantments: [
            { id: 'jlme:parry', lvl: 1 }
        ],
        leggingsEnchantments: [
            { id: 'jlme:evasive', lvl: 1 }
        ],
        ProvideWeapons: false,
        occupation: 3,
        type: 'sword_dancer'
    },
    'snk_recruit_scroll_shieldman': {
        entityId: "hundred_years_war:shieldman",
        displayName: '卫兵',
        costAmount: 60,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 3,
        type: 'shieldman'
    },
    'snk_recruit_scroll_shield_guardian': {
        entityId: "hundred_years_war:shieldman",
        displayName: '守护者',
        costAmount: 120,
        costItem: 'minecraft:amethyst_shard',
        costAmount2: 5,
        costItem2: 'minecraft:enchanted_book',
        weaponEnchantments: [
            { id: 'aggrofix:aggronizing', lvl: 5 }
        ],
        weaponOffhandEnchantments: [
            { id: 'jlme:natural_blocking', lvl: 1 }
        ],
        ProvideWeapons: false,
        occupation: 4,
        type: 'shield_guardian'
    },
    'snk_recruit_scroll_archer': {
        entityId: "hundred_years_war:archer",
        displayName: '弓箭手',
        costAmount: 40,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 2,
        type: 'archer'
    },
    'snk_recruit_scroll_poisoned_archer': {
        entityId: "hundred_years_war:archer",
        displayName: '毒箭手',
        costAmount: 80,
        costItem: 'minecraft:amethyst_shard',
        costAmount2: 5,
        costItem2: 'minecraft:enchanted_book',
        weaponEnchantments: [
            { id: 'call_of_yucutan:toxic_blade', lvl: 2 }
        ],
        leggingsEnchantments: [
            { id: 'jlme:evasive', lvl: 1 }
        ],
        ProvideWeapons: false,
        occupation: 3,
        type: 'poisoned_archer'
    },
    'snk_recruit_scroll_crossbowman': {
        entityId: "hundred_years_war:crossbowman",
        displayName: '弩手',
        costAmount: 40,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 2,
        type: 'crossbowman'
    },
    'snk_recruit_scroll_heavy_crossbowman': {
        entityId: "hundred_years_war:crossbowman",
        displayName: '重弩手',
        costAmount: 80,
        costItem: 'minecraft:amethyst_shard',
        costAmount2: 5,
        costItem2: 'minecraft:enchanted_book',
        weaponEnchantments: [
            { id: 'jlme:piercing_capabilities', lvl: 2 }
        ],
        leggingsEnchantments: [
            { id: 'jlme:evasive', lvl: 1 }
        ],
        ProvideWeapons: false,
        occupation: 3,
        type: 'heavy_crossbowman'
    },
    'snk_recruit_scroll_handgonne_man': {
        entityId: "hundred_years_war:handgonne_man",
        displayName: '手铳兵',
        costAmount: 80,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 3,
        type: 'handgonne_man'
    },
    'snk_recruit_scroll_matchlock_man': {
        entityId: "hundred_years_war:matchlock_man",
        displayName: '火枪手',
        costAmount: 200,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 4,
        type: 'matchlock_man'
    }
    ,
    'snk_recruit_scroll_priest': {
        entityId: "hundred_years_war:priest",
        displayName: '祭司',
        costAmount: 80,
        costItem: 'minecraft:amethyst_shard',
        ProvideWeapons: false,
        occupation: 3,
        type: 'priest'
    }
}

// 基于士兵tag的武器配置
let WEAPON_CONFIG_BY_TAG = {
    // 民兵
    "militia": {
        mainHand: /(_sword|_axe|_spear)$/,
        offHand: /(minecraft:air|wooden_shield|stone_shield|golden_shield|iron_shield|diamond_shield|netherite_shield)$/,
        defaultMainHand: 'sticknstone:stone_spear',
        defaultOffHand: 'shieldexex:wooden_shield'
    },
    // 长矛兵
    "spear_man": {
        mainHand: /(_pike|_spear|_glaive|_halberd|_chakram)$/,
        offHand: /(minecraft:air|wooden_shield|stone_shield|golden_shield|iron_shield|diamond_shield|netherite_shield|_chakram)$/,
        defaultMainHand: 'hundred_years_war:stone_pike',
        defaultOffHand: 'minecraft:air'
    },
    // 战士
    "warrior": {
        mainHand: /(_sword|_axe|_katana|_sai|_cutlass|_claymore|_greataxe|_greathammer)$/,
        offHand: /(minecraft:air|_sword|_axe|_sai|_cutlass)$/,
        defaultMainHand: 'minecraft:stone_axe',
        defaultOffHand: 'minecraft:air'
    },
    // 剑舞者
    "sword_dancer": {
        mainHand: /./,
        offHand: /./,
        defaultMainHand: 'minecraft:stone_sword',
        defaultOffHand: 'minecraft:stone_sword'
    },
    // 盾兵
    "shieldman": {
        mainHand: /(_sword|_longsword|_rapier|_cutlass|_spear|shield)$/,
        offHand: /(minecraft:air|shield)$/,
        defaultMainHand: 'minecraft:stone_sword',
        defaultOffHand: 'shieldexex:wooden_tower_shield'
    },
    // 守护者
    "shield_guardian": {
        mainHand: /./,
        offHand: /./,
        defaultMainHand: 'minecraft:stone_sword',
        defaultOffHand: 'shieldexex:wooden_tower_shield'
    },
    // 猎户
    "hunter": {
        mainHand: /^minecraft:bow$/,
        offHand: /^minecraft:air$/,
        defaultMainHand: 'minecraft:bow',
        defaultOffHand: 'minecraft:air'
    },
    // 弓箭手
    "archer": {
        mainHand: /^minecraft:bow$/,
        offHand: /^minecraft:air$/,
        defaultMainHand: 'minecraft:bow',
        defaultOffHand: 'minecraft:air'
    },
    // 毒箭手
    "poisoned_archer": {
        mainHand: /^minecraft:bow$/,
        offHand: /(minecraft:air|wooden_shield|stone_shield|golden_shield|iron_shield|diamond_shield|netherite_shield)$/,
        defaultMainHand: 'minecraft:bow',
        defaultOffHand: 'minecraft:air'
    },
    // 弩手
    "crossbowman": {
        mainHand: /^minecraft:crossbow$/,
        offHand: /^minecraft:air$/,
        defaultMainHand: 'minecraft:crossbow',
        defaultOffHand: 'minecraft:air'
    },
    // 重弩手
    "heavy_crossbowman": {
        mainHand: /^minecraft:crossbow$/,
        offHand: /(minecraft:air|wooden_shield|stone_shield|golden_shield|iron_shield|diamond_shield|netherite_shield)$/,
        defaultMainHand: 'minecraft:crossbow',
        defaultOffHand: 'minecraft:air'
    },
    // 手铳兵
    "handgonne_man": {
        mainHand: /(pistol|blunderbuss|stick|bone|blaze_rod)$/,
        offHand: /^minecraft:air$/,
        defaultMainHand: 'musketmod:pistol',
        defaultOffHand: 'minecraft:air'
    },
    // 火枪手
    "matchlock_man": {
        mainHand: /(musket|stick|bone|blaze_rod)$/,
        offHand: /^minecraft:air$/,
        defaultMainHand: 'musketmod:musket',
        defaultOffHand: 'minecraft:air'
    },
    // 祭司
    "priest": {
        mainHand: /(lantern)$/,
        offHand: /(priest_cane)$/,
        defaultMainHand: 'minecraft:lantern',
        defaultOffHand: 'hundred_years_war:priest_cane_1'
    }
}

// 装备同步工具
global.weaponUtils = {
    // 检查武器是否允许
    isWeaponAllowed: function (soldierTag, itemId, isMainHand) {
        let config = WEAPON_CONFIG_BY_TAG[soldierTag]
        let pattern = isMainHand ? config.mainHand : config.offHand
        let result = pattern.test(itemId)
        return result
    },

    // 获取士兵类型的默认武器配置
    getDefaultWeapon: function (soldierTag, isMainHand) {
        let config = WEAPON_CONFIG_BY_TAG[soldierTag]
        if (!config) return 'minecraft:air'

        return isMainHand ? config.defaultMainHand : config.defaultOffHand
    },

    // 标准化附魔配置为数组格式
    normalizeEnchantments: function(enchantmentConfig) {
        if (!enchantmentConfig) return []
        
        if (Array.isArray(enchantmentConfig)) {
            return enchantmentConfig.map(ench => {
                if (typeof ench === 'string') {
                    return {id: ench, lvl: 1}
                }
                return ench
            })
        } else if (typeof enchantmentConfig === 'string') {
            return [{id: enchantmentConfig, lvl: 1}]
        } else if (typeof enchantmentConfig === 'object') {
            return [enchantmentConfig]
        }
        
        return []
    },

    // 复制对象（兼容Rhino环境）
    copyObject: function(obj) {
        if (!obj) return {}
        let newObj = {}
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                newObj[key] = obj[key]
            }
        }
        return newObj
    },

    // 为物品添加附魔（支持多种附魔）
    applyEnchantments: function (itemStack, enchantmentConfig, defaultLevel) {
        if (!itemStack || itemStack.id === 'minecraft:air') return itemStack

        // 标准化附魔配置
        let enchantments = this.normalizeEnchantments(enchantmentConfig)
        
        if (enchantments.length === 0) return itemStack

        try {
            // 获取当前物品的附魔
            let currentEnchantments = itemStack.enchantments || {}
            let newEnchantments = this.copyObject(currentEnchantments)
            
            // 添加或更新附魔
            for (let i = 0; i < enchantments.length; i++) {
                let ench = enchantments[i]
                if (ench.id) {
                    newEnchantments[ench.id] = ench.lvl || defaultLevel || 1
                }
            }
            
            // 应用新的附魔集合 - 逐个应用
            let resultItem = itemStack
            for (let enchId in newEnchantments) {
                if (newEnchantments.hasOwnProperty(enchId)) {
                    resultItem = resultItem.enchant(enchId, newEnchantments[enchId])
                }
            }
            
            return resultItem
        } catch (e) {
            console.error(`Failed to apply enchantments to item ${itemStack.id}: ${e}`)
            return itemStack
        }
    },

    // 从NBT创建物品堆栈（完整复制所有NBT数据）
    createItemFromNbt: function (itemNbt) {
        if (!itemNbt || !itemNbt.id || itemNbt.id === 'minecraft:air') {
            return Item.of('minecraft:air')
        }

        try {
            // 使用KubeJS的Item.of方法直接创建带有完整NBT的物品
            let itemStack
            if (itemNbt.tag) {
                // 如果有NBT标签，创建完整的物品
                itemStack = Item.of(itemNbt.id, itemNbt.Count || 1, itemNbt.tag)
            } else {
                // 如果没有NBT标签，只创建基础物品
                itemStack = Item.of(itemNbt.id, itemNbt.Count || 1)
            }
            
            return itemStack
        } catch (e) {
            console.error(`Failed to create item from NBT for ${itemNbt.id}: ${e}`)
            return Item.of(itemNbt.id, itemNbt.Count || 1)
        }
    },

    // 同步武器和装备
    syncEquipment: function (mark, soldier) {
        // 获取士兵类型tag
        let soldierTag = soldier.persistentData.getString('type')
        let recruitConfig = null

        // 查找对应的招募配置
        for (let key in RECRUIT_CONFIGS) {
            if (RECRUIT_CONFIGS[key].type === soldierTag) {
                recruitConfig = RECRUIT_CONFIGS[key]
                break
            }
        }

        // 同步盔甲 - 使用KubeJS方法
        let armorItems = mark.nbt.ArmorItems || [{}, {}, {}, {}]

        // 处理每个盔甲槽位
        for (let i = 0; i < 4; i++) {
            let armorItemNbt = armorItems[i] || {}
            let armorItemId = armorItemNbt.id || 'minecraft:air'

            if (armorItemId !== 'minecraft:air') {
                let armorItem = this.createItemFromNbt(armorItemNbt)

                // 应用盔甲附魔
                if (recruitConfig) {
                    if (i === 3 && recruitConfig.helmetEnchantments) { // 头盔
                        armorItem = this.applyEnchantments(
                            armorItem,
                            recruitConfig.helmetEnchantments,
                            recruitConfig.helmetEnchantmentsLV || 1
                        )
                    } else if (i === 2 && recruitConfig.chestplateEnchantments) { // 胸甲
                        armorItem = this.applyEnchantments(
                            armorItem,
                            recruitConfig.chestplateEnchantments,
                            recruitConfig.chestplateEnchantmentsLV || 1
                        )
                    } else if (i === 1 && recruitConfig.leggingsEnchantments) { // 护腿
                        armorItem = this.applyEnchantments(
                            armorItem,
                            recruitConfig.leggingsEnchantments,
                            recruitConfig.leggingsEnchantmentsLV || 1
                        )
                    } else if (i === 0 && recruitConfig.bootsEnchantments) { // 靴子
                        armorItem = this.applyEnchantments(
                            armorItem,
                            recruitConfig.bootsEnchantments,
                            recruitConfig.bootsEnchantmentsLV || 1
                        )
                    }
                }

                // 设置盔甲
                if (i === 0) soldier.setFeetArmorItem(armorItem)
                else if (i === 1) soldier.setLegsArmorItem(armorItem)
                else if (i === 2) soldier.setChestArmorItem(armorItem)
                else if (i === 3) soldier.setHeadArmorItem(armorItem)
            } else {
                // 清空盔甲槽位
                if (i === 0) soldier.setFeetArmorItem(Item.of('minecraft:air'))
                else if (i === 1) soldier.setLegsArmorItem(Item.of('minecraft:air'))
                else if (i === 2) soldier.setChestArmorItem(Item.of('minecraft:air'))
                else if (i === 3) soldier.setHeadArmorItem(Item.of('minecraft:air'))
            }
        }

        // 获取盔甲架手中的物品
        let markHandItems = mark.nbt.HandItems || [{}, {}]
        let mainHandItemNbt = markHandItems[0] || {}
        let offHandItemNbt = markHandItems[1] || {}

        let mainHandId = mainHandItemNbt.id || 'minecraft:air'
        let offHandId = offHandItemNbt.id || 'minecraft:air'

        // 分别处理主手和副手物品
        // 主手物品
        let mainHandItem
        if (this.isWeaponAllowed(soldierTag, mainHandId, true)) {
            mainHandItem = this.createItemFromNbt(mainHandItemNbt)

            // 应用主手武器附魔
            if (recruitConfig && recruitConfig.weaponEnchantments) {
                mainHandItem = this.applyEnchantments(
                    mainHandItem,
                    recruitConfig.weaponEnchantments,
                    recruitConfig.weaponEnchantmentsLV || 1
                )
            }
        } else {
            // 使用默认主手武器
            let defaultMainHand = this.getDefaultWeapon(soldierTag, true)
            mainHandItem = Item.of(defaultMainHand)

            // 应用默认主手武器附魔
            if (recruitConfig && recruitConfig.weaponEnchantments) {
                mainHandItem = this.applyEnchantments(
                    mainHandItem,
                    recruitConfig.weaponEnchantments,
                    recruitConfig.weaponEnchantmentsLV || 1
                )
            }
        }

        // 设置主手物品
        soldier.setMainHandItem(mainHandItem)

        // 副手物品
        let offHandItem
        if (this.isWeaponAllowed(soldierTag, offHandId, false)) {
            offHandItem = this.createItemFromNbt(offHandItemNbt)

            // 应用副手武器附魔
            if (recruitConfig && recruitConfig.weaponOffhandEnchantments) {
                offHandItem = this.applyEnchantments(
                    offHandItem,
                    recruitConfig.weaponOffhandEnchantments,
                    recruitConfig.weaponOffhandEnchantmentsLV || 1
                )
            }
        } else {
            // 使用默认副手武器
            let defaultOffHand = this.getDefaultWeapon(soldierTag, false)
            offHandItem = Item.of(defaultOffHand)

            // 应用默认副手武器附魔
            if (recruitConfig && recruitConfig.weaponOffhandEnchantments) {
                offHandItem = this.applyEnchantments(
                    offHandItem,
                    recruitConfig.weaponOffhandEnchantments,
                    recruitConfig.weaponOffhandEnchantmentsLV || 1
                )
            }
        }

        // 设置副手物品
        soldier.setOffHandItem(offHandItem)
    }
}