/**
 * Crop and sprite truths from bench/refs.json (see docs/development.md). `<install>` in image paths resolves through src/core/paths.ts.
 */
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'

import type { Rect } from './diff'
import { crop, decodePng, type Image } from './png'

export interface RefEntry {
  image: string
  rect: Rect
  /** Text regions, image-relative. */
  masks?: Rect[]
  note?: string
}

export interface Refs {
  images: Record<string, string>
  crops: Record<string, RefEntry>
  sprites?: Record<string, RefEntry>
}

export function loadRefs(file: string): Refs {
  if (!existsSync(file)) throw new Error(`${file} does not exist`)
  return JSON.parse(readFileSync(file, 'utf8')) as Refs
}

export function findRef(refs: Refs, kind: 'crop' | 'sprite', key: string): RefEntry {
  const entry = (kind === 'sprite' ? refs.sprites?.[key] : undefined) ?? refs.crops[key]
  if (!entry) throw new Error(`no ${kind} '${key}' in refs.json`)
  return entry
}

export function resolveImagePath(refs: Refs, name: string, root: string, installDir: string): string {
  const p = refs.images[name]
  if (!p) throw new Error(`refs.json has no image '${name}'`)
  const resolved = p.replace(/^<install>/, installDir)
  return path.isAbsolute(resolved) ? resolved : path.join(root, resolved)
}

/** The crop plus its masks moved into crop coordinates (clipped to the crop). */
export function cropRef(entry: RefEntry, image: Image): { image: Image; masks: Rect[] } {
  const [x, y, w, h] = entry.rect
  const masks: Rect[] = []
  for (const [mx, my, mw, mh] of entry.masks ?? []) {
    const x0 = Math.max(mx - x, 0), y0 = Math.max(my - y, 0)
    const x1 = Math.min(mx + mw - x, w), y1 = Math.min(my + mh - y, h)
    if (x1 > x0 && y1 > y0) masks.push([x0, y0, x1 - x0, y1 - y0])
  }
  return { image: crop(image, x, y, w, h), masks }
}

const cache = new Map<string, Image>()
export function loadImage(file: string): Image {
  let img = cache.get(file)
  if (!img) { img = decodePng(readFileSync(file)); cache.set(file, img) }
  return img
}
