#!/bin/bash
# OCR Pipeline Deployment Script
# Run this on ceph2401 server

set -e

echo "=========================================="
echo "OCR Pipeline Deployment"
echo "=========================================="

# Configuration
BACKEND_DIR="/home/local/02-Translation/backend"
OCR_DIR="$BACKEND_DIR/ocr_pipeline"
VENV_DIR="$BACKEND_DIR/venv"

# Check if running on correct server
if [[ ! -d "$BACKEND_DIR" ]]; then
    echo "ERROR: Backend directory not found: $BACKEND_DIR"
    echo "Make sure you're running this on ceph2401"
    exit 1
fi

# Step 1: Backup existing OCR service if exists
echo ""
echo "[1/5] Backing up existing OCR service..."
if [[ -f "$BACKEND_DIR/pdf-processor-ocr-main.py" ]]; then
    cp "$BACKEND_DIR/pdf-processor-ocr-main.py" "$BACKEND_DIR/pdf-processor-ocr-main.py.bak"
    echo "  Backed up to pdf-processor-ocr-main.py.bak"
fi

# Step 2: Check if ocr_pipeline folder exists
echo ""
echo "[2/5] Checking ocr_pipeline folder..."
if [[ -d "$OCR_DIR" ]]; then
    echo "  ocr_pipeline folder exists"
    ls -la "$OCR_DIR"
else
    echo "  ERROR: ocr_pipeline folder not found!"
    echo "  Please copy the folder first:"
    echo "    scp -r ocr_pipeline/ ceph2401:$BACKEND_DIR/"
    exit 1
fi

# Step 3: Install dependencies
echo ""
echo "[3/5] Installing dependencies..."
cd "$BACKEND_DIR"
if [[ -d "$VENV_DIR" ]]; then
    source "$VENV_DIR/bin/activate"
else
    echo "  Creating virtual environment..."
    python3 -m venv "$VENV_DIR"
    source "$VENV_DIR/bin/activate"
fi

# Install required packages
pip install --quiet paddlepaddle paddlex pdf2image pdfplumber python-docx pillow httpx

echo "  Dependencies installed"

# Step 4: Run database migration
echo ""
echo "[4/5] Running database migration..."
if [[ -f "$OCR_DIR/schema.sql" ]]; then
    echo "  Applying schema.sql to PostgreSQL..."
    psql -U translynx -d translynx -f "$OCR_DIR/schema.sql" 2>&1 | head -20
    echo "  Database migration complete"
else
    echo "  WARNING: schema.sql not found, skipping migration"
fi

# Step 5: Test import
echo ""
echo "[5/5] Testing OCR pipeline import..."
cd "$BACKEND_DIR"
python3 -c "
from ocr_pipeline import OCRPipeline
from ocr_pipeline.config import get_config
config = get_config()
print('  OCR Pipeline imported successfully')
print(f'  API Key configured: {bool(config.siliconflow_api_key)}')
print(f'  VL Model: {config.vl_model}')
"

echo ""
echo "=========================================="
echo "Deployment Complete!"
echo "=========================================="
echo ""
echo "To start the OCR service:"
echo "  cd $BACKEND_DIR"
echo "  source venv/bin/activate"
echo "  uvicorn ocr_pipeline.service:app --host 0.0.0.0 --port 9100"
echo ""
echo "Or run in background:"
echo "  nohup uvicorn ocr_pipeline.service:app --host 0.0.0.0 --port 9100 > ocr_service.log 2>&1 &"
echo ""
