#!/bin/bash
# Batch section-by-section comparison: React vs HTMX.
# Each entry: <label>  <react-selector>  <htmx-selector>
#
# Assumes `pnpm dev` is running and Charlotte MCP is unavailable from shell —
# so this script expects screenshots already captured via Charlotte by name.
# Run compare.py on each pair and emit a summary.

set -u
OUT="${OUT:-/home/tito/code/monadical/greyproxy/docs/screenshots}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CMP="$SCRIPT_DIR/compare.py"

SECTIONS=(
  "colors"
  "typo"
  "btn-variants"
  "btn-sizes"
  "btn-states"
  "icon-buttons"
  "btn-with-icons"
  "badges-core"
  "badges-tag"
  "badges-semantic"
  "badges-channel"
  "badges-muted"
  "inputs"
  "select"
  "checkboxes-switches"
  "tabs"
  "toggle-group"
  "tooltips"
  "sample-form"
  "settings-card"
  "header"
  "footer"
)

printf "%-25s %-12s %-12s %s\n" "section" "similarity" "differing" "notes"
printf "%-25s %-12s %-12s %s\n" "-------" "----------" "---------" "-----"

fail=0
for s in "${SECTIONS[@]}"; do
  r="$OUT/$s-react.webp"
  h="$OUT/$s-htmx.webp"
  d="$OUT/$s-diff.webp"
  if [ ! -f "$r" ] || [ ! -f "$h" ]; then
    printf "%-25s %-12s %-12s %s\n" "$s" "-" "-" "missing ($([ ! -f "$r" ] && echo react) $([ ! -f "$h" ] && echo htmx))"
    continue
  fi
  line=$(python3 "$CMP" "$r" "$h" --out "$d" 2>&1 | tail -1)
  # "  similarity = 99.97%  (393 / 1436512 pixels differ > 12)"
  sim=$(echo "$line" | sed -nE 's/.*similarity = ([0-9.]+)%.*/\1/p')
  diff=$(echo "$line" | sed -nE 's/.*\(([0-9]+) \/ .*/\1/p')
  # Threshold: 99.0%. Residual diffs under this threshold are driven by:
  #   - font sub-pixel anti-aliasing (~0.03%)
  #   - sticky-header overlay differences in Charlotte's selector screenshot
  #     when element rects happen to land at different viewport Y positions
  #     between React and HTMX (still has the same CSS, just different scroll).
  if awk "BEGIN{exit !($sim>=99.0)}"; then
    marker=PASS
  else
    marker=FAIL
    fail=1
  fi
  printf "%-25s %-12s %-12s %s\n" "$s" "${sim}%" "$diff" "$marker"
done

exit $fail
