#!/bin/bash
# Transparent renders of the OS mockups: page background stripped, card shadows/gradients
# kept (they land in the alpha channel). Auto-expands the canvas when the shadow clips.
# Usage: render-alpha.sh [file.html ...]   (default: all matrix + home alphas)
set -u
cd "$(dirname "$0")/.."
HS=$(ls -d ~/Library/Caches/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-mac-*/chrome-headless-shell | tail -1)
mkdir -p _renders/alpha

shoot() { # html out W H extraW extraH
  local f=$1 out=$2 W=$3 H=$4 EW=$5 EH=$6
  local dir base tmp
  dir=$(cd "$(dirname "$f")" && pwd); base=$(basename "$f")
  tmp="$dir/.alpha-tmp-$base"
  { cat "$dir/$base"; printf '<style>html,body{background:transparent !important;'; \
    [ "$EW" -gt 0 ] && printf 'width:%dpx !important;height:%dpx !important;' $((W+EW)) $((H+EH)); \
    printf '}.scene{background:transparent !important}.scene::before{display:none !important}</style>'; } > "$tmp"
  rm -f "$out"
  "$HS" --headless --disable-gpu --screenshot="$out" --window-size=$((W+EW)),$((H+EH)) \
    --hide-scrollbars --force-device-scale-factor=1 --default-background-color=00000000 \
    "file://$tmp" 2>/dev/null
  rm -f "$tmp"
  [ -s "$out" ]
}

edge_clipped() { # returns 0 if content touches canvas edge
  python3 - "$1" <<'PY'
import sys
from PIL import Image
im = Image.open(sys.argv[1]).convert('RGBA')
w, h = im.size
px = im.load()
def hit(seq):
    return any(px[x, y][3] > 8 for x, y in seq)
clipped = hit(((x, 0) for x in range(0, w, 3))) or hit(((x, h-1) for x in range(0, w, 3))) \
    or hit(((0, y) for y in range(0, h, 3))) or hit(((w-1, y) for y in range(0, h, 3)))
sys.exit(0 if clipped else 1)
PY
}

files=("$@")
[ ${#files[@]} -eq 0 ] && files=(os-renders/*/*.html)
for f in "${files[@]}"; do
  base=$(basename "$f" .html)
  [ "$base" = "alpha-test" ] && continue
  size=$(grep -oE 'width:\s*[0-9]+px;\s*height:\s*[0-9]+px' "$f" | head -1 | grep -oE '[0-9]+' | paste -sd ' ' -)
  [ -z "$size" ] && { echo "SKIP $base"; continue; }
  W=${size%% *}; H=${size##* }
  out="_renders/alpha/$base-alpha.png"
  ok=""
  for pad in 0 240 480; do
    shoot "$f" "$out" "$W" "$H" "$pad" "$pad" || { echo "FAIL $base"; break; }
    if edge_clipped "$out"; then ok=""; else ok="pad=$pad"; break; fi
  done
  if [ -n "$ok" ]; then echo "OK   $base ($ok)"; else echo "CLIP $base (still touching edge at pad=480)"; fi
done
