// 实体 tick 事件处理
ForgeEvents.onEvent("net.minecraftforge.event.entity.living.LivingEvent$LivingTickEvent", event => {
  let entity = event.entity
  let eData = entity.persistentData
  let gameTime = entity.level.time

  // 处理不同实体类型的功能
  processArmorStandRepair(entity, eData)
  processTremorzilla(entity)
  processPriestMinion(entity)
  processSummonedUnit(entity, eData, gameTime)
  processBossCoercion(entity, eData)

  //有时间戳的记录（用于多魔改联动）
  //百年战争士兵脱战恢复
  if (entity.type.toString().startsWith("hundred_years_war") || entity.type.toString().startsWith("guardvillagers")) {
    let eData = entity.persistentData
    if (global.CoolDownTime(entity, "self_recovery", 20, false) && !eData.getBoolean("target")) {
      entity.heal(entity.maxHealth * 0.005)
    }
  }
  if (entity.type === "hundred_years_war:priest") {
    if (global.CoolDownTime(entity, "immune_recovery", 200, false)) {
      // 10秒 = 200 ticks
      entity.mergeNbt({
        ActiveEffects: [{
          Duration: 240,
          Id: 141,
          Amplifier: 0,
          "forge:id": "farm_and_charm:farmers_blessing",
        }],
      })
    }
  }
}
)

// 盔甲架装备修理功能
function processArmorStandRepair(entity, eData) {
  if (entity.type.toString() === "minecraft:armor_stand" && eData.contains("cb_ar")) {
    // 检查CD并执行修理
    if (global.CoolDownTime(entity, "automatic_repair", 1200, false)) {
      // 60秒 = 1200 ticks
      let repairAmounts = { 1: 3, 2: 6, 3: 9, 4: 12, 5: 15 };
      let repairAmount = repairAmounts[eData.getInt("cb_ar")] || 0;

      if (repairAmount > 0) {
        let equipmentSlots = [
          entity.mainHandItem,
          entity.offHandItem,
          entity.headArmorItem,
          entity.chestArmorItem,
          entity.legsArmorItem,
          entity.feetArmorItem,
        ]

        equipmentSlots.forEach((slot) => {
          if (!slot.isEmpty() && slot.isDamageableItem()) {
            let newDamage = Math.max(slot.getDamageValue() - repairAmount, 0);
            slot.setDamageValue(newDamage);
          }
        })
      }
    }
  }
}

// 撼地斯拉成长锁定
function processTremorzilla(entity) {
  if (
    entity.type.toString() === "alexscaves:tremorzilla" &&
    global.tremorzilla !== false
  ) {
    if (global.CoolDownTime(entity, "growth_lock", 1200, false)) {
      // 60秒 = 1200 ticks
      entity.mergeNbt(`{Age:-30000}`)
    }
  }
}

// 侵蚀祭司目标选择
function processPriestMinion(entity) {
  if (
    entity.type.toString() === "hundred_years_war:priest" &&
    entity.tags.contains("snk_minion")
  ) {
    let AABB = entity.boundingBox.inflate(50, 25, 50)
    entity.level.getEntitiesWithin(AABB).forEach((target) => {
      if (
        target.tags.contains("snk_summoner") &&
        target.getMaxHealth() > target.getHealth()
      ) {
        entity.setTarget(target)
        return
      }
    })
  }
}
// 召唤单位持续时间检查（使用游戏时间）
function processSummonedUnit(entity, eData, gameTime) {
  if (eData.getCompound("CoolDownTime").contains("duration")) {
    let spawnTime = eData.getCompound("CoolDownTime").getInt("duration")
    let durationTicks = global.duration * 20

    // 检查游戏时间是否超过持续时间
    if (gameTime - spawnTime >= durationTicks) {
      entity.discard()
    }
  }
  if (eData.getCompound("CoolDownTime").contains("OnlineLegion")) {
    let spawnTime = eData.getCompound("CoolDownTime").getInt("OnlineLegion")
    let durationTicks = global.OnlineLegion * 20

    // 检查游戏时间是否超过持续时间
    if (gameTime - spawnTime >= durationTicks) {
      entity.discard()
    }
  }
}

// BOSS威压系统
function processBossCoercion(entity, eData) {
  if (eData.getInt("coercion")) {
    // 检查CD并执行威压
    if (global.CoolDownTime(entity, "coercion", 200, false)) {
      // 10秒 = 200 ticks
      let coercionLevel = eData.getInt("coercion")
      let AABB = entity.boundingBox.inflate(60, 60, 60)
      let validSoldiers = []

      entity.level.getEntitiesWithin(AABB).forEach(soldier => {
        let sData = soldier.persistentData
        // 检查是否有士兵数据库
        if (sData.getCompound("soldier").contains("Owner") || soldier.isPlayer()) {
          validSoldiers.push(soldier)
        }
      })

      let morale = validSoldiers.length
      let moraleThresholds = { 1: 3, 2: 6, 3: 9 }
      let threshold = moraleThresholds[coercionLevel] || 0

      // 如果士气不足，施加效果
      if (morale < threshold) {
        let effects = getCoercionEffects(coercionLevel)
        validSoldiers.forEach((soldier) => {
          let sUuid = soldier.uuid
          entity.server.runCommandSilent(
            `effect clear ${sUuid} farm_and_charm:farmers_blessing`
          )
          entity.server.runCommandSilent(
            `effect clear ${sUuid} farm_and_charm:grandmas_blessing`
          )
          effects.forEach((effect) => {
            let effectId = effect.id
            entity.server.runCommandSilent(
              `execute as ${sUuid} run effect give @s ${effectId} 12 0`
            )
          })

          if (soldier.isPlayer()) {
            sendCoercionMessage(soldier, coercionLevel, morale, threshold)
          }
        })
      }
    }
  }
}

// 发送威压提示信息
function sendCoercionMessage(player, coercionLevel, currentMorale, requiredMorale) {
  // 避免频繁提示
  if (!global.CoolDownTime(player, "coercion_message", 6000, false)) return
  let messages = {
    1: [
      "一股寒意从脊背升起...你感到不安",
      "周围的空气变得沉重，你的脚步开始迟缓",
      "恐惧悄悄蔓延，你的勇气正在流失",
    ],
    2: [
      "强大的威压让你浑身颤抖，力量正在流失",
      "你感到虚弱无力，仿佛被无形的手扼住喉咙",
      "绝望的情绪在蔓延，你急需同伴的支持",
    ],
    3: [
      "恐怖的威压几乎让你窒息，行动变得无比艰难",
      "你感受到了死亡的凝视，身体不听使唤",
      "这是真正的绝望，只有团结才能带来生机",
    ],
  };

  let levelMessages = messages[coercionLevel]

  let randomValue = Math.random()
  let messageIndex

  if (randomValue <= 0.33) {
    messageIndex = 0
  } else if (randomValue <= 0.66) {
    messageIndex = 1
  } else {
    messageIndex = 2
  }

  let message = levelMessages[messageIndex]

  // 添加士气信息
  message += ` (§c${currentMorale}§f/§a${requiredMorale}§f名战友)`

  // 发送消息
  player.tell(`§6[威压] §f${message}`)
}

// 获取威压效果配置
function getCoercionEffects(level) {
  let effects = {
    1: [
      { id: "minecraft:slowness" }
    ],
    2: [
      { id: "minecraft:slowness" },
      { id: "minecraft:weakness" }
    ],
    3: [
      { id: "minecraft:slowness" },
      { id: "minecraft:mining_fatigue" },
      { id: "minecraft:weakness" },
    ],
  }
  return effects[level] || []
}

//宠物入队
ForgeEvents.onEvent("net.minecraftforge.event.entity.living.AnimalTameEvent", event => {
  let entity = event.entity
  let player = event.getTamer()
  let team = player.team.name
  let eUuid = entity.uuid.toString()
  entity.persistentData.putString("pUuid", player.uuid.toString())
  player.server.runCommandSilent(`execute as ${eUuid} run team join ${team} @s`)
})