#!/bin/bash

echo ""
echo "╔════════════════════════════════════════════════╗"
echo "║  🧪 TESTING PYTHON BATCH UPDATE SCRIPTS      ║"
echo "╚════════════════════════════════════════════════╝"
echo ""

# 1. Check Python scripts exist
echo "1️⃣  Checking Python scripts..."
echo ""

files=(
  "scripts/scrape-cma.py"
  "scripts/scrape-hapag.py"
  "scripts/batch-update-cma.py"
  "scripts/batch-update-hapag.py"
)

all_exist=true
for file in "${files[@]}"; do
  if [ -f "$file" ]; then
    lines=$(wc -l < "$file")
    echo "✅ $file ($lines lines)"
  else
    echo "❌ $file NOT FOUND"
    all_exist=false
  fi
done

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 2. Check Python packages
echo "2️⃣  Checking Python dependencies..."
echo ""

python3 -c "import undetected_chromedriver; print('✅ undetected_chromedriver')" 2>/dev/null || echo "❌ undetected_chromedriver NOT installed"
python3 -c "import selenium; print('✅ selenium')" 2>/dev/null || echo "❌ selenium NOT installed"
python3 -c "import psycopg2; print('✅ psycopg2')" 2>/dev/null || echo "❌ psycopg2 NOT installed"
python3 -c "import dotenv; print('✅ python-dotenv')" 2>/dev/null || echo "❌ python-dotenv NOT installed"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 3. Check containers in database
echo "3️⃣  Checking containers in database..."
echo ""

npx tsx -e "
import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config({ path: '.env.local' });

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

(async () => {
  try {
    const cmaResult = await pool.query(\`SELECT container_number FROM container_shipment WHERE container_number LIKE 'CMAU%' LIMIT 3\`);
    const hapagResult = await pool.query(\`SELECT container_number FROM container_shipment WHERE container_number LIKE 'HLBU%' LIMIT 3\`);
    
    console.log('🔴 CMA (CMAU):');
    if (cmaResult.rows.length > 0) {
      cmaResult.rows.forEach(r => console.log('   -', r.container_number));
    } else {
      console.log('   ℹ️  No containers found');
    }
    
    console.log('');
    console.log('🟠 Hapag-Lloyd (HLBU):');
    if (hapagResult.rows.length > 0) {
      hapagResult.rows.forEach(r => console.log('   -', r.container_number));
    } else {
      console.log('   ℹ️  No containers found');
    }
  } catch(e) {
    console.log('❌ Database connection error:', e.message);
  } finally {
    await pool.end();
  }
})();
" 2>&1

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if [ "$all_exist" = true ]; then
  echo "✅ All Python scripts found!"
  echo ""
  echo "📝 To run the scrapers:"
  echo ""
  echo "   CMA:          python3 scripts/batch-update-cma.py"
  echo "   Hapag-Lloyd:  python3 scripts/batch-update-hapag.py"
  echo ""
else
  echo "❌ Some Python scripts are missing. Create them first."
fi

echo ""

