#!/usr/bin/env bash
# CNPERP unattended auto-update (Linux / macOS local servers)
# Usage: ./auto_update.sh [branch]
set -euo pipefail

BRANCH="${1:-main}"
APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG_DIR="${APP_ROOT}/logs"
LOG_FILE="${LOG_DIR}/auto_update.log"
LOCK_FILE="${LOG_DIR}/auto_update.lock"
VENV_PY="${APP_ROOT}/.venv/bin/python"
VERSION_FILE="${APP_ROOT}/version.txt"
MIGRATIONS_DIR="${APP_ROOT}/migrations"
SERVICE_NAME="${CNPERP_SERVICE_NAME:-cnperp}"

mkdir -p "$LOG_DIR"

log() {
  local level="$1"
  shift
  local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*"
  echo "$msg" | tee -a "$LOG_FILE"
}

cleanup_lock() {
  rm -f "$LOCK_FILE"
}

trap cleanup_lock EXIT

cd "$APP_ROOT"

if [[ ! -d .git ]]; then
  log ERROR "Not a git repository at $APP_ROOT"
  exit 1
fi

if [[ ! -x "$VENV_PY" ]]; then
  log ERROR "Python venv not found at $VENV_PY"
  exit 1
fi

log INFO "════════════════════════════════════════"
log INFO "CNPERP Auto-Update Started"
log INFO "App root : $APP_ROOT"
log INFO "Branch   : $BRANCH"
log INFO "Version  : $(cat "$VERSION_FILE" 2>/dev/null || echo 0.0.0)"
log INFO "════════════════════════════════════════"

# 1 — backup
log INFO "Step 1/6 — Creating pre-update backup..."
if "$VENV_PY" -c "
from app.services.backup_service import BackupService
from app.core.database import SessionLocal
db = SessionLocal()
try:
    BackupService(db).create_backup('pre_update')
    print('ok')
finally:
    db.close()
" >>"$LOG_FILE" 2>&1; then
  log SUCCESS "Backup completed"
else
  log WARNING "Backup failed (non-fatal)"
fi

# 2 — stash
log INFO "Step 2/6 — Stashing local changes..."
git stash push -m "Auto-stash before update $(date '+%F %T')" >>"$LOG_FILE" 2>&1 || true

# 3 — fetch
log INFO "Step 3/6 — Fetching origin/$BRANCH..."
git fetch origin >>"$LOG_FILE" 2>&1

mapfile -t PENDING < <(git log "HEAD..origin/$BRANCH" --oneline --no-color 2>/dev/null || true)
if [[ ${#PENDING[@]} -eq 0 ]]; then
  log INFO "Already on latest — nothing to pull."
  log SUCCESS "Auto-update completed (no changes)"
  exit 0
fi

log INFO "${#PENDING[@]} new commit(s) to pull:"
for line in "${PENDING[@]}"; do
  log INFO "  + $line"
done

# 4 — pull
log INFO "Step 4/6 — Pulling latest code..."
if ! git pull origin "$BRANCH" >>"$LOG_FILE" 2>&1; then
  log ERROR "git pull failed"
  exit 1
fi
log SUCCESS "Code updated."

# 5 — dependencies
log INFO "Step 5/6 — Updating dependencies..."
if ! "$VENV_PY" -m pip install -r "${APP_ROOT}/requirements.txt" --upgrade --quiet >>"$LOG_FILE" 2>&1; then
  log ERROR "pip install failed"
  exit 1
fi
log SUCCESS "Dependencies up to date."

# 5b — migrations
log INFO "Step 5b — Running migrations..."
if [[ -x "${APP_ROOT}/deploy/hetzner/run-migrations.sh" ]]; then
  if ! bash "${APP_ROOT}/deploy/hetzner/run-migrations.sh" "$APP_ROOT" >>"$LOG_FILE" 2>&1; then
    log WARNING "run-migrations.sh reported warnings (continuing)"
  else
    log SUCCESS "Migrations completed."
  fi
elif [[ -d "$MIGRATIONS_DIR" ]]; then
  shopt -s nullglob
  for m in "$MIGRATIONS_DIR"/*.py; do
    base=$(basename "$m")
    [[ "$base" == __* ]] && continue
    log INFO "  Running: $base"
    if ! "$VENV_PY" "$m" >>"$LOG_FILE" 2>&1; then
      log WARNING "  Migration warning: $base"
    else
      log SUCCESS "  Done: $base"
    fi
  done
  shopt -u nullglob
fi

# 6 — restart
log INFO "Step 6/6 — Restarting service..."
if command -v systemctl >/dev/null 2>&1 && systemctl list-units --full -all 2>/dev/null | grep -Fq "${SERVICE_NAME}.service"; then
  if sudo systemctl restart "$SERVICE_NAME" >>"$LOG_FILE" 2>&1; then
    sleep 2
    if systemctl is-active --quiet "$SERVICE_NAME"; then
      log SUCCESS "Service $SERVICE_NAME restarted."
    else
      log ERROR "Service $SERVICE_NAME did not become active."
      exit 1
    fi
  else
    log WARNING "systemctl restart failed — restart manually."
  fi
else
  log WARNING "No systemd service '$SERVICE_NAME' — restart uvicorn manually."
  pkill -f "uvicorn app.main:app" 2>/dev/null || true
fi

LAST=$(git log -1 --pretty=format:'%h — %s')
log SUCCESS "════════════════════════════════════════"
log SUCCESS "Auto-update completed successfully!"
log INFO "  Last commit: $LAST"
log INFO "  Version    : $(cat "$VERSION_FILE" 2>/dev/null || echo unknown)"
log SUCCESS "════════════════════════════════════════"
