import { SYSTEM, STATUS_EFFECTS } from "./module/config/system.mjs"
globalThis.SYSTEM = SYSTEM

import * as models from "./module/models/_module.mjs"
import * as documents from "./module/documents/_module.mjs"
import * as applications from "./module/applications/_module.mjs"
import OathHammerUtils from "./module/utils.mjs"
import OathHammerWeaponDialog from "./module/applications/weapon-dialog.mjs"
import OathHammerCombat from "./module/combat.mjs"
import { rollWeaponDamage } from "./module/rolls.mjs"
import { injectFreeRollBar } from "./module/applications/free-roll.mjs"

Hooks.once("init", function () {
  console.info(SYSTEM.ASCII)
  console.info("Oath Hammer | Initializing System")

  globalThis.oathHammer = game.system
  game.system.CONST = SYSTEM

  game.system.api = { applications, models, documents }

  CONFIG.Actor.documentClass = documents.OathHammerActor
  CONFIG.Combat.documentClass = OathHammerCombat
  CONFIG.Actor.dataModels = {
    character: models.OathHammerCharacter,
    npc: models.OathHammerNPC,
    settlement: models.OathHammerSettlement
  }

  CONFIG.Item.documentClass = documents.OathHammerItem
  CONFIG.Item.dataModels = {
    weapon: models.OathHammerWeapon,
    armor: models.OathHammerArmor,
    ammunition: models.OathHammerAmmunition,
    equipment: models.OathHammerEquipment,
    spell: models.OathHammerSpell,
    miracle: models.OathHammerMiracle,
    "magic-item": models.OathHammerMagicItem,
    trait: models.OathHammerTrait,
    oath: models.OathHammerOath,
    "class": models.OathHammerClass,
    building: models.OathHammerBuilding
  }

  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet)
  foundry.documents.collections.Actors.registerSheet("fvtt-oath-hammer", applications.OathHammerCharacterSheet, {
    types: ["character"],
    makeDefault: true,
    label: "OATHHAMMER.Sheet.Character"
  })
  foundry.documents.collections.Actors.registerSheet("fvtt-oath-hammer", applications.OathHammerNPCSheet, {
    types: ["npc"],
    makeDefault: true,
    label: "OATHHAMMER.Sheet.NPC"
  })
  foundry.documents.collections.Actors.registerSheet("fvtt-oath-hammer", applications.OathHammerSettlementSheet, {
    types: ["settlement"],
    makeDefault: true,
    label: "OATHHAMMER.Sheet.Settlement"
  })

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet)
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerWeaponSheet, { types: ["weapon"], makeDefault: true, label: "OATHHAMMER.Sheet.Weapon" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerArmorSheet, { types: ["armor"], makeDefault: true, label: "OATHHAMMER.Sheet.Armor" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerAmmunitionSheet, { types: ["ammunition"], makeDefault: true, label: "OATHHAMMER.Sheet.Ammunition" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerEquipmentSheet, { types: ["equipment"], makeDefault: true, label: "OATHHAMMER.Sheet.Equipment" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerSpellSheet, { types: ["spell"], makeDefault: true, label: "OATHHAMMER.Sheet.Spell" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerMiracleSheet, { types: ["miracle"], makeDefault: true, label: "OATHHAMMER.Sheet.Miracle" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerMagicItemSheet, { types: ["magic-item"], makeDefault: true, label: "OATHHAMMER.Sheet.MagicItem" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerTraitSheet, { types: ["trait"], makeDefault: true, label: "OATHHAMMER.Sheet.Trait" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerOathSheet, { types: ["oath"], makeDefault: true, label: "OATHHAMMER.Sheet.Oath" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerClassSheet, { types: ["class"], makeDefault: true, label: "OATHHAMMER.Sheet.Class" })
  foundry.documents.collections.Items.registerSheet("fvtt-oath-hammer", applications.OathHammerBuildingSheet, { types: ["building"], makeDefault: true, label: "OATHHAMMER.Sheet.Building" })

  CONFIG.statusEffects = STATUS_EFFECTS

  OathHammerUtils.registerHandlebarsHelpers()

  console.info("Oath Hammer | System Initialized")
})

Hooks.once("ready", async function () {
  console.info("Oath Hammer | System Ready")

  // Migration: remove orphaned items with removed types (lineage → actor field, ability → trait)
  const removedTypes = new Set(["lineage", "ability"])
  for (const actor of game.actors) {
    const invalidItems = actor._source.items?.filter(i => removedTypes.has(i.type)) ?? []
    if (invalidItems.length) {
      console.info(`Oath Hammer | Migrating ${actor.name}: removing ${invalidItems.length} obsolete item(s)`)
      await actor.deleteEmbeddedDocuments("Item", invalidItems.map(i => i._id))
    }
  }
  for (const id of game.items.invalidDocumentIds) {
    const item = game.items.getInvalid(id)
    if (item && removedTypes.has(item._source.type)) {
      console.info(`Oath Hammer | Deleting world item: ${item._source.name} (${item._source.type})`)
      await item.delete()
    }
  }
})

// Handle "Roll Damage" button in weapon attack chat cards
Hooks.on("renderChatMessageHTML", (message, html) => {
  const btn = html.querySelector("[data-action=\"rollWeaponDamage\"]")
  if (!btn) return
  btn.addEventListener("click", async () => {
    const flagData = message.getFlag("fvtt-oath-hammer", "weaponAttack")
    if (!flagData) return
    const { actorUuid, weaponUuid, attackSuccesses } = flagData
    const actor  = await fromUuid(actorUuid)
    const weapon = await fromUuid(weaponUuid)
    if (!actor || !weapon) return ui.notifications.warn(game.i18n.localize("OATHHAMMER.Roll.NoActor"))
    const opts = await OathHammerWeaponDialog.promptDamage(actor, weapon, attackSuccesses ?? 0)
    if (opts) await rollWeaponDamage(actor, weapon, opts)
  })
})

// Inject Free Roll bar into the chat sidebar
Hooks.on("renderChatLog", (_chatLog, html) => injectFreeRollBar(_chatLog, html))
