#!/usr/bin/env bash
set -euo pipefail

if [ -x "./venv/bin/python" ]; then
  VENV_PY="./venv/bin/python"
elif command -v python3 >/dev/null 2>&1; then
  VENV_PY="python3"
else
  VENV_PY="python"
fi

DSN_CANDIDATES=()
if [ -n "${ORACLE_LOCAL_DSN:-}" ]; then
  DSN_CANDIDATES+=("${ORACLE_LOCAL_DSN}")
fi
DSN_CANDIDATES+=("127.0.0.1:1521/XEPDB1" "oracle18c:1521/XEPDB1" "mqapilc_oracle18c:1521/XEPDB1")
API_URL=${API_URL:-"http://localhost:8000"}

echo "[1/4] Aguardando Oracle..."
DSN_HOST=""
for candidate in "${DSN_CANDIDATES[@]}"; do
  echo "  Testando ${candidate}..."
  if $VENV_PY - <<PY >/dev/null 2>&1
import cx_Oracle
conn=cx_Oracle.connect("local123","local123","${candidate}")
cur=conn.cursor();cur.execute("select 1 from dual");cur.fetchone()
cur.close();conn.close()
PY
  then
    DSN_HOST="${candidate}"
    break
  fi
  sleep 2
done

if [ -z "$DSN_HOST" ]; then
  echo "ERRO: nao foi possivel conectar ao Oracle em nenhum dos DSN candidatos."
  exit 1
fi

echo "Oracle OK em ${DSN_HOST}."

echo "[2/4] Conferindo contagem atual..."
COUNT=$($VENV_PY - <<PY
import cx_Oracle
conn=cx_Oracle.connect("local123","local123","${DSN_HOST}")
cur=conn.cursor();cur.execute("select count(*) from tb_ranking_consultor")
print(cur.fetchone()[0])
cur.close();conn.close()
PY
)
echo "  Registros na TB_RANKING_CONSULTOR: ${COUNT}"

if [ "${COUNT}" -eq 0 ]; then
  echo "[3/4] Rodando job de ranking (Blocos A/C/D)..."
  curl -s -X POST "${API_URL}/api/v1/ranking/processar?limpar=false" >/dev/null
  while true; do
    STATUS=$(curl -s "${API_URL}/api/v1/ranking/status")
    running=$($VENV_PY - <<'PY'
import os, json
data=json.loads(os.environ["STATUS"])
print(data.get("running", False))
PY
STATUS="$STATUS")
    echo "  Status: ${STATUS}"
    if [ "$running" != "True" ] && [ "$running" != "true" ]; then
      break
    fi
    sleep 20
  done
else
  echo "[3/4] Tabela ja possui dados. Pulando processamento."
fi

echo "[4/4] Contagens finais:"
$VENV_PY - <<PY
import cx_Oracle
conn=cx_Oracle.connect("local123","local123","${DSN_HOST}")
cur=conn.cursor()
cur.execute("select count(*) from tb_ranking_consultor"); print("total",cur.fetchone()[0])
cur.execute("select count(*) from tb_ranking_consultor where componente_a>0"); print("Bloco A>0",cur.fetchone()[0])
cur.execute("select count(*) from tb_ranking_consultor where componente_c>0"); print("Bloco C>0",cur.fetchone()[0])
cur.execute("select count(*) from tb_ranking_consultor where componente_d>0"); print("Bloco D>0",cur.fetchone()[0])
cur.execute("select max(pontuacao_total) from tb_ranking_consultor"); print("max total",cur.fetchone()[0])
cur.close();conn.close()
PY
echo "Pronto."
