#!/bin/bash

# Script to test x-app-sdk implementation

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

# 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

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

if [ $? -eq 0 ]; then
    echo "✅ Build successful!"
    
    # Start local server
    echo "🚀 Starting local server 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 token retrieval logs in splash screen"
echo "4. Test closeApp functionality"
echo ""
echo "📋 Expected logs:"
echo "- '✅ x-app-sdk loaded from node_modules and ready'"
echo "- '🔧 SDK methods available: ['getToken', 'closeApp']'"
echo "- '🔍 SplashScreen - Attempting to get token from x-app-sdk...'"
echo "- '✅ SplashScreen - Token retrieved from x-app-sdk: ...'"
echo ""
echo "⚠️  Note: x-app-sdk will work differently in Super App environment"
    echo ""
    echo "Press Ctrl+C to stop the server"
    
    # Start server
    cd build/web
    python3 -c "
import http.server
import socketserver
import os

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()

    def do_GET(self):
        path = self.translate_path(self.path)
        if not os.path.exists(path):
            self.path = '/index.html'
            return super().do_GET()
        return super().do_GET()

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
