#!/bin/bash
# CNSC — Consiliul Național de Soluționare a Contestațiilor.
# Walks portal.cnsc.ro/decizii.html (~30K decisions across ~617 pages of 50).
#
# Mirrors scrape-anre.sh / scrape-aaas.sh pattern: Infisical Machine Identity
# → env-file → docker run --env-file (NEVER -e $VAR), file deleted post-launch.
#
# Idempotent: ON CONFLICT (decision_no, decision_year) DO UPDATE.
# Safe to run from cron daily — only newly-published decisions are inserted,
# the rest are no-op updates of fetched_at.
#
# Env knobs:
#   START_PAGE=1        (default 1; set higher to resume after partial run)
#   MAX_PAGES=0         (default 0 = until totalPages; smaller for smoke test)
#
# Run:
#   sudo MAX_PAGES=2 /opt/vreaudigital/services/seap-scraper/cron/scrape-cnsc.sh
#   sudo /opt/vreaudigital/services/seap-scraper/cron/scrape-cnsc.sh
set -euo pipefail

START_PAGE="${START_PAGE:-1}"
MAX_PAGES="${MAX_PAGES:-0}"
LOG=/var/log/vreaudigital-cnsc.log

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG"; }

log "=== CNSC scrape started (start_page=$START_PAGE max_pages=$MAX_PAGES) ==="

if docker ps --filter name=vreaudigital-cnsc --format '{{.Names}}' | grep -q '^vreaudigital-cnsc$'; then
  log "WARN: vreaudigital-cnsc already running, skipping this tick"
  exit 0
fi
docker rm -f vreaudigital-cnsc 2>/dev/null || true

# ── Fetch DATABASE_URL via Infisical Machine Identity ──
source /opt/vreaudigital/.infisical-mi
TOKEN=$(infisical login --method=universal-auth \
  --domain="$INFISICAL_API_URL" \
  --client-id="$INFISICAL_CLIENT_ID" \
  --client-secret="$INFISICAL_CLIENT_SECRET" \
  --silent --plain)

umask 077
ENVF=$(mktemp /tmp/.vreaudigital-cnsc-env.XXXXXX)
DBURL=$(infisical secrets get DATABASE_URL \
  --domain="$INFISICAL_API_URL" \
  --projectId="$INFISICAL_PROJECT_ID" \
  --env="$INFISICAL_ENV" --path="$INFISICAL_PATH" \
  --token="$TOKEN" --plain --silent)
echo "DATABASE_URL=$DBURL" > "$ENVF"
unset DBURL TOKEN

cd /opt/vreaudigital/services/seap-scraper

if [ ! -d node_modules/tsx ]; then
  log "Installing seap-scraper deps..."
  docker run --rm -v "$(pwd):/work" -w /work --user "$(id -u):$(id -g)" \
    node:22-alpine npm install --omit=optional 2>&1 | tee -a "$LOG" >/dev/null
fi

EXTRA_ARGS="--start-page=$START_PAGE"
[ "$MAX_PAGES" -gt 0 ] 2>/dev/null && EXTRA_ARGS="$EXTRA_ARGS --max-pages=$MAX_PAGES"

CID=$(docker run -d \
  --name vreaudigital-cnsc \
  --network host \
  --env-file "$ENVF" \
  -v "$(pwd):/work" \
  -w /work \
  --user "$(id -u):$(id -g)" \
  --restart no \
  node:22-alpine \
  npx tsx src/scrape-cnsc.ts $EXTRA_ARGS)
log "container started: $CID"

sleep 3
rm -f "$ENVF"
log "envfile cleaned"

docker wait vreaudigital-cnsc >/dev/null
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' vreaudigital-cnsc 2>/dev/null || echo "?")
docker logs vreaudigital-cnsc 2>&1 | tail -25 | tee -a "$LOG"
log "=== CNSC scrape done (exit=$EXIT_CODE) ==="

exit "$EXIT_CODE"
