import PrismRPGUtils from "../utils.mjs"
import PrismRPGRoll from "./roll.mjs"

export default class PrismRPGActor extends Actor {

  static async create(data, options) {

    // Case of compendium global import
    if (data instanceof Array) {
      return super.create(data, options);
    }
    // If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
    if (data.items) {
      let actor = super.create(data, options);
      return actor;
    }

    if (data.type === 'character') {
      const skills = await PrismRPGUtils.loadCompendium("fvtt-prism-rpg.lf-skills")
      data.items = data.items || []
      for (let skill of skills) {
        if (skill.system.category === "layperson") {
          data.items.push(skill.toObject())
        }
      }
    }

    return super.create(data, options);
  }

  async _preCreate(data, options, user) {
    await super._preCreate(data, options, user)

    // Configure prototype token settings
    const prototypeToken = {}
    if (this.type === "character") {
      Object.assign(prototypeToken, {
        sight: { enabled: true },
        actorLink: false
      })
      this.updateSource({ prototypeToken })
    }
  }

  /* *************************************************/
  // This method is no longer needed in D&D 5e style system
  // Weapon proficiency is handled through character class/race features
  getBestWeaponClassSkill(skills, rollType, multiplier = 1.0) {
    // In D&D 5e, we don't need weapon skills with bonuses
    // Just return the first skill (or could be removed entirely)
    return skills[0]
  }

  /* *************************************************/
  async applyDamage(hpLoss) {
    let hp = this.system.hp.value + hpLoss
    if (hp < 0) {
      hp = 0
    }
    this.update({ "system.hp.value": hp })
  }

  /* *************************************************/
  async prepareRoll(rollType, rollKey, rollDice) {
    console.log("Preparing roll", rollType, rollKey, rollDice)
    let rollTarget
    switch (rollType) {
      case "characteristic":
        if (!this.system.characteristics || !this.system.characteristics[rollKey]) {
          ui.notifications.error(`Characteristic ${rollKey} not found`)
          return
        }
        rollTarget = {
          ...foundry.utils.duplicate(this.system.characteristics[rollKey]),
          rollKey: rollKey,
          name: game.i18n.localize(`PRISMRPG.Label.${rollKey}`)
        }
        break
      case "sub-attribute":
        if (!this.system.subAttributes || !this.system.subAttributes[rollKey]) {
          ui.notifications.error(`Sub-attribute ${rollKey} not found`)
          return
        }
        rollTarget = {
          ...foundry.utils.duplicate(this.system.subAttributes[rollKey]),
          rollKey: rollKey,
          name: game.i18n.localize(SYSTEM.SUB_ATTRIBUTES[rollKey].label)
        }
        break
      case "granted":
        rollTarget = {
          name: rollKey,
          formula: foundry.utils.duplicate(this.system.granted[rollKey]),
          rollKey: rollKey
        }
        if (rollTarget.formula === "" || rollTarget.formula === undefined) {
          rollTarget.formula = 0
        }
        break;
      case "challenge":
        rollTarget = foundry.utils.duplicate(this.system.challenges[rollKey])
        rollTarget.rollKey = rollKey
        break
      case "save":
        rollTarget = foundry.utils.duplicate(this.system.saves[rollKey])
        rollTarget.rollKey = rollKey
        rollTarget.rollDice = rollDice
        // Pass the characteristic value for D&D 5e modifier calculation
        rollTarget.characteristicValue = this.system.characteristics[rollKey].value
        // The save bonus is the proficiency modifier (value stored in saves)
        rollTarget.saveBonus = this.system.saves[rollKey].value
        break
      case "spell":
        rollTarget = this.items.find((i) => i.type === "spell" && i.id === rollKey)
        rollTarget.rollKey = rollKey
        break
      case "miracle":
        rollTarget = this.items.find((i) => i.type === "miracle" && i.id === rollKey)
        rollTarget.rollKey = rollKey
        break
      case "skill": {
        rollTarget = this.items.find((i) => i.type === "skill" && i.id === rollKey)
        rollTarget.rollKey = rollKey
        if (rollTarget.system.category === "weapon") {
          ui.notifications.warn(game.i18n.localize("PRISMRPG.Notifications.rollFromWeapon"))
          return
        }
        // Get the two sub-attributes for this skill
        const subAttr1 = rollTarget.system.subAttribute1 || "prowess"
        const subAttr2 = rollTarget.system.subAttribute2 || "initiative"

        // Store both sub-attribute values for the dialog to choose from
        rollTarget.subAttribute1 = subAttr1
        rollTarget.subAttribute2 = subAttr2
        rollTarget.subAttribute1Value = this.system.subAttributes?.[subAttr1]?.value || 0
        rollTarget.subAttribute2Value = this.system.subAttributes?.[subAttr2]?.value || 0
        rollTarget.subAttribute1Label = game.i18n.localize(SYSTEM.SUB_ATTRIBUTES?.[subAttr1]?.label || subAttr1)
        rollTarget.subAttribute2Label = game.i18n.localize(SYSTEM.SUB_ATTRIBUTES?.[subAttr2]?.label || subAttr2)
        rollTarget.proficiencyBonus = rollTarget.system.modifier
        break
      }
      case "spell-attack":
      case "spell-power":
      case "spell-cast":
      case "miracle-attack":
      case "miracle-power":
        rollTarget = this.items.find((i) => (i.type === "miracle" || i.type === "spell") && i.id === rollKey)
        rollTarget.rollKey = rollKey
        break
      case "shield-roll": {
        rollTarget = this.items.find((i) => i.type === "shield" && i.id === rollKey)
        let shieldSkill = this.items.find((i) => i.type === "skill" && i.name.toLowerCase() === rollTarget.name.toLowerCase())
        rollTarget.skill = shieldSkill
        rollTarget.rollKey = rollKey
      }
        break;
      case "weapon-damage-small":
      case "weapon-damage-medium":
      case "weapon-attack": {
        let weapon = this.items.find((i) => i.type === "weapon" && i.id === rollKey)
        if (!weapon) {
          console.error("Weapon not found", weapon, skill)
          ui.notifications.warn(game.i18n.localize("PRISMRPG.Notifications.skillNotFound"))
          return
        }

        // Create a plain object for rollTarget to ensure weapon data is preserved
        rollTarget = {
          weapon: weapon.toObject(),
          rollKey: rollKey,
          combat: foundry.utils.duplicate(this.system.combat),
          strMod: PrismRPGRoll.getAbilityModifier(this.system.characteristics.str.value),
          dexMod: PrismRPGRoll.getAbilityModifier(this.system.characteristics.dex.value)
        }
      }
        break
      default:
        ui.notifications.error(game.i18n.localize("PRISMRPG.Notifications.rollTypeNotFound") + String(rollType))
        return
    }

    // In all cases - verify rollTarget exists
    if (!rollTarget) {
      console.error("Roll target is undefined for rollType:", rollType)
      return
    }

    rollTarget.magicUser = this.system.biodata?.magicUser || false
    rollTarget.actorModifiers = this.system.modifiers ? foundry.utils.duplicate(this.system.modifiers) : {}
    rollTarget.actorLevel = this.system.biodata?.level || 1
    await this.system.roll(rollType, rollTarget)
  }

}
