#!/bin/bash
set -euo pipefail

WAOUW_HOME="/opt/waouw"
LOG_DIR="${LOG_DIR:-/var/log/waouw/updates}"

ts() { date '+%Y-%m-%d %H:%M:%S'; }
write_status() {
  local id="$1"; shift; local json="$1"
  mkdir -p "$LOG_DIR"
  echo "$json" > "$LOG_DIR/$id.json"
}

apply_update() {
  local ZIP="" ID=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --zip) ZIP="$2"; shift 2;;
      --id) ID="$2"; shift 2;;
      *) shift;;
    esac
  done

  [[ -f "$ZIP" ]] || { echo "Archive introuvable: $ZIP"; exit 1; }
  [[ -n "$ID" ]] || ID=$(basename "$ZIP" .zip)

  local RUN_LOG="$LOG_DIR/$ID.log"
  mkdir -p "$LOG_DIR"
  write_status "$ID" "{\"id\":\"$ID\",\"state\":\"running\",\"start_time\":\"$(ts)\",\"log_path\":\"$RUN_LOG\"}"

  # All output goes to the log file AND stderr (for systemd journal)
  exec > >(tee -a "$RUN_LOG") 2>&1

  echo "=== WAOUW UPDATE START $(ts) ==="
  echo "ZIP: $ZIP ($(stat -c%s "$ZIP") bytes)"
  echo "ID: $ID"

  # ── Stage 1: Extract ────────────────────────────────────────────────
  STAGE="/tmp/waouw-update-$ID"
  rm -rf "$STAGE" && mkdir -p "$STAGE"
  unzip -oq "$ZIP" -d "$STAGE" || true
  echo "Extracted to $STAGE"

  # Fix Windows backslash paths (Compress-Archive bug)
  cd "$STAGE"
  {
    find . -name '*\\*' 2>/dev/null | sort -r | while IFS= read -r bad; do
      good=$(echo "$bad" | tr '\\' '/')
      mkdir -p "$(dirname "$good")"
      mv "$bad" "$good" 2>/dev/null || true
    done
  } || true
  find "$STAGE" -type d -empty -delete 2>/dev/null || true
  cd /

  # ── Stage 2: Verify manifest ────────────────────────────────────────
  MANI="$STAGE/manifest.yml"
  if [[ ! -f "$MANI" ]]; then
    echo "FATAL: Manifest manquant dans le package"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"manifest missing\",\"log_path\":\"$RUN_LOG\"}"
    exit 2
  fi
  echo "Manifest OK"

  # ── Stage 2b: Enforce complete package + SHA256 (Ed rule 2026-04-07) ─
  # A package MUST declare itself complete and ship a sha256 of files/.
  # Incremental patches are forbidden (cf feedback_update_system.md).
  if ! grep -qE '^complete:[[:space:]]*true' "$MANI"; then
    echo "FATAL: Le manifest ne déclare pas 'complete: true' — package incrémental refusé"
    echo "       Règle Ed 2026-04-07 : chaque OTA DOIT être complète"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"package not declared complete\",\"log_path\":\"$RUN_LOG\"}"
    exit 2
  fi
  EXPECTED_SHA=$(grep -E '^files_sha256:' "$MANI" | awk '{print $2}' | tr -d '"' | tr -d "'")
  if [[ -z "$EXPECTED_SHA" ]]; then
    echo "FATAL: Le manifest ne contient pas 'files_sha256:' — package non vérifiable"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"manifest missing files_sha256\",\"log_path\":\"$RUN_LOG\"}"
    exit 2
  fi
  ACTUAL_SHA=$(cd "$STAGE/files" && find . -type f -print0 | sort -z | xargs -0 sha256sum | sha256sum | awk '{print $1}')
  if [[ "$EXPECTED_SHA" != "$ACTUAL_SHA" ]]; then
    echo "FATAL: SHA256 mismatch — package corrompu ou tronqué"
    echo "       expected=$EXPECTED_SHA"
    echo "       actual  =$ACTUAL_SHA"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"sha256 mismatch\",\"log_path\":\"$RUN_LOG\"}"
    exit 2
  fi
  echo "Package complet et SHA256 vérifié ($ACTUAL_SHA)"

  # ── Stage 3: Verify files directory exists ──────────────────────────
  if [[ ! -d "$STAGE/files" ]]; then
    echo "FATAL: Dossier files/ manquant dans le package"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"files/ missing\",\"log_path\":\"$RUN_LOG\"}"
    exit 2
  fi

  # Count files to sync
  FILE_COUNT=$(find "$STAGE/files" -type f | wc -l)
  echo "Package contains $FILE_COUNT files"

  # ── Stage 4: Backup .env ────────────────────────────────────────────
  cp "$WAOUW_HOME/DEPLOY/.env" "/tmp/waouw-env-backup-$ID" 2>/dev/null || true
  cp "$WAOUW_HOME/.env" "/tmp/waouw-env-root-backup-$ID" 2>/dev/null || true
  echo ".env backed up"

  # ── Stage 5: Rsync overlay ─────────────────────────────────────────
  rsync -av \
    --exclude='.env' \
    --exclude='PASSWORDS.txt' \
    --exclude='sites-data/' \
    --exclude='*.sqlite' \
    --exclude='*.db' \
    "$STAGE/files/" "$WAOUW_HOME/"
  echo "Files synced (overlay mode, $FILE_COUNT files)"

  # ── Stage 6: Restore .env ──────────────────────────────────────────
  if [[ -f "/tmp/waouw-env-backup-$ID" ]]; then
    cp -f "/tmp/waouw-env-backup-$ID" "$WAOUW_HOME/DEPLOY/.env"
    echo ".env DEPLOY restored"
  fi
  if [[ -f "/tmp/waouw-env-root-backup-$ID" ]]; then
    cp -f "/tmp/waouw-env-root-backup-$ID" "$WAOUW_HOME/.env"
    echo ".env root restored"
  fi

  # ── Stage 7: Fix VERSION.json ──────────────────────────────────────
  if [[ -d "$WAOUW_HOME/VERSION.json" ]]; then
    rm -rf "$WAOUW_HOME/VERSION.json"
  fi
  if [[ -f "$STAGE/files/VERSION.json" ]]; then
    cp -f "$STAGE/files/VERSION.json" "$WAOUW_HOME/VERSION.json"
    echo "VERSION.json updated: $(cat "$WAOUW_HOME/VERSION.json")"
  fi

  # ── Stage 8: Fix permissions ───────────────────────────────────────
  chmod -R a+rX "$WAOUW_HOME/BACKEND/" "$WAOUW_HOME/UI/" 2>/dev/null || true
  echo "Permissions fixed"

  # ── Stage 9: Migrations ────────────────────────────────────────────
  if [[ -d "$STAGE/migrations" ]]; then
    echo "Running migrations..."
    chmod +x "$STAGE/migrations"/* 2>/dev/null || true
    for s in "$STAGE/migrations"/*; do
      [ -f "$s" ] && echo "  Migration: $(basename "$s")" && bash "$s"
    done
  fi

  # ── Stage 10: Traefik config ───────────────────────────────────────
  if [[ -f "$WAOUW_HOME/DEPLOY/traefik/dynamic.yml" ]]; then
    cp -f "$WAOUW_HOME/DEPLOY/traefik/dynamic.yml" /etc/waouw/traefik/dynamic.yml 2>/dev/null || true
    echo "Traefik dynamic.yml updated"
  fi

  # ── Stage 11: Docker build ─────────────────────────────────────────
  echo "Building Docker images (--no-cache)..."
  pushd "$WAOUW_HOME/DEPLOY" >/dev/null

  if ! docker compose build --no-cache backend frontend; then
    echo "FATAL: docker compose build FAILED"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"failed\",\"error\":\"docker build failed\",\"end_time\":\"$(ts)\",\"log_path\":\"$RUN_LOG\"}"
    cp -f "/tmp/waouw-env-backup-$ID" "$WAOUW_HOME/DEPLOY/.env" 2>/dev/null || true
    popd >/dev/null
    exit 3
  fi
  echo "Docker build succeeded"

  # ── Stage 12: Verify new image contains updated files ──────────────
  echo "Verifying new images..."
  if [[ -f "$WAOUW_HOME/BACKEND/app/api/routes.py" ]]; then
    EXPECTED_ROUTERS=$(grep -c 'include_router' "$WAOUW_HOME/BACKEND/app/api/routes.py" || echo 0)
    echo "  routes.py has $EXPECTED_ROUTERS registered routers"
  fi

  # ── Stage 13: Restart containers ───────────────────────────────────
  echo "Restarting containers..."
  docker compose up -d 2>&1 || true
  sleep 10
  docker compose up -d frontend 2>&1 || true
  popd >/dev/null

  # ── Stage 14: Health check ─────────────────────────────────────────
  echo "Waiting for health checks..."
  sleep 15
  BACKEND_OK=$(docker inspect waouw_backend --format '{{.State.Health.Status}}' 2>/dev/null || echo "unknown")
  FRONTEND_OK=$(docker inspect waouw_frontend --format '{{.State.Health.Status}}' 2>/dev/null || echo "unknown")
  echo "Backend health: $BACKEND_OK"
  echo "Frontend health: $FRONTEND_OK"

  if [[ "$BACKEND_OK" != "healthy" ]]; then
    echo "WARNING: Backend not healthy after update"
    write_status "$ID" "{\"id\":\"$ID\",\"state\":\"warning\",\"error\":\"backend not healthy\",\"end_time\":\"$(ts)\",\"log_path\":\"$RUN_LOG\"}"
    exit 0
  fi

  echo "=== WAOUW UPDATE DONE $(ts) ==="
  write_status "$ID" "{\"id\":\"$ID\",\"state\":\"success\",\"start_time\":\"$(ts)\",\"end_time\":\"$(ts)\",\"log_path\":\"$RUN_LOG\"}"

  # Cleanup
  rm -rf "$STAGE"
  exit 0
}

case "${1:-}" in
  apply) shift; apply_update "$@" ;;
  *) echo "Usage: waouw-update apply --zip <archive> [--id <id>]"; exit 1 ;;
esac
