#!/bin/bash
# ============================================================
# Deploy Token Broker — systemd service + Docker PG
# ============================================================
set -euo pipefail

APP_DIR="/home/h3r7/turf_saas"
SERVICE_NAME="token-broker"
PID_FILE="/tmp/token_broker.pid"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo "[$(date -Iseconds)] === Deploying Token Broker ==="

# Step 1: Backup current code
echo "[$(date -Iseconds)] Backing up current code..."
mkdir -p /home/h3r7/backups/token-broker
cp "${APP_DIR}/services/token-broker/token_broker_api.py" \
   "/home/h3r7/backups/token-broker/token_broker_api_${TIMESTAMP}.py"

# Step 2: Ensure Docker PG is running
echo "[$(date -Iseconds)] Ensuring PostgreSQL container..."
if ! docker inspect token-broker-db >/dev/null 2>&1; then
    echo "Creating PG container..."
    docker run -d \
        --name token-broker-db \
        --restart unless-stopped \
        -e POSTGRES_DB=token_broker \
        -e POSTGRES_USER=token_broker \
        -e POSTGRES_PASSWORD="${TOKEN_BROKER_DB_PASSWORD}" \
        -v token-broker-pgdata:/var/lib/postgresql/data \
        -v "${APP_DIR}/infra/postgres/token_broker_init.sql:/docker-entrypoint-initdb.d/init.sql:ro" \
        -p 127.0.0.1:5434:5432 \
        postgres:16-alpine
elif ! docker ps --filter name=token-broker-db --format '{{.Status}}' | grep -q Up; then
    echo "Starting existing PG container..."
    docker start token-broker-db
else
    echo "PG container already running."
fi

# Wait for PG readiness
echo "[$(date -Iseconds)] Waiting for PG to be ready..."
for i in $(seq 1 20); do
    if docker exec token-broker-db pg_isready -U token_broker -d token_broker >/dev/null 2>&1; then
        echo "PG ready."
        break
    fi
    sleep 2
done

# Step 3: Ensure psycopg2-binary is installed
echo "[$(date -Iseconds)] Checking Python deps..."
source "${APP_DIR}/venv/bin/activate"
pip install -q psycopg2-binary PyJWT flask-cors python-dotenv gunicorn 2>/dev/null || true

# Step 4: Stop current service
echo "[$(date -Iseconds)] Stopping current service..."
if systemctl is-active --quiet ${SERVICE_NAME} 2>/dev/null; then
    systemctl stop ${SERVICE_NAME}
elif [ -f "$PID_FILE" ] && kill -0 $(cat "$PID_FILE") 2>/dev/null; then
    kill $(cat "$PID_FILE") 2>/dev/null || true
fi
sleep 2

# Step 5: Copy systemd unit and start
echo "[$(date -Iseconds)] Starting via systemd..."
cp "${APP_DIR}/services/token-broker/token-broker.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable ${SERVICE_NAME}
systemctl start ${SERVICE_NAME}

# Wait for startup
sleep 3

# Step 6: Health check
echo "[$(date -Iseconds)] Running health check..."
HEALTH=$(curl -s http://127.0.0.1:8783/health 2>/dev/null || echo '{"status":"failed"}')
STATUS=$(echo "$HEALTH" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','unknown'))" 2>/dev/null || echo "unknown")

if [ "$STATUS" = "ok" ]; then
    echo "[$(date -Iseconds)] ✅ Health check passed: ${HEALTH}"
    echo "[$(date -Iseconds)] === Token Broker deploy SUCCESS ==="
else
    echo "[$(date -Iseconds)] ❌ Health check failed: ${HEALTH}"
    echo "[$(date -Iseconds)] === Token Broker deploy FAILED ==="
    exit 1
fi

# Step 7: Clean old backups (keep last 30)
find /home/h3r7/backups/token-broker -name "*.py" -mtime +30 -delete
