// priority: 10
// 士兵管理功能 - 手持士兵管理手册左键触发记录

ItemEvents.firstLeftClicked('minecraft:writable_book', event => {
    let player = event.player
    let item = event.item
    // 检查是否为士兵管理书
    if (!item.nbt.getBoolean("roster")) return
    // 检查是否正在处理
    if (global.soldierManagement && global.soldierManagement.isProcessing) {
        player.tell('§e正在处理士兵数据，请稍候...')
        return
    }
    // 初始化处理状态
    global.soldierManagement = {
        isProcessing: true,
        currentProcess: {
            player: player,
            startTime: Date.now(),
            soldiersProcessed: 0,
            soldiersTotal: 0,
            results: {
                found: 0,
                notFound: 0,
                unbound: 0,
                armorStandMissing: 0,
                guards: 0,
                details: []
            }
        }
    }
    player.tell('§a开始全面检查登记士兵...')
    startSoldierManagement()
})

// 开始士兵管理处理
function startSoldierManagement() {
    if (!global.soldierManagement || !global.soldierManagement.currentProcess) return
    let process = global.soldierManagement.currentProcess
    let player = process.player
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    // 获取所有登记的士兵UUID
    let soldierUUIDs = pSoldierData.getAllKeys()
    process.soldiersTotal = soldierUUIDs.length
    if (soldierUUIDs.length === 0) {
        finishSoldierManagement("没有登记的士兵")
        return
    }
    player.tell(`§7找到 ${soldierUUIDs.length} 个登记士兵，开始处理...`)
    // 异步处理每个士兵
    processSoldierQueue(soldierUUIDs, 0)
}

// 递归处理士兵队列
function processSoldierQueue(soldierUUIDs, index) {
    if (!global.soldierManagement || index >= soldierUUIDs.length) {
        finishSoldierManagement("处理完成")
        return
    }
    let soldierUUID = soldierUUIDs[index]
    let process = global.soldierManagement.currentProcess
    let player = process.player
    // 处理单个士兵
    processSingleSoldier(soldierUUID, player, (result) => {
        process.results.details.push(result)
        process.soldiersProcessed++
        // 实时反馈有问题的士兵，跳过正常状态的士兵
        if (result.status !== "正常") {
            let message = `§6${result.name} - §c${result.status}`
            if (result.issues.length > 0) {
                message += `: ${result.issues.join(', ')}`
            }
            player.tell(message)
        }
        // 延迟1tick后处理下一个，避免服务器压力
        player.level.server.scheduleInTicks(1, () => {
            processSoldierQueue(soldierUUIDs, index + 1)
        })
    })
}
// 处理单个士兵
function processSingleSoldier(soldierUUID, player, callback) {
    let process = global.soldierManagement.currentProcess
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    let result = {
        uuid: soldierUUID,
        name: "未知",
        status: "未知",
        issues: []
    }
    // 尝试获取士兵实体
    global.GetGlobalEntity(soldierUUID, player, (soldier, usedForceLoad) => {
        if (!soldier) {
            // 士兵找不到，删除登记
            pSoldierData.remove(soldierUUID)
            pData.put("soldier", pSoldierData)

            result.status = "已删除"
            result.issues.push("无法找到士兵实体")
            process.results.notFound++

            callback(result)
            return
        }
        // 获取士兵名称
        result.name = soldier.name.string
        process.results.found++
        // 检查是否为警卫（特殊处理）
        if (soldier.type.toString().startsWith("guardvillagers")) {
            process.results.guards++
            result.status = "正常"
            callback(result)
            return
        }
        // 获取士兵的home数据
        let sData = soldier.persistentData
        let sSoldierData = sData.getCompound("soldier")
        let homeUUID = sSoldierData.getString("Home")
        if (!homeUUID) {
            // 没有绑定盔甲架
            result.status = "未绑定"
            result.issues.push("士兵没有绑定盔甲架")
            process.results.unbound++
            callback(result)
            return
        }
        // 获取盔甲架的位置信息
        let homeDim = sSoldierData.getString("HomePosDim")
        let homeX = sSoldierData.getInt("HomePosX")
        let homeZ = sSoldierData.getInt("HomePosZ")
        // 尝试查找盔甲架（使用区块加载确保找到）
        findArmorStandByUUIDWithLoading(homeUUID, homeDim, homeX, homeZ, player, (armorStand) => {
            if (!armorStand) {
                // 盔甲架找不到，解除绑定
                sSoldierData.remove("Home")
                sData.put("soldier", sSoldierData)
                result.status = "已解除绑定"
                result.issues.push("绑定的盔甲架不存在")
                process.results.armorStandMissing++
                callback(result)
                return
            }
            // 检查盔甲架与士兵的绑定关系是否匹配
            let mData = armorStand.persistentData
            let armorStandResident = mData.getString("Resident")
            if (armorStandResident !== soldierUUID) {
                // 绑定关系不匹配，解除绑定
                sSoldierData.remove("Home")
                sData.put("soldier", sSoldierData)
                result.status = "绑定不匹配"
                result.issues.push("盔甲架绑定的士兵UUID不匹配")
                process.results.armorStandMissing++
                callback(result)
                return
            }
            // 同步属性和装备
            try {
                // 同步属性
                attributeModifier(armorStand, soldier)
                // 同步装备
                if (global.weaponUtils && global.weaponUtils.syncEquipment) {
                    global.weaponUtils.syncEquipment(armorStand, soldier)
                }
                soldier.setHealth(9999)
                result.status = "正常"
            } catch (e) {
                result.status = "同步失败"
                result.issues.push("属性或装备同步失败: " + e)
            }
            callback(result)
        })
    })
}



// 通过UUID查找盔甲架（使用区块加载）
function findArmorStandByUUIDWithLoading(uuid, dimension, x, z, player, callback) {
    let server = player.server
    let level = server.getLevel(dimension)
    // 使用区块加载确保盔甲架所在区域被加载
    global.ShortLoadChunks(level, x, z, 20) // 加载20tick
    // 延迟一小段时间让区块加载完成
    server.scheduleInTicks(10, () => {
        let armorStand = level.getEntity(uuid)
        callback(armorStand)
    })
}
// 完成士兵管理处理
function finishSoldierManagement(reason) {
    if (!global.soldierManagement || !global.soldierManagement.currentProcess) return
    let process = global.soldierManagement.currentProcess
    let player = process.player
    let duration = Date.now() - process.startTime
    // 生成报告
    let report = generateManagementReport(process.results, duration)
    // 更新士兵管理手册内容
    updateBookWithReport(player, report)
    player.tell(`§a士兵管理完成！耗时: ${duration}ms`)
    player.tell(`§6处理结果已记录在士兵管理手册中`)
    // 重置状态
    global.soldierManagement.isProcessing = false
    global.soldierManagement.currentProcess = null
}
// 生成管理报告
function generateManagementReport(results, duration) {
    let report = `§3§l士兵管理报告§r\n`
    report += `生成时间: ${new Date().toLocaleString()}\n\n`
    report += `§3§l=== 统计摘要 ===§r\n`
    report += `总处理士兵: ${results.found + results.notFound}\n`
    report += `正常士兵: ${results.found}\n`
    report += `已删除士兵: ${results.notFound}\n`
    report += `未绑定士兵: ${results.unbound}\n`
    report += `盔甲架丢失: ${results.armorStandMissing}\n`
    report += `警卫士兵: ${results.guards}\n\n                           \n`
    report += `§3§l=== 详细记录 ===§r\n`
    results.details.forEach(detail => {
        report += `§9§l${detail.name}§r\n`
        report += `状态: ${detail.status}\n`
        if (detail.issues.length > 0) {
            detail.issues.forEach(issue => {
                report += `问题: ${issue}\n`
            })
        }
    })
    return report
}
// 更新士兵管理手册内容
function updateBookWithReport(player, report) {
    let handItem = player.mainHandItem
    if (handItem.id !== 'minecraft:writable_book') {
        player.tell('§c错误：请确保手持士兵管理手册')
        return
    }
    // 分割报告为多页（每页最多256字符）
    let pages = splitReportToPages(report)
    // 创建pages列表标签
    let pagesTag = NBT.listTag()
    pages.forEach(page => {
        pagesTag.add(NBT.stringTag(page))
    })
    // 创建完整的书NBT
    let bookNbt = NBT.compoundTag()
    bookNbt.put("pages", pagesTag)
    bookNbt.putString("title", "士兵管理报告")
    bookNbt.putString("author", player.name.string)
    // 创建新物品
    let newBook = handItem.withNBT(bookNbt)
    // 更新玩家手中的物品
    player.setMainHandItem(newBook)
}

// 分割报告为多页
function splitReportToPages(report) {
    let pages = []
    let lines = report.split('\n')
    let currentPage = ""
    let currentLength = 0
    for (let line of lines) {
        // 每行加上换行符
        let lineWithNewline = line + '\n'
        let lineLength = lineWithNewline.length
        // 如果当前页加上这行会超过限制，就新建一页
        if (currentLength + lineLength > 160) {
            if (currentPage) {
                pages.push(currentPage)
            }
            currentPage = lineWithNewline
            currentLength = lineLength
        } else {
            currentPage += lineWithNewline
            currentLength += lineLength
        }
    }
    // 添加最后一页
    if (currentPage) {
        pages.push(currentPage)
    }
    // 如果页数过多，截断并添加提示
    if (pages.length > 50) {
        pages = pages.slice(0, 50)
        pages[49] += "\n\n... (报告过长，已截断)"
    }
    return pages
}

// 属性修饰器
function attributeModifier(mark, soldier) {
    let mData = mark.persistentData
    let Type = soldier.persistentData.getString("type")
    CAPABILITY.forEach((config) => {
        if (mData.getInt(config.prefix)) {
            // 跳过玩家专属属性
            if (config.target === "player") return
            // 检查是否指定了士兵类型且当前士兵类型不匹配
            if (config.soldierTypes && !config.soldierTypes.includes(Type)) return
            let level = mData.getInt(config.prefix)
            // 使用新的属性加成函数
            let value = config.baseValue * level
            global.AttributeEnhancement(soldier, config.Attribute, config.prefix, value, config.Operation)
        }
    })
}