import { SYSTEM } from "../config/system.mjs"
import { abilitySchema, booleanField, conditionSchema, htmlField, numberField, stringField, trackSchema } from "./shared.mjs"

export default class MGNECharacter extends foundry.abstract.TypeDataModel {
  static defineSchema() {
    const fields = foundry.data.fields

    return {
      abilities: abilitySchema(),
      hp: trackSchema(1, 1),
      omens: new fields.SchemaField({
        current: numberField(0, 0),
        die: new fields.StringField({ required: true, nullable: false, initial: "d2", choices: SYSTEM.omenDieChoices }),
      }),
      resonance: new fields.SchemaField({
        max: numberField(1, 0),
        used: numberField(0, 0),
        blocked: booleanField(false),
      }),
      artifactSync: new fields.SchemaField({
        used: numberField(0, 0),
      }),
      survival: new fields.SchemaField({
        salvationUsed: booleanField(false),
      }),
      conditions: conditionSchema(),
      carryCapacity: numberField(8, 0),
      rations: numberField(0, 0),
      kiffol: numberField(0, 0),
      background: stringField(""),
      origin: stringField(""),
      scars: stringField(""),
      motivation: stringField(""),
      vice: stringField(""),
      description: htmlField(""),
      notes: htmlField(""),
    }
  }

  prepareDerivedData() {
    super.prepareDerivedData()

    this.carryCapacity = (this.abilities.strength?.value ?? 0) + 8
    this.resonance.remaining = Math.max(0, (this.resonance.max ?? 0) - (this.resonance.used ?? 0))
    this.syncLimit = Math.max(0, this.abilities.toughness?.value ?? 0)
    this.syncRemaining = Math.max(0, this.syncLimit - (this.artifactSync.used ?? 0))
    this.armorFormula = this.parent?.getArmorRollFormula?.() ?? "0"

    // Compute current load per RAW:
    // trivial = 0, light = 10 per slot, normal = 1, heavy = fills remaining capacity (max 1)
    let normalLoad = 0
    let lightCount = 0
    let heavyCount = 0
    for (const item of (this.parent?.items ?? [])) {
      if (item.system?.carried === false) continue  // not being carried
      const w = item.system?.weight ?? "normal"
      if (w === "trivial") continue
      else if (w === "light") lightCount++
      else if (w === "normal") normalLoad++
      else if (w === "heavy") heavyCount++
    }
    normalLoad += Math.floor(lightCount / 10)
    this.lightItemCount = lightCount
    this.heavyItemCount = heavyCount

    if (heavyCount >= 2) {
      // Can't carry two heavy items — automatically overloaded
      this.currentLoad = this.carryCapacity + (heavyCount - 1)
    } else if (heavyCount === 1) {
      // Heavy fills remaining capacity; other items fit alongside it
      this.currentLoad = Math.max(normalLoad, this.carryCapacity)
    } else {
      this.currentLoad = normalLoad
    }
    this.overloaded = this.currentLoad > this.carryCapacity
  }

  /** @override */
  static LOCALIZATION_PREFIXES = ["MGNE.Character"]
}
