#!/usr/bin/env bash
#
# scripts/rasterize-icons.sh — Plan 01-12 Wave 2 Task 1.
#
# One-off icon rasterization recipe.
#
# Reads src/shared/brand/mokosh-mark.svg (the Loom 2×2 weave intersection
# brand mark; D-01) and emits icons/icon{16,48,128}.png via rsvg-convert.
#
# Verified locally (RESEARCH §3): output is 8-bit/color RGBA, non-
# interlaced PNG at the requested dimensions. Sizes clear assets-spec.md
# Chrome imageUtil floors (16≥200B, 48≥500B, 128≥1024B):
#   16  → ~406 B
#   48  → ~784 B
#   128 → ~1952 B
#
# This script is NOT wired into prebuild (per RESEARCH §3 anti-pattern:
# regenerating icons at every build is wasteful + masks regressions in
# the source SVG). PNGs are committed as static artifacts; re-run this
# script when src/shared/brand/mokosh-mark.svg changes.
#
# Replaces the Bug A Plan 01-09 Path A placeholder icons (16-bit/color
# RGB dark-square + green-dot at 574 B / 1153 B / 2615 B) with the
# rasterized Loom mark.
#
# References:
#   - librsvg rsvg-convert(1) manpage
#   - assets-spec.md Chrome imageUtil silent-rejection floors
#   - Plan 01-12 RESEARCH §3 (rsvg-convert default output format)
#
# Google bash style applies; see https://google.github.io/styleguide/shellguide.html

set -euo pipefail

readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly MARK_SVG="${REPO_ROOT}/src/shared/brand/mokosh-mark.svg"
readonly ICONS_DIR="${REPO_ROOT}/icons"

# Per assets-spec.md silent-rejection floors. Indexed by size for clear logs.
declare -rA FLOORS=(
  [16]=200
  [48]=500
  [128]=1024
)

main() {
  if [[ ! -f "${MARK_SVG}" ]]; then
    echo "ERROR: ${MARK_SVG} not found" >&2
    return 1
  fi
  if ! command -v rsvg-convert >/dev/null 2>&1; then
    echo "ERROR: rsvg-convert not found on PATH (install librsvg)" >&2
    return 1
  fi

  mkdir -p "${ICONS_DIR}"

  local size
  for size in 16 48 128; do
    local out="${ICONS_DIR}/icon${size}.png"
    rsvg-convert -w "${size}" -h "${size}" "${MARK_SVG}" -o "${out}"

    local bytes
    bytes="$(stat -c%s "${out}")"
    local floor="${FLOORS[${size}]}"

    if (( bytes < floor )); then
      echo "FAIL: ${out} (${bytes} bytes) is below Chrome imageUtil floor ${floor} B" >&2
      return 1
    fi
    echo "  rasterized: ${out} (${bytes} bytes; floor ${floor} B)"
  done

  echo
  echo "==> Done. PNGs are at ${ICONS_DIR}/icon{16,48,128}.png."
}

main "$@"
