#!/bin/bash

# Script to test x-app-sdk integration locally

echo "🧪 Testing x-app-sdk integration..."

# Check if we're in the right directory
if [ ! -f "pubspec.yaml" ]; then
    echo "❌ Please run this script from the Flutter project root directory"
    exit 1
fi

# Install web dependencies
echo "📦 Installing web dependencies..."
cd web
if [ -f "package.json" ]; then
    npm install
    if [ $? -eq 0 ]; then
        echo "✅ Web dependencies installed successfully!"
    else
        echo "❌ Failed to install web dependencies"
        exit 1
    fi
else
    echo "❌ No package.json found in web directory"
    exit 1
fi
cd ..

# Build Flutter web app
echo "🔨 Building Flutter web app..."
flutter build web --release

if [ $? -eq 0 ]; then
    echo "✅ Build successful!"
    
    # Start local server with CORS headers
    echo "🚀 Starting local server with CORS support on port 8080..."
    echo "🌐 Open your browser and go to: http://localhost:8080"
    echo ""
    echo "🔧 To test x-app-sdk integration:"
    echo "1. Open browser console (F12)"
    echo "2. Check for x-app-sdk initialization logs"
    echo "3. Look for 'AppHostData' object in window"
    echo "4. Test with URL parameters: ?token=test123&user={\"id\":\"user123\"}"
    echo ""
    echo "⚠️  Note: If you see CORS errors, use the CORS proxy script:"
    echo "   ./scripts/run_web_with_cors.sh"
    echo ""
    echo "Press Ctrl+C to stop the server"
    
    # Start server with CORS headers
    cd build/web
    python3 -c "
import http.server
import socketserver
from urllib.parse import urlparse

class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

PORT = 8080
with socketserver.TCPServer(('', PORT), CORSHTTPRequestHandler) as httpd:
    print(f'Serving at port {PORT}')
    httpd.serve_forever()
"
else
    echo "❌ Build failed!"
    exit 1
fi
