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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

POOL_DB_NAME="${POOL_DB_NAME:-vexonpool}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_BIN_DIR="${VEX_BIN_DIR:-$VEX_POOL_ROOT/bin}"
VEX_WEB_DIR="${VEX_WEB_DIR:-/opt/vexon-pool/web}"
VEX_MIN_PAYOUT="${VEX_MIN_PAYOUT:-0.001}"
VEX_START_WALLET="${VEX_START_WALLET:-0}"
VEX_WALLET_RPC_PORT="${VEX_WALLET_RPC_PORT:-18557}"
VEX_WALLET_RPC_USER="${VEX_WALLET_RPC_USER:-}"
VEX_WALLET_RPC_PASSWORD="${VEX_WALLET_RPC_PASSWORD:-}"
VEX_WALLET_PASSPHRASE="${VEX_WALLET_PASSPHRASE:-}"
VEX_PAYOUT_HOUR="${VEX_PAYOUT_HOUR:-8}"
VEX_PAYOUT_MINUTE="${VEX_PAYOUT_MINUTE:-0}"
VEX_PAYOUT_TIMEZONE="${VEX_PAYOUT_TIMEZONE:-Asia/Shanghai}"
VEX_PAYOUT_SCHEDULE_LABEL="${VEX_PAYOUT_SCHEDULE_LABEL:-Daily at 08:00 CST}"

if ! command -v mysql >/dev/null 2>&1; then
  echo "mysql client is required." >&2
  exit 1
fi

echo "== payout policy =="
echo "Minimum payout: ${VEX_MIN_PAYOUT} VEX"
echo "Schedule: ${VEX_PAYOUT_SCHEDULE_LABEL}"
echo "Timezone: ${VEX_PAYOUT_TIMEZONE}"
echo "Wallet automation: VEX_START_WALLET=${VEX_START_WALLET}"
if [[ "$VEX_START_WALLET" == "1" ]]; then
  [[ -n "$VEX_WALLET_PASSPHRASE" ]] && echo "Wallet restart passphrase: configured" || echo "Wallet restart passphrase: missing"
fi
if date -d "today ${VEX_PAYOUT_HOUR}:${VEX_PAYOUT_MINUTE}" >/dev/null 2>&1; then
  next="$(TZ="$VEX_PAYOUT_TIMEZONE" date -d "today ${VEX_PAYOUT_HOUR}:${VEX_PAYOUT_MINUTE}" '+%Y-%m-%d %H:%M:%S %Z')"
  now_epoch="$(date +%s)"
  next_epoch="$(TZ="$VEX_PAYOUT_TIMEZONE" date -d "today ${VEX_PAYOUT_HOUR}:${VEX_PAYOUT_MINUTE}" '+%s')"
  if (( next_epoch <= now_epoch )); then
    next="$(TZ="$VEX_PAYOUT_TIMEZONE" date -d "tomorrow ${VEX_PAYOUT_HOUR}:${VEX_PAYOUT_MINUTE}" '+%Y-%m-%d %H:%M:%S %Z')"
  fi
  echo "Next scheduled window: $next"
fi

if [[ "$VEX_START_WALLET" == "1" && -x "$VEX_BIN_DIR/vexonctl" && -n "$VEX_WALLET_RPC_USER" && -n "$VEX_WALLET_RPC_PASSWORD" ]]; then
  wallet_balance="$("$VEX_BIN_DIR/vexonctl" --wallet --notls --rpcserver "127.0.0.1:${VEX_WALLET_RPC_PORT}" -u "$VEX_WALLET_RPC_USER" -P "$VEX_WALLET_RPC_PASSWORD" getbalance 2>/dev/null || true)"
  if [[ -n "$wallet_balance" ]]; then
    echo "Wallet RPC balance: $wallet_balance"
  else
    echo "Wallet RPC balance: unavailable"
  fi
else
  echo "Wallet RPC balance: skipped until VEX_START_WALLET=1"
fi

echo
echo "== coin payout config =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT id,name,symbol,enable,auto_ready,payout_min,mature_blocks,txfee,master_wallet
FROM coins
WHERE symbol='VEX'\G
" 2>/dev/null || true

echo
echo "== payable accounts =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT A.id,A.username AS address,A.balance,C.payout_min
FROM accounts A
JOIN coins C ON C.id=A.coinid
WHERE C.symbol='VEX' AND A.balance >= ${VEX_MIN_PAYOUT}
ORDER BY A.balance DESC
LIMIT 50;
"

echo
echo "== recent block lifecycle =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT category,COUNT(*) AS rows_count,FROM_UNIXTIME(MAX(time)) AS latest
FROM blocks
WHERE coin_id=(SELECT id FROM coins WHERE symbol='VEX' LIMIT 1)
GROUP BY category
ORDER BY rows_count DESC;
" 2>/dev/null || true

echo
echo "== immature and mature earnings =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT status,COUNT(*) AS rows_count,SUM(amount) AS amount
FROM earnings
WHERE coinid=(SELECT id FROM coins WHERE symbol='VEX' LIMIT 1)
GROUP BY status
ORDER BY status;
" 2>/dev/null || true

echo
echo "== recent payouts =="
mysql -uroot "$POOL_DB_NAME" -e "
SELECT P.id,A.username AS address,P.amount,P.completed,P.tx,P.errmsg,FROM_UNIXTIME(P.time) AS t
FROM payouts P
JOIN accounts A ON A.id=P.account_id
JOIN coins C ON C.id=A.coinid
WHERE C.symbol='VEX'
ORDER BY P.id DESC
LIMIT 20;
" 2>/dev/null || true

echo
echo "== backend payout trigger =="
echo "Automatic payments run inside ${VEX_WEB_DIR}/main.sh through runconsole.php cronjob/run."
echo "To manually let the backend evaluate whether the payout window is due:"
echo "  cd ${VEX_WEB_DIR} && php -d max_execution_time=300 runconsole.php cronjob/run"
