import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { PIECES, resolve, type Pair, type PieceName, type RGBA, type StyleDump, type StyleLayer, type StyleState } from '../src/core/gameStyle'
import { crop, decodePng, encodePng, type Image } from './bench/png'
import { styleInstall } from './dump-styles'

export type AxisMode = 'fixed' | 'stretch' | 'tile'
export interface SlicePiece {
  name: PieceName
  image: Image
  screenSize: Pair
  axes: [AxisMode, AxisMode]
}

/** Area integration uses premultiplied samples and returns straight alpha. */
export function boxResize(image: Image, width: number, height: number): Image {
  if (![width, height].every(n => Number.isInteger(n) && n > 0)) throw new Error('Invalid box-filter output size')
  const data = new Uint8Array(width * height * 4)
  const dx = image.width / width, dy = image.height / height
  // The game's exact 2:1 atlas mip truncates channels (dialog and widget benches).
  const quantize = dx === 2 && dy === 2 ? Math.floor : Math.round
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const x0 = x * dx, x1 = (x + 1) * dx, y0 = y * dy, y1 = (y + 1) * dy
      const channels = [0, 0, 0]
      let alpha = 0
      for (let sy = Math.floor(y0); sy < Math.ceil(y1) && sy < image.height; sy++) {
        for (let sx = Math.floor(x0); sx < Math.ceil(x1) && sx < image.width; sx++) {
          const weight = (Math.min(x1, sx + 1) - Math.max(x0, sx)) * (Math.min(y1, sy + 1) - Math.max(y0, sy))
          const i = (sy * image.width + sx) * 4
          const a = image.data[i + 3]! * weight
          alpha += a
          for (let c = 0; c < 3; c++) channels[c] = channels[c]! + image.data[i + c]! * a
        }
      }
      const i = (y * width + x) * 4
      for (let c = 0; c < 3; c++) data[i + c] = alpha ? quantize(channels[c]! / alpha) : 0
      data[i + 3] = quantize(alpha / (dx * dy))
    }
  }
  return { width, height, data }
}

export function tintImage(image: Image, tint: RGBA, opacity = 1): Image {
  const data = new Uint8Array(image.data.length)
  for (let i = 0; i < data.length; i += 4) {
    for (let c = 0; c < 4; c++) data[i + c] = Math.round(image.data[i + c]! * tint[c]! / 255 * (c === 3 ? opacity : 1))
  }
  return { width: image.width, height: image.height, data }
}

export function pieceAxes(layer: StyleLayer, key: PieceName): [AxisMode, AxisMode] {
  const monolith = Object.keys(layer.pieces).length === 1 && layer.pieces.center !== undefined
  const x = monolith ? layer.stretchMonolith : key === 'top' || key === 'center' || key === 'bottom'
  const y = monolith ? layer.stretchMonolith : key === 'left' || key === 'center' || key === 'right'
  const tileX = key === 'center' ? layer.tiling.center_tiling_horizontal : layer.tiling[`${key}_tiling`]
  const tileY = key === 'center' ? layer.tiling.center_tiling_vertical : layer.tiling[`${key}_tiling`]
  return [x ? tileX ? 'tile' : 'stretch' : 'fixed', y ? tileY ? 'tile' : 'stretch' : 'fixed']
}

export function sliceLayer(layer: StyleLayer, load: (filename: string) => Image): SlicePiece[] {
  const result: SlicePiece[] = []
  for (const name of PIECES) {
    const sprite = layer.pieces[name]
    if (!sprite) continue
    const [w, h] = sprite.size
    if (![...sprite.position, w, h].every(Number.isInteger) || w <= 0 || h <= 0 || !Number.isFinite(sprite.scale) || sprite.scale <= 0) {
      throw new Error(`Invalid sprite geometry: ${layer.name}.${name}`)
    }
    const axes = pieceAxes(layer, name)
    const region = crop(load(sprite.filename), ...sprite.position, w, h)
    const screenSize: Pair = [w * sprite.scale, h * sprite.scale]
    const width = axes[0] === 'stretch' ? w : Math.max(1, Math.round(screenSize[0]))
    const height = axes[1] === 'stretch' ? h : Math.max(1, Math.round(screenSize[1]))
    const image = tintImage(boxResize(region, width, height), sprite.tint, sprite.opacity)
    result.push({ name, image, screenSize, axes })
  }
  return result
}

export const SPIKE_SET = [
  'button:default', 'button:hovered', 'button:clicked', 'button:disabled',
  'checkbox:unchecked', 'checkbox:checked', 'checkbox:disabled-checked',
  'table_with_selection:default', 'table_with_selection:hovered', 'table_with_selection:selected',
  'mods_scroll_pane:default',
]

const STATES: StyleState[] = ['default', 'hovered', 'clicked', 'disabled', 'selected', 'selected_hovered', 'selected_clicked',
  'unchecked', 'checked', 'disabled-checked', 'hovered-checked', 'clicked-checked', 'intermediate', 'disabled-intermediate']

export function writeSlices(args: string[]): void {
  const dump = JSON.parse(readFileSync('assets/game/styles.json', 'utf8')) as StyleDump
  const install = styleInstall()
  const cache = new Map<string, Image>()
  const load = (filename: string) => {
    let image = cache.get(filename)
    if (!image) {
      if (!/^__(core|base|space-age)__\/[\w./-]+\.png$/.test(filename) || filename.split('/').includes('..')) throw new Error(`Unsupported game image path: ${filename}`)
      const file = filename.replace(/^__(core|base|space-age)__\//, '$1/')
      image = decodePng(readFileSync(path.join(install, 'data', file)))
      cache.set(filename, image)
    }
    return image
  }
  const entries: Record<string, unknown> = {}
  const out = 'assets/game/slices'
  mkdirSync(out, { recursive: true })
  for (const arg of args.length ? args : SPIKE_SET) {
    const [name, state = 'default', extra] = arg.split(':')
    if (!name || !/^[a-z0-9_]+$/.test(name) || extra !== undefined || !STATES.includes(state as StyleState)) throw new Error(`Expected style:state, got ${arg}`)
    const resolved = resolve(dump, name, state as StyleState)
    const layers = resolved.layers.map((layer, i) => {
      const pieces = Object.fromEntries(sliceLayer(layer, load).map(piece => {
        const file = `${name}-${state}-${i}-${piece.name}.png`
        writeFileSync(path.join(out, file), encodePng(piece.image))
        return [piece.name, { file, screenSize: piece.screenSize, rasterSize: [piece.image.width, piece.image.height], axes: piece.axes, source: layer.pieces[piece.name] }]
      }))
      return { ...layer, pieces }
    })
    entries[`${name}:${state}`] = { ...resolved, layers }
  }
  writeFileSync(path.join(out, 'index.json'), JSON.stringify({ gameVersion: dump.gameVersion, uiScale: 1, entries }, null, 2) + '\n')
  console.log(`[style-slices] ${Object.keys(entries).length} style/state pairs -> ${out}/index.json`)
}

if (import.meta.main) writeSlices(process.argv.slice(2))
