import { promises as fs } from "fs"
import path from "path"
import { compilePack } from "@foundryvtt/foundryvtt-cli"

const DATA_FILE = "assets/data/tarot.json"
const SRC_DIR = "packs_src/hamalron-items"
const DEST_DIR = "packs-system/hamalron-items"

async function main() {
  const raw = await fs.readFile(DATA_FILE, "utf-8")
  const cards = JSON.parse(raw)

  if (!Array.isArray(cards)) {
    console.error("Invalid data: expected array")
    process.exit(1)
  }

  console.log(`Generating ${cards.length} tarot cards...`)

  // Clear and recreate the destination LevelDB
  await fs.mkdir(DEST_DIR, { recursive: true })

  // Create a temporary directory for individual JSON files
  await fs.mkdir(SRC_DIR, { recursive: true })
  const existing = await fs.readdir(SRC_DIR)
  for (const f of existing) {
    await fs.unlink(path.join(SRC_DIR, f))
  }

  // Créer le dossier Tarot dans le compendium
  const tarotFolderId = "a000000000000001"
  const folderDoc = {
    _id: tarotFolderId,
    _key: `!folders!${tarotFolderId}`,
    name: "Tarot",
    type: "Item",
    sorting: "a",
    sort: 0,
    color: "#8b4513",
    flags: {},
  }
  const folderPath = path.join(SRC_DIR, `${tarotFolderId}.json`)
  await fs.writeFile(folderPath, JSON.stringify(folderDoc, null, 2), "utf-8")

  // Write each card as a single JSON document file
  for (let i = 0; i < cards.length; i++) {
    const card = cards[i]
    const id = `tarot_${String(i + 1).padStart(3, "0")}`
    const doc = {
      _id: id,
      _key: `!items!${id}`,
      name: card.name,
      type: "tarot",
      img: "systems/fvtt-hamalron/assets/icons/tarot.svg",
      folder: tarotFolderId,
      sort: (i + 1) * 100000,
      flags: {},
      system: {
        type: card.type,
        symbole: card.symbole,
        valeur: card.valeur,
        description: card.description || `<p>${card.name}</p>`,
        image: "systems/fvtt-hamalron/assets/icons/tarot.svg",
      },
    }
    // Write as JSON file for the pack tool
    const filePath = path.join(SRC_DIR, `${id}.json`)
    await fs.writeFile(filePath, JSON.stringify(doc, null, 2), "utf-8")
  }

  console.log("Compiling to LevelDB...")

  // Compile using the CLI
  try {
    // Update the source dir to use JSON instead of YAML
    await compilePack(SRC_DIR, DEST_DIR, { yaml: false, log: true })
    console.log(`Compiled to ${DEST_DIR}`)

    // Count entries
    const files = await fs.readdir(DEST_DIR)
    console.log(`LevelDB files: ${files.length}`)
  } catch (e) {
    console.error("Compile error:", e.message)
    // Fallback: copy JSON to a packs/ dir
    console.log("Fallback: copy JSON to packs/...")
    const fallbackDir = "packs"
    await fs.mkdir(fallbackDir, { recursive: true })
    for (const f of existing) {
      await fs.unlink(path.join(SRC_DIR, f)).catch(() => {})
    }
    console.log(`JSON data in ${SRC_DIR} (compile to LevelDB manually)`)
  }
}

main().catch(console.error)
