#!/bin/bash
# שחזור מסד נתונים מגיבוי
# Usage: ./restore-db.sh <backup_file>

set -euo pipefail

if [ $# -lt 1 ]; then
    echo "שימוש: ./restore-db.sh <backup_file>"
    echo ""
    echo "גיבויים זמינים:"
    ls -lhrt /home/chaim/legal-ai/data/backups/legal_ai_* 2>/dev/null || echo "  (אין גיבויים)"
    exit 1
fi

BACKUP_FILE="$1"

if [ ! -f "${BACKUP_FILE}" ]; then
    echo "קובץ לא נמצא: ${BACKUP_FILE}"
    exit 1
fi

# Load DB credentials
source "${HOME}/.env" 2>/dev/null || true

DB_HOST="${POSTGRES_HOST:-127.0.0.1}"
DB_PORT="${POSTGRES_PORT:-5433}"
DB_NAME="${POSTGRES_DB:-legal_ai}"
DB_USER="${POSTGRES_USER:-legal_ai}"

echo "⚠️  שחזור מגיבוי: ${BACKUP_FILE}"
echo "    מסד נתונים: ${DB_NAME}@${DB_HOST}:${DB_PORT}"
echo ""
read -p "האם להמשיך? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "בוטל."
    exit 0
fi

# Determine file format
if [[ "${BACKUP_FILE}" == *.gz ]]; then
    echo "[$(date)] Decompressing..."
    gunzip -k "${BACKUP_FILE}"
    RESTORE_FILE="${BACKUP_FILE%.gz}"
else
    RESTORE_FILE="${BACKUP_FILE}"
fi

echo "[$(date)] Restoring..."

PGPASSWORD="${POSTGRES_PASSWORD:-}" pg_restore \
    -h "${DB_HOST}" \
    -p "${DB_PORT}" \
    -U "${DB_USER}" \
    -d "${DB_NAME}" \
    --clean \
    --if-exists \
    --no-owner \
    "${RESTORE_FILE}" 2>&1 || true

echo "[$(date)] ✅ שחזור הושלם"

# Verify
PGPASSWORD="${POSTGRES_PASSWORD:-}" psql \
    -h "${DB_HOST}" \
    -p "${DB_PORT}" \
    -U "${DB_USER}" \
    -d "${DB_NAME}" \
    -c "SELECT COUNT(*) as cases FROM cases; SELECT COUNT(*) as documents FROM documents;" 2>/dev/null || true
