#!/bin/bash
# ANRE — Autoritatea Națională de Reglementare în domeniul Energiei.
# Scrapes 4 public registries from portal.anre.ro/PublicLists:
#   electricitate (~5K), gaze (~350), atestat (~10K), electricieni (~100K).
#
# Mirrors scrape-regas.sh / scrape-bugetar.sh pattern: Infisical Machine
# Identity → env-file → docker run --env-file (NEVER -e $VAR), file deleted
# post-launch.
#
# Idempotent (UPSERT on sha1 PK / UNIQUE(nr_autorizare,nume_prenume)).
# Safe to run from cron.
#
# Env knobs:
#   SOURCE=all|electricitate|gaze|atestat|electricieni  (default: all)
#   LIMIT=0                                             (default: 0 = full)
#
# Run:
#   sudo SOURCE=electricitate LIMIT=100 /opt/vreaudigital/services/seap-scraper/cron/scrape-anre.sh
#   sudo /opt/vreaudigital/services/seap-scraper/cron/scrape-anre.sh    # full all sources
set -euo pipefail

SOURCE="${SOURCE:-all}"
LIMIT="${LIMIT:-0}"
LOG=/var/log/vreaudigital-anre.log

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

log "=== ANRE scrape started (source=$SOURCE limit=$LIMIT) ==="

if docker ps --filter name=vreaudigital-anre --format '{{.Names}}' | grep -q '^vreaudigital-anre$'; then
  log "WARN: vreaudigital-anre already running, skipping this tick"
  exit 0
fi
docker rm -f vreaudigital-anre 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-anre-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"
# ANRE portal uses an intermediate CA cert chain that node's bundle doesn't trust.
# Cert is valid (verified OOB via Microsoft-IIS handshake), bypass for this scraper.
echo "NODE_TLS_REJECT_UNAUTHORIZED=0" >> "$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="--source=$SOURCE"
[ "$LIMIT" -gt 0 ] 2>/dev/null && EXTRA_ARGS="$EXTRA_ARGS --limit=$LIMIT"

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

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

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

exit "$EXIT_CODE"
