#!/usr/bin/env bash
# time-free-tools.sh: capture one URL with several free tools, 3 runs each, and print CSV.
# Needs: curl, node (for npx playwright), python3, and Google Chrome for the Chrome row.
set -euo pipefail

TARGET="${1:-https://example.com}"
CHROME="${CHROME:-/Applications/Google Chrome.app/Contents/MacOS/Google Chrome}"
OUT="$(mktemp -d)"
ENC=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$TARGET")

now_ms() { python3 -c 'import time; print(int(time.time() * 1000))'; }
dims() { python3 - "$1" <<'PY'
import struct, sys
d = open(sys.argv[1], 'rb').read(24)
print(f"{struct.unpack('>I', d[16:20])[0]}x{struct.unpack('>I', d[20:24])[0]}" if d[:4] == b'\x89PNG' else 'n/a')
PY
}
row() { echo "$1,$2,$3,$(wc -c < "$4" | tr -d ' '),$(dims "$4")"; }

echo "tool,run,ms,bytes,dimensions"
for run in 1 2 3; do
  f="$OUT/chrome-$run.png"; t=$(now_ms)
  "$CHROME" --headless --hide-scrollbars --window-size=1280,800 \
    --blink-settings=preferredColorScheme=1 --screenshot="$f" "$TARGET" >/dev/null 2>&1
  row chrome-cli "$run" $(( $(now_ms) - t )) "$f"

  f="$OUT/pw-$run.png"; t=$(now_ms)
  npx --no-install playwright screenshot --viewport-size=1280,800 "$TARGET" "$f" >/dev/null
  row playwright-cli "$run" $(( $(now_ms) - t )) "$f"

  f="$OUT/thum-$run.png"; t=$(now_ms)
  curl -sfL -o "$f" "https://image.thum.io/get/width/1280/$TARGET"
  row thum.io "$run" $(( $(now_ms) - t )) "$f"

  f="$OUT/microlink-$run.png"; t=$(now_ms)
  img=$(curl -sf "https://api.microlink.io/?url=$ENC&screenshot=true&meta=false" \
    | python3 -c 'import json, sys; print(json.load(sys.stdin)["data"]["screenshot"]["url"])')
  curl -sf -o "$f" "$img"   # the API returns JSON; the image is a second download
  row microlink "$run" $(( $(now_ms) - t )) "$f"
done
echo "files kept in $OUT" >&2
