// priority: 9999

// 冷却时间配置 (30分钟)
let SAVE_COOLDOWN = 30 * 60 * 1000; // 毫秒
let SUMMON_COOLDOWN = 30 * 60 * 1000;
// 士兵ID与卷轴ID的映射关系
let SOLDIER_TO_SCROLL = {
    "hundred_years_war:militia": "hundred_years_war:scroll_militia",
    "hundred_years_war:spear_man": "hundred_years_war:scroll_spear_man",
    "hundred_years_war:warrior": "hundred_years_war:scroll_warrior",
    "hundred_years_war:shieldman": "hundred_years_war:scroll_shieldman",
    "hundred_years_war:archer": "hundred_years_war:scroll_archer",
    "hundred_years_war:crossbowman": "hundred_years_war:scroll_crossbowman",
    "hundred_years_war:handgonne_man": "hundred_years_war:scroll_handgonne_man",
    "hundred_years_war:matchlock_man": "hundred_years_war:scroll_matchlock_man"
}
// 允许保存的士兵类型列表
let ALLOWED_SOLDIER_TYPES = [
    "hundred_years_war:militia",
    "hundred_years_war:spear_man",
    "hundred_years_war:warrior",
    "hundred_years_war:shieldman",
    "hundred_years_war:archer",
    "hundred_years_war:crossbowman",
    "hundred_years_war:handgonne_man",
    "hundred_years_war:matchlock_man"
]
// 位置检查函数
function isValidPosition(level, x, y, z, requireGround) {
    let blockHere = level.getBlock(x, y, z)
    let blockBelow = level.getBlock(x, y - 1, z)
    let blockAbove = level.getBlock(x, y + 1, z)
    let isAirBlock = function (id) {
        return [
            "minecraft:air",
            "minecraft:cave_air",
            "minecraft:void_air"
        ].includes(id)
    }
    let isUnsafeBelow = function (id) {
        return [
            "minecraft:lava",
            "minecraft:flowing_lava",
            "minecraft:cobweb",
            "minecraft:pointed_dripstone"
        ].includes(id)
    }
    if (requireGround) {
        return isAirBlock(blockHere.id) &&
            isAirBlock(blockAbove.id) &&
            !isAirBlock(blockBelow.id) &&
            !isUnsafeBelow(blockBelow.id);
    }
    return isAirBlock(blockHere.id) && isAirBlock(blockAbove.id)
}
// 查找安全位置函数
function findSafePosition(player, radius, minRadius, attempts) {
    radius = radius || 20
    minRadius = minRadius || 8
    attempts = attempts || 100
    let centerX = player.x
    let centerY = player.y
    let centerZ = player.z
    let level = player.level
    for (let i = 0; i < attempts; i++) {
        let offsetX, offsetZ
        do {
            offsetX = (Math.random() * 2 - 1) * radius
            offsetZ = (Math.random() * 2 - 1) * radius
        } while (Math.abs(offsetX) < minRadius && Math.abs(offsetZ) < minRadius);
        let x = centerX + offsetX
        let z = centerZ + offsetZ
        let foundY = null
        // 向下搜索
        for (let dy = 0; dy >= -5; dy--) {
            let testY = Math.floor(centerY) + dy
            if (isValidPosition(level, x, testY, z, true)) {
                foundY = testY
                break
            }
        }
        // 向上搜索
        if (foundY === null) {
            for (let dy = 1; dy <= 5; dy++) {
                let testY = Math.floor(centerY) + dy
                if (isValidPosition(level, x, testY, z, true)) {
                    foundY = testY
                    break
                }
            }
        }
        if (foundY !== null) {
            return { x: x, y: foundY, z: z }
        }
    }
    return null
}
// 主事件处理
ItemEvents.rightClicked("minecraft:stick", event => {
    let player = event.player
    let item = event.item
    // 检查是否为军团之杖
    if (item.hoverName.contains('军团之杖')) {

        if (player.shiftKeyDown) {
            saveSoldiers(event, player)
        } else {
            summonSoldiers(event, player)
        }
    }
})
// 保存士兵功能
function saveSoldiers(event, player) {
    let currentTime = Date.now()
    let pData = player.persistentData
    // 冷却检查
    if (pData.contains('last_save_legion_time')) {
        let lastUsed = pData.getLong('last_save_legion_time')
        if (currentTime - lastUsed < SAVE_COOLDOWN) {
            let remaining = Math.ceil((SAVE_COOLDOWN - (currentTime - lastUsed)) / 1000 / 60)
            player.tell('§c保存功能冷却中，剩余§e' + remaining + '§c分钟')
            return
        }
    }
    // 检查物品栏中是否已有军团之盒
    let hasLegionBox = false
    for (let i = 0; i < player.inventory.getContainerSize(); i++) {
        let stack = player.inventory.getItem(i)
        if (!stack.isEmpty() && stack.hoverName.contains('军团之盒')) {
            hasLegionBox = true
            break
        }
    }
    if (hasLegionBox) {
        player.tell('§c请先移除物品栏中的军团之盒！')
        return
    }
    // 收集符合条件的士兵
    let soldiers = []

    // 遍历玩家数据库中的所有士兵
    let pSoldierData = pData.getCompound("soldier")
    pSoldierData.getAllKeys().forEach(soldierUuid => {
        let soldierData = pSoldierData.getCompound(soldierUuid)
        let legion = pData.legion
        // 检查士兵是否有Legion数据且在当前队伍中
        if (soldierData.contains("Legion")) {
            let legionCompound = soldierData.getCompound("Legion")
            if (legionCompound.getBoolean(`Legion_${legion}`)) {
                // 尝试获取士兵实体
                let soldier = player.level.getEntity(soldierUuid)
                if (!soldier) return
                // 检查士兵与玩家的距离
                if (soldier.distanceToEntity(player) > 10) return
                // 设置行为为跟随模式
                if (ALLOWED_SOLDIER_TYPES.includes(soldier.type)) { soldiers.push(soldier) }
            }
        }
    })
    if (soldiers.length === 0) {
        player.tell('§c周围没有可保存的远征军士兵！')
        return
    }
    // 创建军团之盒 (潜影盒)
    let shulkerBox = Item.of('minecraft:shulker_box', {
        display: { Name: '{"text":"军团之盒"}' },
        BlockEntityTag: {
            Items: []
        }
    })
    // 添加士兵卷轴到潜影盒
    let count = 0
    for (let i = 0; i < Math.min(soldiers.length, 27); i++) {
        let soldier = soldiers[i]
        let scrollId = SOLDIER_TO_SCROLL[soldier.type]
        if (scrollId) {
            // 创建士兵卷轴
            let scrollItem = Item.of(scrollId)
            // 添加士兵NBT到卷轴-仅保留有效信息信息
            scrollItem.nbt = {
                EntityData: {
                    ArmorItems: soldier.nbt.ArmorItems,
                    AttackDamage: soldier.nbt.AttackDamage,
                    Attributes: soldier.nbt.Attributes,
                    CustomName: soldier.nbt.CustomName,
                    ExperiencePoints: soldier.nbt.ExperiencePoints,
                    HandItems: soldier.nbt.HandItems,
                    Health: soldier.nbt.Health,
                    KubeJSPersistentData: soldier.nbt.KubeJSPersistentData,
                    Level: soldier.nbt.Level,
                    MaxHealth: soldier.nbt.MaxHealth,
                    OwnerUUID: soldier.nbt.OwnerUUID,
                    Skin: soldier.nbt.Skin,
                    Tags: soldier.nbt.Tags,
                    UUID: soldier.nbt.UUID,
                },
                LegionStaffData: {
                    SoldierType: soldier.type
                }
            }
            // 添加到潜影盒
            shulkerBox.nbt.BlockEntityTag.Items.push({
                Slot: i,
                Count: 1,
                id: scrollId,
                tag: scrollItem.nbt
            })
            count++
        }
    }
    // 给予玩家军团之盒
    player.give(shulkerBox);
    player.tell('§a成功保存§e' + count + '§a名士兵到军团之盒！');
    // 设置冷却时间
    pData.putLong('last_save_legion_time', currentTime);
}
// 召唤士兵功能
function summonSoldiers(event, player) {
    let currentTime = Date.now()
    let pData = player.persistentData
    let pName = player.name.string
    let team = player.team.name
    // 冷却检查
    if (pData.contains('last_summon_legion_time')) {
        let lastUsed = pData.getLong('last_summon_legion_time')
        if (currentTime - lastUsed < SUMMON_COOLDOWN) {
            let remaining = Math.ceil((SUMMON_COOLDOWN - (currentTime - lastUsed)) / 1000 / 60)
            player.tell('§c召唤功能冷却中，剩余§e' + remaining + '§c分钟')
            return
        }
    }
    // 查找军团之盒
    let shulkerBoxItem = null
    let slotFound = -1
    for (let i = 0; i < player.inventory.getContainerSize(); i++) {
        let stack = player.inventory.getItem(i)
        if (!stack.isEmpty() && stack.hoverName.contains('军团之盒')) {
            shulkerBoxItem = stack
            slotFound = i
            break
        }
    }
    if (!shulkerBoxItem) {
        player.tell('§c请先获取军团之盒！')
        return
    }
    // 检查UUID是否已存在
    let uuids = []
    let scrolls = []
    if (shulkerBoxItem.nbt && shulkerBoxItem.nbt.BlockEntityTag && shulkerBoxItem.nbt.BlockEntityTag.Items) {
        for (let item of shulkerBoxItem.nbt.BlockEntityTag.Items) {
            if (item.tag && item.tag.EntityData && item.tag.EntityData.UUID) {
                let uuid = item.tag.EntityData.UUID
                // 检查世界中是否已存在相同UUID的实体
                let entityExists = false
                event.level.entities.forEach(entity => {
                    if (entity.nbt && entity.nbt.UUID &&
                        entity.nbt.UUID[0] === uuid[0] &&
                        entity.nbt.UUID[1] === uuid[1] &&
                        entity.nbt.UUID[2] === uuid[2] &&
                        entity.nbt.UUID[3] === uuid[3]) {
                        entityExists = true
                    }
                })
                if (entityExists) {
                    player.tell('§c存在相同UUID的生物，召唤取消！')
                    return
                }
                // 从自定义字段读取士兵类型
                let soldierType = item.tag.LegionStaffData?.SoldierType;

                uuids.push(uuid)
                scrolls.push({
                    soldierType: soldierType,
                    entityData: item.tag.EntityData
                })
            }
        }
    }
    if (scrolls.length === 0) {
        player.tell('§c军团之盒中没有士兵卷轴！')
        return
    }
    // 召唤士兵
    let count = 0
    for (let scroll of scrolls) {
        let soldierType = scroll.soldierType
        let entityData = scroll.entityData
        // 检查士兵类型是否有效
        if (!soldierType || !ALLOWED_SOLDIER_TYPES.includes(soldierType)) {
            player.tell('§c无效的士兵类型: ' + soldierType)
            continue
        }
        let pos = findSafePosition(player)
        if (!pos) {
            player.tell('§c没有足够的安全位置召唤士兵！')
            break;
        }
        // 创建士兵实体（直接使用保存的类型）
        let soldier = event.level.createEntity(soldierType)
        if (!soldier) {
            player.tell('§c无法创建士兵实体: ' + soldierType)
            continue
        }
        // 合并NBT数据
        soldier.mergeNbt(entityData)
        // 添加召唤时间限制
        let eData = soldier.persistentData
        let CDdata = eData.getCompound("CoolDownTime")
        CDdata.putInt("OnlineLegion", event.level.time)
        eData.put("CoolDownTime", CDdata)
        // 设置位置
        soldier.setPosition(pos.x + 0.5, pos.y, pos.z + 0.5)
        // 生成实体
        soldier.spawn()
        event.server.runCommandSilent(`hundred_years_war follow ${soldier.uuid} ${pName}`)
        if (soldier.type != "hundred_years_war:priest") {
            event.server.runCommandSilent(`execute as ${soldier.uuid} run team join ${team} @s`)
        }
        count++
    }
    // 删除军团之盒
    player.inventory.setItem(slotFound, Item.of('minecraft:air'))
    player.tell('§a成功召唤§e' + count + '§a名士兵！')
    // 设置冷却时间
    pData.putLong('last_summon_legion_time', currentTime)
}
// 禁用复制的卷轴直接召唤
ItemEvents.rightClicked(event => {
    let item = event.item
    let id = item.id
    if ((
        id === 'hundred_years_war:scroll_militia' ||
        id === 'hundred_years_war:scroll_spear_man' ||
        id === 'hundred_years_war:scroll_warrior' ||
        id === 'hundred_years_war:scroll_shieldman' ||
        id === 'hundred_years_war:scroll_archer' ||
        id === 'hundred_years_war:scroll_crossbowman' ||
        id === 'hundred_years_war:scroll_handgonne_man' ||
        id === 'hundred_years_war:scroll_matchlock_man'
    ) && event.item.nbt.LegionStaffData != null && event.item.nbt.LegionStaffData) {
        event.player.tell("§c远征军召唤卷轴不允许右键使用")
        event.cancel()
    }
})