import MyriadSystemActorBase from "./base-actor.mjs";

export default class MyriadSystemNPC extends MyriadSystemActorBase {

  static defineSchema() {
    const fields = foundry.data.fields;
    const requiredInteger = { required: true, nullable: false, integer: true };
    const baseSchema = super.defineSchema();
    
    // Define characteristics schema like in Character
    const characteristicFields = {};
    if (CONFIG.MYRIAD_SYSTEM?.characteristics) {
      for (const [key] of Object.entries(CONFIG.MYRIAD_SYSTEM.characteristics)) {
        characteristicFields[key] = new fields.SchemaField({
          value: new fields.NumberField({ ...requiredInteger, initial: 50, min: 0, max: 100 }),
          max: new fields.NumberField({ ...requiredInteger, initial: 100, min: 0, max: 200 }),
          bonus: new fields.NumberField({ ...requiredInteger, initial: 0 }),
          malus: new fields.NumberField({ ...requiredInteger, initial: 0 })
        });
      }
    }

    // Return the merged schema
    return foundry.utils.mergeObject(baseSchema, {
      // Propriétés spécifiques aux PNJ
      cr: new fields.NumberField({ ...requiredInteger, initial: 1, min: 0 }),
      xp: new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 }),
      isHostile: new fields.BooleanField({ initial: false }),
      racialFeatures: new fields.ArrayField(new fields.StringField()),
      characteristics: new fields.SchemaField(characteristicFields)
    });
  }

  prepareDerivedData() {
    super.prepareDerivedData();
    
    // Calculate XP based on CR
    this.xp = this.cr * this.cr * 100;
    
    // Process characteristics like Character model
    if (this.characteristics) {
      for (let [key, characteristic] of Object.entries(this.characteristics)) {
        // Calculate the modifier using d20 rules.
        characteristic.mod = Math.floor((characteristic.value - 10) / 2);
        // Handle characteristic label localization.
        characteristic.label = game.i18n.localize(CONFIG.MYRIAD_SYSTEM.characteristics?.[key]) ?? key;
        
        // Update max value based on supernaturalTiers
        const tier = this.supernaturalTiers?.[key] || 0;
        characteristic.max = 100 + (tier * 20); // 100 + 20 par palier surhumain
      }
    }
    
    // Calculate health max based on Puissance + bonus
    if (this.characteristics?.puissance && this.health) {
      const puissanceValue = this.characteristics.puissance.value || 0;
      const puissanceBonus = this.characteristics.puissance.bonus || 0;
      const newMaxHealth = puissanceValue + puissanceBonus;
      
      // Update max health if it has changed
      if (this.health.max !== newMaxHealth) {
        this.health.max = newMaxHealth;
        
        // If current health is higher than new max, adjust it
        if (this.health.value > newMaxHealth) {
          this.health.value = newMaxHealth;
        }
      }
    }

    // Action Points for NPCs (same stance logic as characters)
    if (this.parent && this.actionPoints) {
      const inCombat = !!game.combat?.combatants.find(c => c.actor?.id === this.parent.id);
      const stance = this.actionPoints.stance || 'defensive';
      const baseMax = stance === 'aggressive' ? 10 : 5;
      this.actionPoints.max = inCombat ? baseMax : 0;
      if (!inCombat) this.actionPoints.value = 0;
      else if (this.actionPoints.value === 0) this.actionPoints.value = this.actionPoints.max;
      else if (this.actionPoints.value > this.actionPoints.max) this.actionPoints.value = this.actionPoints.max;
    }
  }
  
  getRollData() {
    const data = {};

    // Copy the characteristic scores to the top level, so that rolls can use
    // formulas like `@puissance.mod + 4`.
    if (this.characteristics) {
      for (let [k, v] of Object.entries(this.characteristics)) {
        data[k] = foundry.utils.deepClone(v);
      }
    }

    return data;
  }
}