// priority: 99999

// 集结士兵（处理uuid列表）
global.AssembleSoldiers = function (player, soldierUUIDs, totalScale) {
    let centerX = player.x
    let centerY = player.y
    let centerZ = player.z
    let dimension = player.level.dimension.path

    let summonTasks = []
    let processedCount = 0
    let fallbackCount = 0 // 记录使用备选方法的士兵数量

    // 计算基于队伍规模的最大延迟
    let maxDelay = calculateMaxDelay(totalScale)

    // 为每个士兵创建独立的召唤任务
    soldierUUIDs.forEach(soldierUUID => {
        processSoldierSummon(player, soldierUUID, centerX, centerY, centerZ, dimension, maxDelay, (summonInfo) => {
            processedCount++

            if (summonInfo) {
                if (summonInfo.useFallback) {
                    fallbackCount++ // 记录使用备选方法的数量
                }
                summonTasks.push(summonInfo)
            }

            // 所有士兵处理完成后开始召唤
            if (processedCount === soldierUUIDs.length) {
                executeSummonTasks(player, summonTasks)
            }
        })
    })
}

// 传送士兵到玩家（单个uuid）
global.TPSoldier = function (player, soldierUUID) {
    let centerX = player.x
    let centerY = player.y
    let centerZ = player.z
    let dimension = player.level.dimension.path
    // 使用全范围随机方向射线搜索
    let safePos = findSafePositionRandomDirection(player.level, centerX, centerY, centerZ, TPSoldierConfig.minRadius, TPSoldierConfig.maxRadius)
    if (!safePos) {
        safePos = { x: centerX, y: centerY, z: centerZ }
    }
    // 获取士兵实体并传送
    global.GetGlobalEntity(soldierUUID, player, (soldier, usedForceLoad) => {
        if (!soldier || soldier.isRemoved()) return
        // 传送士兵及其坐骑
        teleportEntityWithMount(soldier, dimension, safePos.x + 0.5, safePos.y, safePos.z + 0.5, 0, 0)
        // 播放传送特效和音效
        playSummonEffects(soldier.level, safePos.x + 0.5, safePos.y, safePos.z + 0.5)
        // 设置跟随行为
        setSoldierFollowBehavior(soldier, player)
    })
}

// 传送实体及其坐骑
function teleportEntityWithMount(entity, dimension, x, y, z, yaw, pitch) {
    // 检查实体是否有坐骑
    let mount = entity.getVehicle()
    if (mount && !mount.isRemoved()) {
        // 先传送坐骑
        mount.teleportTo(dimension, x, y, z, yaw, pitch)
        // 短暂延迟后传送骑手，确保坐骑先到达
        entity.level.server.scheduleInTicks(2, () => {
            entity.teleportTo(dimension, x, y, z, yaw, pitch)
        })
    } else {
        // 没有坐骑，直接传送
        entity.teleportTo(dimension, x, y, z, yaw, pitch)
    }
}

// 播放召唤特效和音效
function playSummonEffects(level, x, y, z) {
    // 播放音效 - 使用传送门音效
    level.playSound(null, x, y, z, "minecraft:entity.enderman.teleport", 'hostile', 1.0, 0.8)
    // 添加一些火花粒子效果
    level.spawnParticles("minecraft:witch", false, x, y + 0.5, z, 0.3, 0.5, 0.3, 30, 0.01)
}

// 全范围随机方向射线搜索
function findSafePositionRandomDirection(level, centerX, centerY, centerZ, minDistance, maxDistance) {
    for (let attempts = 0; attempts < 15; attempts++) {
        // 随机角度
        let angle = Math.random() * KMath.PI * 2
        let directionX = Math.cos(angle)
        let directionZ = Math.sin(angle)
        // 从最大距离开始向玩家方向步进搜索
        let position = findPositionAlongRayFromFar(level, centerX, centerY, centerZ, directionX, directionZ, minDistance, maxDistance)
        if (position) return position
    }
    return null
}

// 固定方向（带小范围随机）射线搜索
function findSafePositionAlongDirection(level, centerX, centerY, centerZ, baseDirectionX, baseDirectionZ, targetDistance) {
    // 在基础方向上加入小范围随机偏移
    let randomAngle = (Math.random() - 0.5) * 0.3
    let cos = Math.cos(randomAngle)
    let sin = Math.sin(randomAngle)
    let directionX = baseDirectionX * cos - baseDirectionZ * sin
    let directionZ = baseDirectionX * sin + baseDirectionZ * cos
    // 从最大距离开始向玩家方向步进搜索
    let minDistance = Math.max(1, targetDistance - 5)
    let maxDistance = targetDistance + 5
    return findPositionAlongRayFromFar(level, centerX, centerY, centerZ, directionX, directionZ, minDistance, maxDistance)
}

// 从远到近沿射线搜索位置
function findPositionAlongRayFromFar(level, startX, startY, startZ, dirX, dirZ, minDistance, maxDistance) {
    // 优先检查最大距离，然后逐步向玩家靠近
    for (let dist = maxDistance; dist >= minDistance; dist -= 2) {
        let testX = startX + dirX * dist
        let testZ = startZ + dirZ * dist
        let position = raycastToGround(level, testX, startY, testZ)
        if (position && !isRayObstructed(level, startX, startY + 1, startZ, position.x, position.y + 1, position.z)) {
            return position
        }
    }
    // 如果从远到近没找到，尝试从近到远作为备用
    for (let dist = minDistance; dist <= maxDistance; dist += 2) {
        let testX = startX + dirX * dist
        let testZ = startZ + dirZ * dist
        let position = raycastToGround(level, testX, startY, testZ)
        if (position) {
            return position
        }
    }
    return null
}

// 检查射线是否被障碍物阻挡
function isRayObstructed(level, startX, startY, startZ, endX, endY, endZ) {
    let dx = endX - startX
    let dy = endY - startY
    let dz = endZ - startZ
    let distance = Math.sqrt(dx * dx + dy * dy + dz * dz)
    if (distance === 0) return false
    let steps = Math.ceil(distance)
    for (let i = 1; i <= steps; i++) {
        let t = i / steps
        let checkX = startX + dx * t
        let checkY = startY + dy * t
        let checkZ = startZ + dz * t
        // 如果路径上有实体方块阻挡，则认为被 obstructed
        if (!global.isPassablePosition(level, checkX, checkY, checkZ)) {
            return true
        }
    }
    return false
}

// 计算基于队伍规模的最大延迟
function calculateMaxDelay(totalScale) {
    let baseMaxDelay = AssembleSoldiersConfig.baseMaxDelay || 1
    let maxDelayScale = AssembleSoldiersConfig.maxDelayScale || 0.1
    return baseMaxDelay + (totalScale * maxDelayScale)
}

// 处理单个士兵的召唤信息
function processSoldierSummon(player, soldierUUID, centerX, centerY, centerZ, dimension, maxDelay, callback) {
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    let soldierData = pSoldierData.getCompound(soldierUUID)
    // 使用GetGlobalEntity方法获取实体
    global.GetGlobalEntity(soldierUUID, player, (soldier, usedForceLoad) => {
        processSoldierWithEntity(soldier, soldierUUID, player, centerX, centerY, centerZ, dimension, maxDelay, soldierData, callback)
    })
}

// 使用实体处理士兵召唤
function processSoldierWithEntity(soldier, soldierUUID, player, centerX, centerY, centerZ, dimension, maxDelay, soldierData, callback) {
    let soldierX, soldierZ, hasRecordedPos = false
    if (soldier && !soldier.isRemoved()) {
        // 使用已加载实体的实际位置
        soldierX = soldier.x
        soldierZ = soldier.z
    } else {
        // 使用TPPos记录的位置
        soldierX = centerX
        soldierZ = centerZ
        if (soldierData.contains("TPPosX") && soldierData.contains("TPPosZ")) {
            soldierX = soldierData.getInt("TPPosX")
            soldierZ = soldierData.getInt("TPPosZ")
            hasRecordedPos = true
        }
    }
    let distance = Math.sqrt(Math.pow(soldierX - centerX, 2) + Math.pow(soldierZ - centerZ, 2))
    // 检查士兵是否已经在召唤距离内
    if (distance <= AssembleSoldiersConfig.maxSummonDistance) {
        if (soldier && !soldier.isRemoved()) {
            if (soldier && !soldier.isRemoved()) {
                let randomTick = Math.random() * 60
                player.server.scheduleInTicks(randomTick, () => {
                    global.TPSoldier(player, soldierUUID)
                    setSoldierFollowBehavior(soldier, player)
                })
            }
            callback(null)
        } else {
            callback({
                uuid: soldierUUID,
                position: null,
                delay: 0,
                distance: distance,
                hasRecordedPos: hasRecordedPos,
                recordedX: soldierX,
                recordedZ: soldierZ,
                recordedDim: soldierData.getString("TPPosDim") || dimension,
                useEntity: false,
                alreadyNearby: true
            })
        }
        return
    }

    // 计算方向向量
    let directionX = 0, directionZ = 0
    if (distance > 0.1) {
        directionX = (soldierX - centerX) / distance
        directionZ = (soldierZ - centerZ) / distance
    } else {
        let angle = Math.random() * KMath.PI * 2
        directionX = Math.cos(angle)
        directionZ = Math.sin(angle)
    }

    // 使用固定方向射线搜索召唤位置
    let summonPos = findSafePositionAlongDirection(player.level, centerX, centerY, centerZ, directionX, directionZ, AssembleSoldiersConfig.preferredDistance)

    if (!summonPos) {
        // 使用快速传送函数作为备用方案，但也要计算延迟
        let delay = calculateSummonDelay(distance, maxDelay)
        callback({
            uuid: soldierUUID,
            position: null,
            delay: delay,
            distance: distance,
            hasRecordedPos: hasRecordedPos,
            recordedX: soldierX,
            recordedZ: soldierZ,
            recordedDim: soldierData.getString("TPPosDim") || dimension,
            useEntity: false,
            useFallback: true, // 标记使用备选方法
            alreadyNearby: false
        })
        return
    }

    let delay = calculateSummonDelay(distance, maxDelay)
    callback({
        uuid: soldierUUID,
        entity: soldier,
        position: summonPos,
        delay: delay,
        distance: distance,
        useEntity: !!soldier,
        hasRecordedPos: hasRecordedPos,
        recordedX: soldierX,
        recordedZ: soldierZ,
        recordedDim: soldierData.getString("TPPosDim") || dimension,
        useFallback: false // 正常方法
    })
}

// 设置士兵跟随行为
function setSoldierFollowBehavior(soldier, player) {
    let commandData = soldier.persistentData.getCompound("command")
    commandData.putInt("Behavior", 2)
    soldier.persistentData.put("command", commandData)
    let sUuid = soldier.uuid.toString()
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    let sUuidData = pSoldierData.getCompound(sUuid)
    sUuidData.putInt("Behavior", 2)
    pSoldierData.put(sUuid, sUuidData)
    pData.put("soldier", pSoldierData)

    global.BehaviorTranslation(soldier, player)
}

// 执行所有召唤任务
function executeSummonTasks(player, summonTasks) {
    if (summonTasks.length === 0) {
        return
    }
    // 计算最小和最大延迟的传统写法
    let minDelay = Number.MAX_VALUE
    let maxDelay = 0
    for (let i = 0; i < summonTasks.length; i++) {
        let delay = summonTasks[i].delay
        if (delay < minDelay) minDelay = delay
        if (delay > maxDelay) maxDelay = delay
    }
    player.tell(`§a集结令已下达`)
    player.tell(`最近的士兵将在§e${minDelay.toFixed(1)}§a秒后抵达`)
    player.tell(`最远的士兵将在§e${maxDelay.toFixed(1)}§a秒后抵达`)
    let totalSummoned = 0
    // 按照延迟时间排序，确保延迟短的先执行
    summonTasks.sort((a, b) => a.delay - b.delay)
    // 添加最小延迟间隔
    let minTickInterval = 5
    let lastScheduledTick = 0
    summonTasks.forEach((task, index) => {
        let baseDelayTicks = Math.max(10, Math.floor(task.delay * 20))
        // 计算实际延迟ticks
        let actualDelayTicks = Math.max(baseDelayTicks, lastScheduledTick + minTickInterval)
        player.server.scheduleInTicks(actualDelayTicks, () => {
            summonSingleSoldier(player, task, () => {
                totalSummoned++
                if (totalSummoned === summonTasks.length) {
                    player.tell(`§a远征军已完成集结！`)
                }
            })
        })
        // 更新最后调度的tick时间
        lastScheduledTick = actualDelayTicks
    })
}

// 单个士兵召唤函数
function summonSingleSoldier(player, task, callback) {
    if (task.alreadyNearby) {
        global.GetGlobalEntity(task.uuid, player, (soldier, usedForceLoad) => {
            if (soldier && !soldier.isRemoved()) {
                setSoldierFollowBehavior(soldier, player)
            }
            callback()
        })
        return
    }

    // 如果使用备选方法
    if (task.useFallback) {
        player.server.scheduleInTicks(1, () => {
            global.TPSoldier(player, task.uuid)
            callback()
        })
        return
    }
    let pos = task.position
    let dimension = player.level.dimension.path
    if (task.useEntity && task.entity && !task.entity.isRemoved()) {
        summonEntity(player, task.entity, pos, dimension)
        callback()
    } else {
        global.GetGlobalEntity(task.uuid, player, (soldier, usedForceLoad) => {
            if (soldier && !soldier.isRemoved()) {
                summonEntity(player, soldier, pos, dimension)
            }
            callback()
        })
    }
}

// 实际召唤实体
function summonEntity(player, soldier, pos, dimension) {
    // 使用新的传送函数，支持连坐骑一起传送
    teleportEntityWithMount(soldier, dimension, pos.x + 0.5, pos.y, pos.z + 0.5, 0, 0)
    // 播放传送特效和音效
    playSummonEffects(soldier.level, pos.x + 0.5, pos.y, pos.z + 0.5)
    setSoldierFollowBehavior(soldier, player)
}

// 计算召唤延迟
function calculateSummonDelay(distance, maxDelay) {
    let delay = distance * AssembleSoldiersConfig.baseDelayPerBlock
    delay = Math.max(delay, AssembleSoldiersConfig.minDelay)
    delay = Math.min(delay, maxDelay)
    return delay
}

// 垂直射线搜索地面
function raycastToGround(level, x, startY, z) {
    let searchStartY = Math.min(startY + 10, level.getMaxBuildHeight() - 5)
    let searchEndY = Math.max(level.getMinBuildHeight() + 1, startY - 10)
    for (let y = searchStartY; y >= searchEndY; y--) {
        if (global.isValidPosition(level, x, y, z, true)) {
            return { x: x, y: y, z: z }
        }
    }
    return null
}