#!/usr/bin/env bash
# Shard the kommune tour across N parallel Playwright workers.
# Each worker launches its own Chromium, logs into Placepoint (or copies
# the user's Chrome profile), and runs the tour for a non-overlapping
# slice of the kommune list.
#
# Usage:
#   ./scripts/tour/run-kommune-shards.sh <num-workers> <slug1,slug2,...>
#
# Or with all slugs that have an .mdx but no kommune.png yet (resume mode):
#   ./scripts/tour/run-kommune-shards.sh <num-workers> --missing
#
# Or all kommuner in the registry:
#   ./scripts/tour/run-kommune-shards.sh <num-workers> --all
#
# Output logs land in /tmp/kommune-shard-<N>.log. Tail them all with:
#   tail -F /tmp/kommune-shard-*.log
set -euo pipefail

WORKERS="${1:-10}"
MODE="${2:-}"

cd "$(dirname "$0")/../.."
source .env

# Resolve the slug list.
case "$MODE" in
  --all)
    SLUGS=$(npx tsx -e 'import {KOMMUNER} from "./scripts/tour/data/kommuner"; console.log(KOMMUNER.map(k => k.slug).join("\n"))')
    ;;
  --missing)
    SLUGS=""
    for d in sales/kommune/*-meta.json; do
      slug=$(basename "$d" -meta.json)
      if [[ ! -f "sales/kommune/img/$slug/kommune.png" ]]; then
        SLUGS+="${slug}"$'\n'
      fi
    done
    ;;
  '')
    echo "usage: $0 <num-workers> --all | --missing | <slug1,slug2,...>" >&2
    exit 2
    ;;
  *)
    SLUGS=$(echo "$MODE" | tr ',' '\n')
    ;;
esac

# Strip empties + dedupe.
SLUGS=$(echo "$SLUGS" | awk 'NF' | sort -u)
TOTAL=$(echo "$SLUGS" | wc -l | tr -d ' ')
echo "==> Sharding $TOTAL kommuner across $WORKERS workers"

# Build per-shard slug list (round-robin so adjacent slugs end up on
# different workers - that spreads any "neighbor" co-ownership across
# shards, reducing duplicate Chromium tabs hitting the same property).
# Stagger worker startup so 30 Chromiums don't all hit Azure B2C in
# the same instant - that triggers selector timeouts and the section
# fails before any kommune is captured.
STAGGER_SECS="${STAGGER:-4}"
for i in $(seq 0 $((WORKERS - 1))); do
  shard=$(echo "$SLUGS" | awk -v n="$WORKERS" -v r="$i" 'NR%n==r')
  if [[ -z "$shard" ]]; then continue; fi
  csv=$(echo "$shard" | paste -sd, -)
  count=$(echo "$shard" | wc -l | tr -d ' ')
  log="/tmp/kommune-shard-${i}.log"
  echo "  worker $i ($count slugs) → $log"
  (
    sleep $((i * STAGGER_SECS))
    cd scripts
    WORKER_INDEX="$i" KOMMUNE_SLUGS="$csv" SKIP_KARTLAG="${SKIP_KARTLAG:-}" ONLY_MATCHING_ZOOM="${ONLY_MATCHING_ZOOM:-}" ONLY_KARTLAG="${ONLY_KARTLAG:-}" npm run tour:section kommune
  ) > "$log" 2>&1 &
done

# Focus-restorer disabled - the activate-Cursor loop was itself a
# focus-stealer (it pulled Cursor to the front every 4 seconds even
# when the user had moved on to another app). Best to accept that
# Chromium grabs focus once per worker launch and leave the user in
# control of where focus goes after.

wait
echo "==> All $WORKERS workers finished"
