/**
 * DataModel pour les acteurs de type "creature" (créature).
 * Étend foundry.abstract.TypeDataModel.
 */
import {
  woundSchema,
  combatStatusSchema,
  equipmentSchema,
  attributeSchema
} from "./_shared.mjs"

export default class VermineCreatureData extends foundry.abstract.TypeDataModel {

  /** @override */
  static LOCALIZATION_PREFIXES = ["VERMINE.creature"]

  /** @override */
  static defineSchema() {
    const fields = foundry.data.fields

    return {
      // Blessures (base)
      minorWound: new fields.SchemaField(woundSchema(1, 5)),
      majorWound: new fields.SchemaField(woundSchema(4, 4)),
      deadlyWound: new fields.SchemaField(woundSchema(8, 2)),

      // Statut de combat (base)
      combatStatus: combatStatusSchema(),

      // Identité
      identity: new fields.SchemaField({
        profile: new fields.StringField({ required: true, nullable: false, initial: "" }),
        origin: new fields.StringField({ required: true, nullable: false, initial: "" }),
        theme: new fields.StringField({ required: true, nullable: false, initial: "" }),
        notes: new fields.HTMLField({ required: true, initial: "" }),
        biography: new fields.HTMLField({ required: true, initial: "" })
      }),

      // Compétences (description libre)
      skills: new fields.StringField({ required: true, nullable: false, initial: "" }),

      // Modes de jeu actifs
      modes: new fields.SchemaField({
        survival: new fields.BooleanField({ required: true, initial: true }),
        nightmare: new fields.BooleanField({ required: true, initial: true }),
        apocalypse: new fields.BooleanField({ required: true, initial: false })
      }),

      // Niveaux de créature (patron, taille, rôle, meute)
      pattern: attributeSchema(1, 1, 4),
      size: attributeSchema(1, 1, 3),
      role: attributeSchema(1, 1, 4),
      pack: attributeSchema(0, 0, 3),

      // Valeurs calculées (dérivées de pattern/size/role/pack)
      computed: new fields.SchemaField({
        attack: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        damage: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        vigor: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        reaction: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        reactionBonus: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        pools: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        gear: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 9 }),
        gearHindrance: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 0 }),
        protection: new fields.NumberField({ required: true, nullable: false, integer: true, initial: 1 })
      }),

      // Équipement
      equipment: equipmentSchema()
    }
  }

  /** @override */
  prepareDerivedData() {
    super.prepareDerivedData()

    // 1. Calculer les valeurs dérivées (attaque, dégâts, vigueur, etc.)
    this._calculateCreatureComputedValues()

    // 2. Calculer les seuils de blessures
    this._calculateCreatureWoundThresholds()

    // 3. Mettre à jour le statut de combat
    this._updateCombatStatus()
  }

  /**
   * Calcule les valeurs dérivées à partir des niveaux de patron, taille, rôle et meute.
   * Utilise les configs CONFIG.VERMINE.creaturePatternLevels, .creatureSizeLevels,
   * .creatureRoleLevels, .creaturePackLevels.
   *
   * Règles :
   * - Attaque = pattern.attack + size.attack + pack.attack + role.reaction
   * - Dégâts  = pattern.damage + size.vigor + pack.damage
   * - Vigueur = size.vigor + pack.damage
   * - Réaction = role.reaction + role.reaction_bonus
   */
  _calculateCreatureComputedValues() {
    const patternLevel = this.pattern?.value || 1
    const sizeLevel = this.size?.value || 1
    const roleLevel = this.role?.value || 1
    const packLevel = this.pack?.value || 0

    const patternConfig = CONFIG.VERMINE.creaturePatternLevels[patternLevel] || {}
    const sizeConfig = CONFIG.VERMINE.creatureSizeLevels[sizeLevel] || {}
    const roleConfig = CONFIG.VERMINE.creatureRoleLevels[roleLevel] || {}
    const packConfig = CONFIG.VERMINE.creaturePackLevels[packLevel] || {}

    // Attaque : patron + taille + meute + réaction du rôle
    this.computed.attack = (patternConfig.attack || 0)
      + (sizeConfig.attack || 0)
      + (packConfig.attack || 0)
      + (roleConfig.reaction || 0)

    // Dégâts : patron + vigueur de taille + meute
    this.computed.damage = (patternConfig.damage || 0)
      + (sizeConfig.vigor || 0)
      + (packConfig.damage || 0)

    // Vigueur : taille + meute
    this.computed.vigor = (sizeConfig.vigor || 0) + (packConfig.damage || 0)

    // Réaction : rôle
    this.computed.reaction = (roleConfig.reaction || 0) + (roleConfig.reaction_bonus || 0)
    this.computed.reactionBonus = roleConfig.reaction_bonus || 0

    // Réserves
    this.computed.pools = roleConfig.pools || 0

    // Équipement et handicap
    this.computed.gear = roleConfig.gear || 9
    this.computed.gearHindrance = roleConfig.gear_hindrance || 0

    // Protection
    this.computed.protection = roleConfig.protection || 1
  }

  /**
   * Calcule les seuils de blessures à partir du patron, de la taille et de la meute.
   * Les seuils sont la somme des valeurs correspondantes des trois sources.
   */
  _calculateCreatureWoundThresholds() {
    const patternLevel = this.pattern?.value || 1
    const sizeLevel = this.size?.value || 1
    const packLevel = this.pack?.value || 0

    const patternConfig = CONFIG.VERMINE.creaturePatternLevels[patternLevel] || {}
    const sizeConfig = CONFIG.VERMINE.creatureSizeLevels[sizeLevel] || {}
    const packConfig = CONFIG.VERMINE.creaturePackLevels[packLevel] || {}

    this.minorWound.threshold = (patternConfig.minorWound || 0)
      + (sizeConfig.minorWound || 0)
      + (packConfig.minorWound || 0)
    this.majorWound.threshold = (patternConfig.majorWound || 0)
      + (sizeConfig.majorWound || 0)
      + (packConfig.majorWound || 0)
    this.deadlyWound.threshold = (patternConfig.deadlyWound || 0)
      + (sizeConfig.deadlyWound || 0)
      + (packConfig.deadlyWound || 0)

    // Max de blessures
    this.minorWound.max = Math.min(5, this.minorWound.threshold + 2)
    this.majorWound.max = Math.min(4, this.majorWound.threshold + 1)
    this.deadlyWound.max = Math.min(2, this.deadlyWound.threshold)
  }

  /**
   * Met à jour le label du statut de combat en fonction de la difficulté.
   */
  _updateCombatStatus() {
    const difficulty = parseInt(this.combatStatus.difficulty) || 9
    let newLabel = "Passif"
    switch (difficulty) {
      case 5: newLabel = "Offensif"; break
      case 7: newLabel = "Actif"; break
      case 9: newLabel = "Passif"; break
    }
    if (this.combatStatus.label !== newLabel) {
      this.combatStatus.label = newLabel
    }
  }
}
