#!/bin/bash

# Run Flutter app with local Supabase credentials
# This script extracts local Supabase credentials and runs Flutter with them

set -e

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

# Check if Supabase is running
if ! supabase status > /dev/null 2>&1; then
    echo "❌ Supabase is not running locally."
    echo "   Please run: ./scripts/setup-local-supabase.sh"
    exit 1
fi

# Get Supabase credentials from status
echo "🔍 Getting local Supabase credentials..."

# Get status output
STATUS_OUTPUT=$(supabase status 2>/dev/null)

# Extract URL - look for "API URL" line
SUPABASE_URL=$(echo "$STATUS_OUTPUT" | grep -i "API URL" | sed -E 's/.*(http[^[:space:]]+).*/\1/' | head -1)

# Extract anon key - look for "anon key" line  
SUPABASE_ANON_KEY=$(echo "$STATUS_OUTPUT" | grep -i "anon key" | sed -E 's/.*anon key[[:space:]]+([^[:space:]]+).*/\1/' | head -1)

# Alternative: try JSON output if available
if [ -z "$SUPABASE_URL" ] || [ -z "$SUPABASE_ANON_KEY" ]; then
    JSON_OUTPUT=$(supabase status --output json 2>/dev/null || echo "")
    if [ -n "$JSON_OUTPUT" ]; then
        SUPABASE_URL=$(echo "$JSON_OUTPUT" | grep -o '"API URL":"[^"]*' | sed 's/"API URL":"//' | head -1)
        SUPABASE_ANON_KEY=$(echo "$JSON_OUTPUT" | grep -o '"anon key":"[^"]*' | sed 's/"anon key":"//' | head -1)
    fi
fi

# If still empty, try reading from .env.local or config
if [ -z "$SUPABASE_URL" ] || [ -z "$SUPABASE_ANON_KEY" ]; then
    echo "⚠️  Could not automatically extract credentials."
    echo "   Please run 'supabase status' and manually set:"
    echo "   SUPABASE_URL and SUPABASE_ANON_KEY"
    echo ""
    echo "   Then run Flutter with:"
    echo "   flutter run -d chrome --dart-define=SUPABASE_URL=<url> --dart-define=SUPABASE_ANON_KEY=<key>"
    exit 1
fi

echo "✅ Found local Supabase credentials"
echo "   URL: $SUPABASE_URL"
echo "   Key: ${SUPABASE_ANON_KEY:0:20}..."
echo ""

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

echo "🚀 Running Flutter app with local Supabase..."
echo ""

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

