#!/bin/bash
# ANAF lista albă — LIVE scraper wrapper (JCaptcha via 2captcha).
#
# Mirrors scrape-anaf-datornici-live.sh exactly. Difference is endpoint
# (/restante/listaalba.xhtml) and target table (anaf.lista_alba — 3 cols/row).
#
# Infisical Machine Identity → env-file (DATABASE_URL + TWOCAPTCHA_KEY) →
# docker run --env-file (NEVER -e $VAR), file deleted post-launch.
#
# Idempotent (UPSERT on cui+publication_date). Designed to be triggered
# quarterly by vreaudigital-anaf-lista-alba.timer (offset +1h vs datornici).
#
# Env knobs:
#   DRY_RUN=1                 — parse-only, zero spend, zero DB writes.
#
# Run:
#   sudo /opt/vreaudigital/services/seap-scraper/cron/scrape-anaf-lista-alba.sh
#   sudo DRY_RUN=1 /opt/vreaudigital/services/seap-scraper/cron/scrape-anaf-lista-alba.sh

set -euo pipefail

DRY_RUN="${DRY_RUN:-0}"
LOG=/var/log/vreaudigital-anaf-lista-alba.log

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

log "=== ANAF lista_alba LIVE scrape started (dry_run=$DRY_RUN) ==="

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

# ── Fetch DATABASE_URL + TWOCAPTCHA_KEY 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-anaf-lista-alba-live-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

if [ "$DRY_RUN" != "1" ]; then
  for try_path in "$INFISICAL_PATH" "/"; do
    TWOCAPTCHA_KEY=$(infisical secrets get TWOCAPTCHA_KEY \
      --domain="$INFISICAL_API_URL" \
      --projectId="$INFISICAL_PROJECT_ID" \
      --env="$INFISICAL_ENV" --path="$try_path" \
      --token="$TOKEN" --plain --silent 2>/dev/null || true)
    [ -n "${TWOCAPTCHA_KEY:-}" ] && break
  done
  if [ -z "${TWOCAPTCHA_KEY:-}" ]; then
    log "ERROR: TWOCAPTCHA_KEY missing in Infisical (checked $INFISICAL_PATH + /)"
    rm -f "$ENVF"
    exit 3
  fi
  echo "TWOCAPTCHA_KEY=$TWOCAPTCHA_KEY" >> "$ENVF"
  unset TWOCAPTCHA_KEY
fi
unset TOKEN

echo "DRY_RUN=$DRY_RUN" >> "$ENVF"
echo "ANAF_LISTA_ALBA_LOG=/work/.log/anaf-lista-alba.log" >> "$ENVF"

cd /opt/vreaudigital/services/seap-scraper

mkdir -p .log

CID=$(docker run -d \
  --name vreaudigital-anaf-lista-alba-live \
  --network host \
  --env-file "$ENVF" \
  -v "$(pwd):/work" \
  -w /work \
  --user "$(id -u):$(id -g)" \
  --restart no \
  python:3.12-slim \
  bash -c "pip install --quiet --no-cache-dir psycopg2-binary requests && python3 scrapers/anaf_lista_alba/scraper.py")
log "container started: $CID"

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

docker wait vreaudigital-anaf-lista-alba-live >/dev/null
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' vreaudigital-anaf-lista-alba-live 2>/dev/null || echo "?")
docker logs vreaudigital-anaf-lista-alba-live 2>&1 | tail -30 | tee -a "$LOG"
log "=== ANAF lista_alba LIVE scrape done (exit=$EXIT_CODE) ==="

exit "$EXIT_CODE"
