#!/bin/bash

# Run Flutter app with Supabase credentials from env.json
# This script reads env.json and passes Supabase credentials to Flutter

set -e

# Navigate to project root
cd "$(dirname "$0")/.."

# Check if env.json exists
if [ ! -f "env.json" ]; then
    echo "❌ env.json not found!"
    echo "   Please create env.json with SUPABASE_URL and SUPABASE_ANON_KEY"
    exit 1
fi

# Extract Supabase credentials from env.json
# Using Python for reliable JSON parsing
SUPABASE_URL=$(python3 -c "import json; print(json.load(open('env.json'))['SUPABASE_URL'])" 2>/dev/null || echo "")
SUPABASE_ANON_KEY=$(python3 -c "import json; print(json.load(open('env.json'))['SUPABASE_ANON_KEY'])" 2>/dev/null || echo "")
GOOGLE_MAPS_API_KEY=$(python3 -c "import json; print(json.load(open('env.json'))['GOOGLE_MAPS_API_KEY'])" 2>/dev/null || echo "")

# Fallback: try with node if python fails
if [ -z "$SUPABASE_URL" ] || [ -z "$SUPABASE_ANON_KEY" ]; then
    if command -v node >/dev/null 2>&1; then
        SUPABASE_URL=$(node -e "const fs=require('fs'); const data=JSON.parse(fs.readFileSync('env.json')); console.log(data.SUPABASE_URL);" 2>/dev/null || echo "")
        SUPABASE_ANON_KEY=$(node -e "const fs=require('fs'); const data=JSON.parse(fs.readFileSync('env.json')); console.log(data.SUPABASE_ANON_KEY);" 2>/dev/null || echo "")
        GOOGLE_MAPS_API_KEY=$(node -e "const fs=require('fs'); const data=JSON.parse(fs.readFileSync('env.json')); console.log(data.GOOGLE_MAPS_API_KEY);" 2>/dev/null || echo "")
    fi
fi

# Check if we got the credentials
if [ -z "$SUPABASE_URL" ] || [ -z "$SUPABASE_ANON_KEY" ]; then
    echo "❌ Could not extract Supabase credentials from env.json"
    echo "   Make sure env.json contains SUPABASE_URL and SUPABASE_ANON_KEY"
    exit 1
fi

echo "✅ Found Supabase credentials"
echo "   URL: $SUPABASE_URL"
echo "   Key: ${SUPABASE_ANON_KEY:0:20}..."
if [ -n "$GOOGLE_MAPS_API_KEY" ] && [ "$GOOGLE_MAPS_API_KEY" != "your-google-maps-api-key" ]; then
    echo "🗺️  Found Google Maps API Key"
    # Inject into web/index.html
    if [ -f "web/index.html" ]; then
        sed -i '' "s/key=[^\&\"]*/key=$GOOGLE_MAPS_API_KEY/" web/index.html
    fi
fi
echo ""

# Determine device (default to web-server for web)
DEVICE="${1:-web-server}"

echo "🚀 Running Flutter app with Supabase..."
echo "   Device: $DEVICE"
echo ""

# Run Flutter with environment variables
flutter run -d "$DEVICE" \
  --dart-define=SUPABASE_URL="$SUPABASE_URL" \
  --dart-define=SUPABASE_ANON_KEY="$SUPABASE_ANON_KEY" \
  --dart-define=GOOGLE_MAPS_API_KEY="$GOOGLE_MAPS_API_KEY"

