/**
 * Pixel metrics, diff images and verdicts for the fidelity bench
 * (docs/development.md, "Fidelity bench"). Pure functions only.
 */
import type { Image } from './png'

export type Rect = [x: number, y: number, w: number, h: number]
export type Verdict = 'PASS' | 'NEAR' | 'FAIL'

/** The tiers from the spec, in one place. The owner fixes the numbers after S1. */
export const TOLERANCE = {
  /** PASS: max per-channel Δ outside masks. */
  passMaxDelta: 2,
  /** NEAR: max Δ and the share of pixels with Δ > passMaxDelta (2%). */
  nearMaxDelta: 8,
  nearShareOver: 0.02,
  /** Text ink: pixels differing from the case background by more than this. */
  inkThreshold: 24,
  /** Each ink-box edge must match within this many px. */
  inkEdge: 1,
} as const

/** [x0, y0, x1, y1], inclusive-exclusive, or null when a region has no ink. */
export type Box = [number, number, number, number]

export interface TextDelta {
  mask: Rect
  truth: Box | null
  ours: Box | null
  /** Per-edge ours − truth (left, top, right, bottom); null when either side has no ink. */
  edges: [number, number, number, number] | null
  ok: boolean
}

export interface Metrics {
  width: number
  height: number
  /** Pixels compared (outside masks). */
  pixels: number
  maxDelta: number
  over2: number
  over8: number
  text: TextDelta[]
  verdict: Verdict
}

export function parseHex(hex: string): [number, number, number] {
  let h = hex.replace('#', '')
  if (h.length === 3) h = [...h].map((c) => c + c).join('')
  const n = Number.parseInt(h.slice(0, 6), 16)
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
}

function inRect(x: number, y: number, [rx, ry, rw, rh]: Rect): boolean {
  return x >= rx && x < rx + rw && y >= ry && y < ry + rh
}

/** Max per-channel |Δ| of pixel i (byte offset), alpha included. */
function pixelDelta(a: Uint8Array, b: Uint8Array, i: number): number {
  let m = 0
  for (let c = 0; c < 4; c++) {
    const d = Math.abs(a[i + c]! - b[i + c]!)
    if (d > m) m = d
  }
  return m
}

/** Bounding box of pixels inside `rect` that differ from `bg` by more than `threshold`. */
export function inkBox(img: Image, rect: Rect, bg: string, threshold: number = TOLERANCE.inkThreshold): Box | null {
  const [br, bgc, bb] = parseHex(bg)
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity
  const [rx, ry, rw, rh] = rect
  for (let y = Math.max(0, ry); y < Math.min(img.height, ry + rh); y++) {
    for (let x = Math.max(0, rx); x < Math.min(img.width, rx + rw); x++) {
      const i = (y * img.width + x) * 4
      const d = Math.max(Math.abs(img.data[i]! - br), Math.abs(img.data[i + 1]! - bgc), Math.abs(img.data[i + 2]! - bb))
      if (d <= threshold) continue
      if (x < x0) x0 = x
      if (y < y0) y0 = y
      if (x + 1 > x1) x1 = x + 1
      if (y + 1 > y1) y1 = y + 1
    }
  }
  return x0 === Infinity ? null : [x0, y0, x1, y1]
}

export function textDelta(truth: Image, ours: Image, mask: Rect, bg: string): TextDelta {
  const t = inkBox(truth, mask, bg)
  const o = inkBox(ours, mask, bg)
  if (!t || !o) return { mask, truth: t, ours: o, edges: null, ok: t === o }
  const edges: [number, number, number, number] = [o[0] - t[0], o[1] - t[1], o[2] - t[2], o[3] - t[3]]
  return { mask, truth: t, ours: o, edges, ok: edges.every((e) => Math.abs(e) <= TOLERANCE.inkEdge) }
}

export function verdict(maxDelta: number, over2: number, pixels: number, textOk: boolean): Verdict {
  if (!textOk) return 'FAIL'
  if (maxDelta <= TOLERANCE.passMaxDelta) return 'PASS'
  if (maxDelta <= TOLERANCE.nearMaxDelta && over2 <= pixels * TOLERANCE.nearShareOver) return 'NEAR'
  return 'FAIL'
}

/** Compare two same-sized images; masked pixels are scored as text only. */
export function compare(truth: Image, ours: Image, masks: Rect[] = [], bg = '#000000'): Metrics {
  if (truth.width !== ours.width || truth.height !== ours.height) {
    throw new Error(`size mismatch: truth ${truth.width}x${truth.height}, ours ${ours.width}x${ours.height}`)
  }
  let pixels = 0, maxDelta = 0, over2 = 0, over8 = 0
  for (let y = 0; y < truth.height; y++) {
    for (let x = 0; x < truth.width; x++) {
      if (masks.some((m) => inRect(x, y, m))) continue
      const d = pixelDelta(truth.data, ours.data, (y * truth.width + x) * 4)
      pixels++
      if (d > maxDelta) maxDelta = d
      if (d > 2) over2++
      if (d > 8) over8++
    }
  }
  const text = masks.map((m) => textDelta(truth, ours, m, bg))
  return { width: truth.width, height: truth.height, pixels, maxDelta, over2, over8, text, verdict: verdict(maxDelta, over2, pixels, text.every((t) => t.ok)) }
}

/** |Δ| per channel ×8, opaque; masks hatched grey so they read as "not scored". */
export function diffImage(truth: Image, ours: Image, masks: Rect[] = [], gain = 8): Image {
  const { width, height } = truth
  const data = new Uint8Array(width * height * 4)
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const i = (y * width + x) * 4
      for (let c = 0; c < 3; c++) data[i + c] = Math.min(255, Math.abs(truth.data[i + c]! - ours.data[i + c]!) * gain)
      data[i + 3] = 255
      if (masks.some((m) => inRect(x, y, m)) && (x + y) % 4 < 2) {
        for (let c = 0; c < 3; c++) data[i + c] = Math.max(data[i + c]!, 96)
      }
    }
  }
  return { width, height, data }
}

/** Images left to right on one row, separated by `gap` px of `fill`. */
export function sideBySide(images: Image[], gap = 2, fill = '#ff00ff'): Image {
  const width = images.reduce((n, im) => n + im.width, 0) + gap * (images.length - 1)
  const height = Math.max(...images.map((im) => im.height))
  const [fr, fg, fb] = parseHex(fill)
  const data = new Uint8Array(width * height * 4)
  for (let i = 0; i < width * height; i++) { data[i * 4] = fr; data[i * 4 + 1] = fg; data[i * 4 + 2] = fb; data[i * 4 + 3] = 255 }
  let ox = 0
  for (const im of images) {
    for (let y = 0; y < im.height; y++) data.set(im.data.subarray(y * im.width * 4, (y + 1) * im.width * 4), (y * width + ox) * 4)
    ox += im.width + gap
  }
  return { width, height, data }
}

export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
  return true
}
