import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { inheritStyles, PIECES, resolve, type Pair, type Rect, type RGBA, type Sides, type Style, type StyleDump, type StyleLayer, type StyleSprite, type StyleState } from '../src/core/gameStyle'
import { readGameVersion } from '../src/core/paths'
import { crop, decodePng, encodePng, type Image } from './bench/png'
import { dumpStyles, styleInstall } from './dump-styles'
import { boxResize, pieceAxes } from './style-slices'

export type PieceScale = 1 | 1.25
const ROOT = fileURLToPath(new URL('../', import.meta.url))
const FORMAT = 4
const ATLAS = '__core__/graphics/gui-new.png'
/** Bump when requests() gains or loses a style, so cached piece sets refresh. */
const PIECE_SET_REVISION = 'slider+frame-action-button+red-back-button+negative-hovered+horizontal-caps+progressbar-tinted'
const BUTTON_STATES: StyleState[] = ['default', 'hovered', 'clicked', 'disabled']
const SELECT_STATES: StyleState[] = [...BUTTON_STATES, 'selected', 'selected_hovered', 'selected_clicked']
const CHECK_STATES: StyleState[] = [...SELECT_STATES, 'unchecked', 'checked', 'disabled-checked', 'hovered-checked', 'clicked-checked', 'intermediate', 'disabled-intermediate']

export interface Piece {
  file: string
  /** Exact logical dimensions; fixed sprites can occupy fractional screen pixels. */
  screenSize: Pair
  rasterSize: Pair
  /** Slint order: top, right, bottom, left, in screen pixels. */
  nineSlice: [number, number, number, number]
  outerExtent: Sides
  drawType: 'inner' | 'outer'
  tint: RGBA
  opacity: number
  source: Record<string, { filename: string, rect: Rect, tint: RGBA, opacity: number }>
  tiling: Record<string, unknown>
  stretchMonolith: boolean
  /** Tips and precomposed ribs have a fixed height; stretch/tile horizontally only. */
  fixedHeight?: number
  /** Opaque precomposition: valid only on this named Mods-window surface. */
  backdrop?: { name: string, color: RGBA, layers: string[] }
}

export interface PiecesIndex {
  format: number
  gameVersion: string
  scale: PieceScale
  fingerprint: string
  pieces: Record<string, Piece>
  /** Ordered layer keys, including shadows before faces and marks after faces. */
  entries: Record<string, string[]>
}

function blank(width: number, height: number): Image {
  return { width, height, data: new Uint8Array(width * height * 4) }
}

/** Premultiplied game tint, composited before any straight-alpha PNG clamping. */
export function precomposePixel(source: RGBA, tint: RGBA, opacity: number, backdrop: RGBA): RGBA {
  const coverage = source[3] / 255 * opacity
  const alpha = coverage * tint[3] / 255
  return [0, 1, 2].map(c => Math.min(255, Math.max(0, Math.round(
    source[c]! * coverage * tint[c]! / 255 + backdrop[c]! * (1 - alpha),
  )))).concat(255) as RGBA
}

function sliceAt(n: number, target: number, size: number, before: number, after: number): number {
  if (n < before) return n
  if (n >= target - after) return size - (target - n)
  return before + Math.min(size - before - after - 1, Math.floor((n - before) * (size - before - after) / (target - before - after)))
}

/** Bake both the face and the spill; canonical middle pixels remain stretchable. */
function precomposeState(layers: StyleLayer[], scale: PieceScale, load: (filename: string) => Image, name: string, color: RGBA, tipped: boolean) {
  const w = Math.round(40 * scale), h = Math.round((tipped ? 32 : 28) * scale), pad = Math.round(4 * scale)
  const image = blank(w + pad * 2, h + pad * 2)
  for (let i = 0; i < image.data.length; i += 4) image.data.set(color, i)
  const sources: Piece['source'] = {}
  for (const layer of layers) {
    const neutral = { ...layer, tint: [255, 255, 255, 255] as RGBA, opacity: 1,
      pieces: Object.fromEntries(Object.entries(layer.pieces).map(([k, p]) => [k, { ...p, tint: [255, 255, 255, 255] as RGBA, opacity: 1 }])) }
    const raw = composeLayer(neutral, scale, load)
    const original = composeLayer(layer, scale, load)
    Object.assign(sources, Object.fromEntries(Object.entries(original.metadata.source).map(([k, v]) => [`${layer.name}.${k}`, v])))
    const e = original.metadata.outerExtent
    const x0 = pad - Math.round(e.left), y0 = pad - Math.round(e.top)
    const tw = w + Math.round(e.left + e.right), th = h + Math.round(e.top + e.bottom)
    const [top, right, bottom, left] = raw.metadata.nineSlice
    for (let y = 0; y < th; y++) for (let x = 0; x < tw; x++) {
      const dx = x + x0, dy = y + y0
      if (dx < 0 || dy < 0 || dx >= image.width || dy >= image.height) continue
      const sx = sliceAt(x, tw, raw.image.width, left, right), sy = sliceAt(y, th, raw.image.height, top, bottom)
      const si = (sy * raw.image.width + sx) * 4, di = (dy * image.width + dx) * 4
      image.data.set(precomposePixel(Array.from(raw.image.data.slice(si, si + 4)) as RGBA, layer.tint, layer.opacity, Array.from(image.data.slice(di, di + 4)) as RGBA), di)
    }
  }
  const metadata: Omit<Piece, 'file'> = {
    screenSize: [image.width, image.height], rasterSize: [image.width, image.height],
    nineSlice: tipped ? [0, 20 * scale, 0, 20 * scale] : [8 * scale, 8 * scale, 8 * scale, 8 * scale],
    outerExtent: { top: pad, right: pad, bottom: pad, left: pad }, drawType: 'outer', tint: [255, 255, 255, 255], opacity: 1,
    source: sources, tiling: {}, stretchMonolith: true,
    backdrop: { name, color, layers: layers.map(l => l.name) }, ...(tipped ? { fixedHeight: image.height } : {}),
  }
  return { image, metadata }
}

function put(dst: Image, src: Image, x: number, y: number): void {
  for (let row = 0; row < src.height; row++) {
    dst.data.set(src.data.subarray(row * src.width * 4, (row + 1) * src.width * 4), ((y + row) * dst.width + x) * 4)
  }
}

/** Game tints multiply premultiplied RGB, independently of tint alpha (dialog bench). */
export function gameTint(image: Image, tint: RGBA, opacity: number): Image {
  const data = new Uint8Array(image.data.length)
  for (let i = 0; i < data.length; i += 4) {
    for (let c = 0; c < 3; c++) data[i + c] = tint[3] ? Math.min(255, Math.floor(image.data[i + c]! * tint[c]! / tint[3])) : 0
    data[i + 3] = Math.round(image.data[i + 3]! * tint[3] / 255 * opacity)
  }
  return { ...image, data }
}

function raster(sprite: StyleSprite, load: (filename: string) => Image, width: number, height: number): Image {
  if (![...sprite.position, ...sprite.size].every(Number.isInteger) || sprite.size.some(n => n <= 0) || !Number.isFinite(sprite.scale) || sprite.scale <= 0) throw new Error('Invalid sprite geometry')
  return gameTint(boxResize(crop(load(sprite.filename), ...sprite.position, ...sprite.size), width, height), sprite.tint, sprite.opacity)
}

const scaledSides = (sides: Sides, scale: number): Sides => Object.fromEntries(Object.entries(sides).map(([k, v]) => [k, v * scale])) as unknown as Sides

/** Compact nine-slice composition, retaining one source pixel on stretch axes. */
export function composeLayer(layer: StyleLayer, scale: PieceScale, load: (filename: string) => Image): { image: Image, metadata: Omit<Piece, 'file'> } {
  const sprites = layer.pieces
  const size = (key: typeof PIECES[number], axis: 0 | 1) => {
    const s = sprites[key]
    return s ? Math.max(1, Math.round(s.size[axis] * s.scale * scale)) : 0
  }
  const extent = (keys: typeof PIECES[number][], axis: 0 | 1) => Math.max(0, ...keys.map(k => size(k, axis)))
  const monolith = Object.keys(sprites).length === 1 && !!sprites.center
  const left = extent(['left_top', 'left', 'left_bottom'], 0)
  const right = extent(['right_top', 'right', 'right_bottom'], 0)
  const top = extent(['left_top', 'top', 'right_top'], 1)
  const bottom = extent(['left_bottom', 'bottom', 'right_bottom'], 1)
  const center = sprites.center
  const tall = !!center && center.size[1] > 1 && (!!sprites.left || !!sprites.right) && !layer.tiling.center_tiling_vertical
  const centerWidth = center && (monolith || pieceAxes(layer, 'center')[0] === 'tile') ? size('center', 0) : 1
  const centerHeight = center && (monolith || pieceAxes(layer, 'center')[1] === 'tile') ? size('center', 1) : 1
  const width = monolith ? size('center', 0) : left + centerWidth + right
  const height = monolith ? size('center', 1) : Math.max(top + centerHeight + bottom, tall ? size('center', 1) : 0, size('left', 1), size('right', 1))
  let image = blank(width, height)
  for (const key of PIECES) {
    const sprite = sprites[key]
    if (!sprite) continue
    const column = PIECES.indexOf(key) % 3, row = Math.floor(PIECES.indexOf(key) / 3)
    let w = column === 1 ? width - left - right : size(key, 0)
    let h = row === 1 ? height - top - bottom : size(key, 1)
    let x = column === 0 ? left - w : column === 1 ? left : width - right
    let y = row === 0 ? top - h : row === 1 ? top : height - bottom
    // tab_glow has 8px corners but 4px straight bands. Their outer edges
    // align; aligning their inner edges creates spots at the top and notch.
    if (sprites.left_top && !sprites.left_bottom && layer.draw_type === 'outer') {
      if (key === 'top') y = 0
      if (key === 'left') x = 0
      if (key === 'right') x = width - w
    }
    if (monolith) { w = width; h = height; x = 0; y = 0 }
    // Back/confirm tips and their centre strips span the complete button height.
    if (tall && row === 1 && sprite.size[1] > 1) { h = height; y = 0 }
    if (w > 0 && h > 0) put(image, raster(sprite, load, w, h), x, y)
  }
  const source = Object.fromEntries(Object.entries(sprites).map(([key, s]) => [key, {
    filename: s.filename, rect: [...s.position, ...s.size] as Rect, tint: s.tint, opacity: s.opacity,
  }]))
  // PNG dimensions must be integers; retain the exact fixed-sprite size for layout.
  let screenSize: Pair = monolith && center ? center.size.map(n => n * center.scale * scale) as Pair : [width, height]
  // Filter a contiguous tiled strip as a whole: independently rounding a 7/8/7
  // source-pixel scrollbar would incorrectly turn its 11 screen pixels into 12.
  const strip = sprites.top && sprites.bottom && center && center.size[1] > 1 && Object.keys(sprites).length === 3
    ? [sprites.top, center, sprites.bottom] : sprites.left && sprites.right && center && center.size[0] > 1 && Object.keys(sprites).length === 3
      ? [sprites.left, center, sprites.right] : undefined
  if (strip && center && strip.every(s => s.scale === center.scale && s.filename === center.filename && s.opacity === center.opacity && s.tint.every((v, i) => v === center.tint[i]))) {
    const vertical = !!sprites.top
    const axis = vertical ? 1 : 0
    const cross = vertical ? 0 : 1
    if (strip.every(s => s.size[cross] === center.size[cross])) {
      const length = strip.reduce((sum, s) => sum + s.size[axis], 0)
      const big = blank(vertical ? center.size[0] : length, vertical ? length : center.size[1])
      let offset = 0
      for (const s of strip) {
        put(big, crop(load(s.filename), ...s.position, ...s.size), vertical ? 0 : offset, vertical ? offset : 0)
        offset += s.size[axis]
      }
      screenSize = [big.width * center.scale * scale, big.height * center.scale * scale]
      image = gameTint(boxResize(big, Math.max(1, Math.round(screenSize[0])), Math.max(1, Math.round(screenSize[1]))), center.tint, center.opacity)
    }
  }
  return { image, metadata: {
    screenSize, rasterSize: [image.width, image.height], nineSlice: monolith ? [0, 0, 0, 0] : [tall ? 0 : top, right, tall ? 0 : bottom, left],
    outerExtent: scaledSides(layer.outerExtent, scale), drawType: layer.draw_type, tint: layer.tint, opacity: layer.opacity,
    source, tiling: layer.tiling, stretchMonolith: layer.stretchMonolith,
    ...(tall ? { fixedHeight: height } : {}),
  } }
}

interface Request { name: string, style: Style, state: string, resolverState: StyleState }

/** Adapt embedded image-set properties to the existing resolver, without changing core. */
function requests(dump: StyleDump): Request[] {
  const styles = inheritStyles(dump.raw)
  const result: Request[] = []
  const add = (name: string, states: StyleState[] = ['default']) => {
    const style = styles[name]
    if (!style) throw new Error(`ESCALATE: Missing screenshot style ${name}`)
    for (const state of states) result.push({ name, style, state, resolverState: state })
  }
  for (const name of ['frame', 'inside_shallow_frame', 'inside_deep_frame', 'draggable_space', 'draggable_space_header', 'mod_thumbnail_image', 'mod_explore_thumbnail_image', 'mods_scroll_pane', 'scroll_pane', 'subheader_frame', 'negative_message_frame', 'tabbed_pane_frame']) add(name)
  // Added after the test fixtures were written; those synthetic dumps have no tooltip style.
  if (styles.tooltip_frame) add('tooltip_frame')
  if (styles.progressbar) {
    for (const [name, property] of [['progressbar_background', 'bar_background'], ['progressbar_fill', 'bar']] as const) {
      const graphic = styles.progressbar[property] as Style
      const color = styles.progressbar.color as { r?: number, g?: number, b?: number }
      const set = property === 'bar' ? { ...graphic, tint: [255 * (color.r ?? 0), 255 * (color.g ?? 0), 255 * (color.b ?? 0), 255] } : graphic
      result.push({ name, style: { graphical_set: set }, state: 'default', resolverState: 'default' })
    }
  }
  if (styles.slider) {
    for (const part of ['full_bar', 'full_bar_disabled', 'empty_bar', 'empty_bar_disabled']) {
      result.push({ name: `slider_${part}`, style: { graphical_set: styles.slider[part] }, state: 'default', resolverState: 'default' })
    }
    for (const state of BUTTON_STATES) result.push({ name: 'slider_thumb', style: styles.slider.button as Style, state, resolverState: state })
  }
  if (styles.frame_action_button) add('frame_action_button', BUTTON_STATES)
  if (styles.red_back_button) add('red_back_button', BUTTON_STATES)
  for (const name of ['button', 'green_button', 'red_button', 'back_button', 'confirm_button', 'dropdown_button', 'tool_button', 'tool_button_red']) add(name, BUTTON_STATES)
  for (const name of ['tab', 'table_with_selection', 'mods_explore_results_table', 'list_box_item']) add(name, SELECT_STATES)
  for (const name of ['checkbox', 'black_checkbox']) add(name, CHECK_STATES)
  for (const name of ['textbox', 'search_popup_textfield']) {
    const style = styles[name]
    if (!style) throw new Error(`ESCALATE: Missing screenshot style ${name}`)
    for (const [state, property] of [['default', 'default_background'], ['focused', 'active_background'], ['disabled', 'disabled_background']] as const) {
      if (!style[property]) throw new Error(`ESCALATE: Missing ${name}.${property}`)
      result.push({ name, style: { graphical_set: style[property] }, state, resolverState: 'default' })
    }
  }
  for (const state of SELECT_STATES) {
    const property = `${({ hovered: 'hover', clicked: 'press', selected_hovered: 'selected', selected_clicked: 'selected' } as Record<string, string>)[state] ?? state}_badge_graphical_set`
    result.push({ name: 'tab_badge', style: { graphical_set: styles.tab![property] }, state, resolverState: 'default' })
  }
  for (const name of ['vertical_scrollbar', 'horizontal_scrollbar']) {
    add(name)
    const thumb = styles[name]!.thumb_button_style as Style
    for (const state of ['default', 'hovered', 'clicked'] as const) result.push({ name: `${name}_thumb`, style: thumb, state, resolverState: state })
  }
  // Border sprites supply line ends, table cell separators, intersections and corners.
  for (const name of ['line', 'bordered_table']) {
    const border = styles[name]?.border as Style | undefined
    if (!border) throw new Error(`ESCALATE: Missing ${name}.border`)
    for (const [key, value] of Object.entries(border)) {
      if (typeof value === 'object') result.push({ name: `${name}_${key}`, style: { graphical_set: value }, state: 'default', resolverState: 'default' })
    }
    result.push({ name, style: { graphical_set: { left: border.left_end, center: border.horizontal_line, right: border.right_end } }, state: 'default', resolverState: 'default' })
  }
  return result
}

/** Compose ribs before filtering so the odd seven-source-pixel top keeps its phase. */
function ribs(layer: StyleLayer, height: number, scale: PieceScale, load: (filename: string) => Image): { image: Image, metadata: Omit<Piece, 'file'> } {
  const { top, center, bottom } = layer.pieces
  if (!top || !center || !bottom) throw new Error('ESCALATE: Unresolved draggable_space ribs')
  const sourceHeight = Math.round(height / center.scale)
  const big = blank(center.size[0], sourceHeight)
  const cut = (s: StyleSprite) => crop(load(s.filename), ...s.position, ...s.size)
  put(big, cut(top), 0, 0)
  const tile = cut(center)
  for (let y = top.size[1]; y < sourceHeight - bottom.size[1]; y++) put(big, crop(tile, 0, (y - top.size[1]) % tile.height, tile.width, 1), 0, y)
  put(big, cut(bottom), 0, sourceHeight - bottom.size[1])
  const image = gameTint(boxResize(big, Math.round(big.width * center.scale * scale), Math.round(height * scale)), center.tint, center.opacity)
  const { metadata } = composeLayer(layer, scale, load)
  return { image, metadata: { ...metadata, screenSize: [image.width, image.height], rasterSize: [image.width, image.height], nineSlice: [0, 0, 0, 0], fixedHeight: image.height } }
}

export function writePieces(dump: StyleDump, scale: PieceScale, out: string, load: (filename: string) => Image, fingerprint = ''): PiecesIndex {
  if (scale !== 1 && scale !== 1.25) throw new Error('Scale must be 1 or 1.25')
  const dir = path.join(out, String(scale))
  const index: PiecesIndex = { format: FORMAT, gameVersion: dump.gameVersion, scale, fingerprint, pieces: {}, entries: {} }
  const pending: { file: string, bytes: Uint8Array }[] = []
  const emit = (key: string, composed: ReturnType<typeof composeLayer>) => {
    const file = `${key}.png`
    index.pieces[key] = { file, ...composed.metadata }
    pending.push({ file, bytes: encodePng(composed.image) })
  }
  for (const request of requests(dump)) {
    const source = { ...dump, raw: { ...dump.raw, __piece: request.style } }
    const resolved = resolve(source, '__piece', request.resolverState)
    if (!resolved.layers.length) throw new Error(`ESCALATE: No graphical set resolved for ${request.name}:${request.state}`)
    const keys: string[] = []
    for (const layer of resolved.layers) {
      const key = `${request.name}-${request.state}-${layer.name.replaceAll('.', '-')}`
      keys.push(key)
      const composed = composeLayer(layer, scale, load)
      emit(key, composed)
      const glow = dump.constants?.red_button_glow_color as RGBA | undefined
      if (request.name === 'negative_message_frame' && layer.name === 'base' && glow) {
        // The game has no hover state for this frame. Derived: the game's own red hover glow colour
        // (constants.red_button_glow_color, used by red_button / red_back_button hover) composited over the base.
        const hovered = { ...composed.image, data: composed.image.data.slice() }
        for (let i = 0; i < hovered.data.length; i += 4) {
          for (let c = 0; c < 3; c++) hovered.data[i + c] = Math.round(composed.image.data[i + c]! * (1 - glow[3] / 255) + glow[c]! * glow[3] / 255)
        }
        emit(`${request.name}-hovered-${layer.name}`, { ...composed, image: hovered })
      }
      if (request.name.endsWith('scrollbar_thumb') && layer.name === 'base') {
        const parts = request.name.startsWith('horizontal')
          ? [['left', 'left'], ['tile', 'center'], ['right', 'right']] as const
          : [['top', 'top'], ['tile', 'center'], ['bottom', 'bottom']] as const
        for (const [part, spriteKey] of parts) {
          const sprite = layer.pieces[spriteKey]
          if (sprite) emit(`${key}-${part}`, composeLayer({ ...layer, pieces: { center: sprite } }, scale, load))
        }
      }
      if (request.name === 'draggable_space' && layer.name === 'base') {
        for (const height of [24, 32]) emit(`draggable_space-${height}-base`, ribs(layer, height, scale, load))
      }
    }
    index.entries[`${request.name}:${request.state}`] = keys
    if (resolved.layers.some(l => l.tint.slice(0, 3).some(c => c > l.tint[3]))) {
      const tipped = request.name === 'confirm_button' || request.name === 'back_button' || request.name === 'red_back_button'
      const backdrop = tipped ? 'footer' : 'subheader'
      const color: RGBA = tipped ? [49, 48, 49, 255] : [36, 35, 36, 255]
      emit(`${request.name}-${request.state}-precomposed`, precomposeState(resolved.layers, scale, load, backdrop, color, tipped))
    }
  }
  // Resolve every style and cut every PNG before publishing a new cache index.
  mkdirSync(dir, { recursive: true })
  for (const { file, bytes } of pending) atomicWrite(path.join(dir, file), bytes)
  atomicWrite(path.join(dir, 'index.json'), JSON.stringify(index, null, 2) + '\n')
  return index
}

function atomicWrite(file: string, bytes: string | Uint8Array): void {
  const temp = `${file}.${process.pid}.tmp`
  writeFileSync(temp, bytes)
  renameSync(temp, file)
}

export function piecesCurrent(index: PiecesIndex | undefined, gameVersion: string, scale: PieceScale, fingerprint: string, dir: string): boolean {
  return !!index && index.format === FORMAT && index.gameVersion === gameVersion && index.scale === scale && index.fingerprint === fingerprint
    && !!index.entries && !!index.pieces && Object.keys(index.entries).length > 0 && Object.keys(index.pieces).length > 0
    && Object.values(index.pieces).every(p => p && typeof p.file === 'string' && path.basename(p.file) === p.file && existsSync(path.join(dir, p.file)))
}

export interface EnsureOptions { install?: string, out?: string, styles?: string }

/** Startup API: paths default to this checkout, regardless of the app's cwd. */
export async function ensurePieces(scale: PieceScale, options: EnsureOptions = {}): Promise<PiecesIndex> {
  if (scale !== 1 && scale !== 1.25) throw new Error('Scale must be 1 or 1.25')
  const install = options.install ?? styleInstall()
  const out = path.resolve(options.out ?? path.join(ROOT, 'assets/game/pieces'))
  const styles = path.resolve(options.styles ?? path.join(ROOT, 'assets/game/styles.json'))
  const gameVersion = readGameVersion(install)
  const inputs = ['data/core/prototypes/style.lua', 'data/core/prototypes/fonts.lua', 'data/core/locale/en/info.json']
  let dump: StyleDump | undefined
  try { dump = JSON.parse(readFileSync(styles, 'utf8')) as StyleDump } catch { /* Missing or corrupt dump is regenerated. */ }
  if (!dump || dump.gameVersion !== gameVersion || inputs.some(f => statSync(path.join(install, f)).mtimeMs > statSync(styles).mtimeMs)) {
    dump = await dumpStyles(install)
    mkdirSync(path.dirname(styles), { recursive: true })
    atomicWrite(styles, JSON.stringify(dump, null, 2) + '\n')
  }
  const atlasPath = path.join(install, 'data/core/graphics/gui-new.png')
  const atlasStat = statSync(atlasPath)
  const fingerprint = createHash('sha256').update(readFileSync(styles)).update(`${atlasStat.size}:${atlasStat.mtimeMs}`).update(PIECE_SET_REVISION).digest('hex')
  const dir = path.join(out, String(scale))
  let previous: PiecesIndex | undefined
  try { previous = JSON.parse(readFileSync(path.join(dir, 'index.json'), 'utf8')) as PiecesIndex } catch { /* Cache miss. */ }
  if (piecesCurrent(previous, gameVersion, scale, fingerprint, dir)) return previous!
  const atlas = decodePng(readFileSync(atlasPath))
  return writePieces(dump, scale, out, filename => {
    if (filename !== ATLAS) throw new Error(`ESCALATE: Screenshot piece requires unsupported atlas ${filename}`)
    return atlas
  }, fingerprint)
}

if (import.meta.main) {
  let scale: PieceScale = 1
  let out: string | undefined
  const args = process.argv.slice(2)
  for (let i = 0; i < args.length; i++) {
    const arg = args[i], value = args[++i]
    if (arg === '--scale' && (value === '1' || value === '1.25')) scale = Number(value) as PieceScale
    else if (arg === '--out' && value) out = value
    else throw new Error('Usage: bun tools/pieces.ts [--scale 1|1.25] [--out assets/game/pieces]')
  }
  const index = await ensurePieces(scale, { out })
  console.log(`[pieces] ${Object.keys(index.pieces).length} PNGs at ${scale}x (game ${index.gameVersion}) -> ${path.resolve(out ?? path.join(ROOT, 'assets/game/pieces'), String(scale), 'index.json')}`)
}
