#!/bin/bash
# ============================================================
# SPC-PUSH - Deploy staging (auto-suffisant)
# Copie et execute par le pipeline Bitbucket
# ============================================================
set -e

DEPLOY_ROOT="/home/ceterisprime/public_html/app/connect"
SERVICE_DIR="$DEPLOY_ROOT/spc-push"
GIT_BRANCH="master"
REPO_SLUG="spc-push"

# Detecter Python 3
PYTHON_BIN="python3"
for py in python3.12 python3.11 python3.10 python3.9; do
    if command -v "$py" &>/dev/null; then PYTHON_BIN="$py"; break; fi
done

# Git URL (auth via env vars du pipeline)
GIT_URL="https://bitbucket.org/alcyonpartners/$REPO_SLUG.git"
if [ -n "$GIT_USER" ] && [ -n "$GIT_TOKEN" ]; then
    GIT_URL="https://$GIT_USER:$GIT_TOKEN@bitbucket.org/alcyonpartners/$REPO_SLUG.git"
fi

echo "[DEPLOY] ========== Deploiement SPC-PUSH (staging) =========="

mkdir -p "$SERVICE_DIR"

# Reparer repo git corrompu
if [ -d "$SERVICE_DIR/.git" ] && ! git -C "$SERVICE_DIR" rev-parse --git-dir >/dev/null 2>&1; then
    echo "[WARN] Repo git corrompu, re-clone..."
    rm -rf "$SERVICE_DIR"
    mkdir -p "$SERVICE_DIR"
fi

# Clone ou pull
if [ ! -d "$SERVICE_DIR/.git" ]; then
    echo "[INFO] Premier deploiement: clone..."
    git clone --branch "$GIT_BRANCH" "$GIT_URL" "$SERVICE_DIR"
else
    cd "$SERVICE_DIR"
    [ -n "$GIT_USER" ] && git remote set-url origin "$GIT_URL"
    echo "[INFO] Mise a jour du code..."
    git fetch origin
    git reset --hard "origin/$GIT_BRANCH"
    git remote set-url origin "https://bitbucket.org/alcyonpartners/$REPO_SLUG.git" 2>/dev/null || true
fi

cd "$SERVICE_DIR"

# Arreter gunicorn existant (via PID file, sans sudo)
PIDFILE="$SERVICE_DIR/logs/gunicorn.pid"
if [ -f "$PIDFILE" ]; then
    PID=$(cat "$PIDFILE" 2>/dev/null)
    if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
        echo "[INFO] Arret de gunicorn spc-push (PID $PID)..."
        kill "$PID" 2>/dev/null
        for i in $(seq 1 10); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
        kill -9 "$PID" 2>/dev/null || true
    fi
    rm -f "$PIDFILE"
fi

# Installer dependances Python
echo "[INFO] Installation Python ($PYTHON_BIN)..."
if [ -d "venv" ] && [ ! -f "venv/bin/activate" ]; then rm -rf venv; fi
if [ ! -d "venv" ]; then
    $PYTHON_BIN -m venv venv || { echo "[ERROR] venv echoue"; exit 1; }
fi
source venv/bin/activate
pip install --upgrade pip --quiet
pip install -r requirements.txt --quiet
deactivate

# Dossiers necessaires
mkdir -p logs traces

# .env.staging -> .env
[ -f ".env.staging" ] && cp .env.staging .env && echo "[INFO] .env.staging applique"

# Demarrer gunicorn en daemon (sans sudo, 1 worker gthread 4 threads)
echo "[INFO] Demarrage gunicorn spc-push (port 5200 staging)..."
source venv/bin/activate
gunicorn \
    --bind 127.0.0.1:5200 \
    --worker-class gthread \
    --workers 1 \
    --threads 4 \
    --timeout 600 \
    --pid logs/gunicorn.pid \
    --access-logfile logs/gunicorn_access.log \
    --error-logfile logs/gunicorn_error.log \
    --log-level info \
    --daemon \
    "app:create_app()"
deactivate

if [ -f "logs/gunicorn.pid" ]; then
    echo "[INFO] Gunicorn demarre (PID $(cat logs/gunicorn.pid))"
else
    echo "[WARN] PID file non trouve - verifier logs/gunicorn_error.log"
fi

# Health check
sleep 5
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:5200/api/v1/health" --max-time 15 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ]; then
    echo "[INFO] spc-push OK (HTTP $HTTP_CODE)"
else
    echo "[WARN] spc-push health check: HTTP $HTTP_CODE"
fi

echo "[DEPLOY] ========== SPC-PUSH deploye avec succes =========="
