#!/bin/bash

# Complete script to run Flutter web app with CORS solution

echo "🌐 Starting Flutter web app with CORS solution..."

# 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 (force HTML renderer via dart-define for older Flutter)
echo "🔨 Building Flutter web app (HTML renderer)..."
flutter build web --release --dart-define=FLUTTER_WEB_USE_SKIA=false

if [ $? -eq 0 ]; then
    echo "✅ Build successful!"
    echo "📥 Copying x-app-sdk bundle into build artifacts..."
    ./scripts/copy_x_app_sdk_bundle.sh
else
    echo "❌ Build failed!"
    exit 1
fi

# Start web server in background
echo "🚀 Starting web server..."
cd build/web
python3 -c "
import http.server
import socketserver
import socket
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, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin')
        super().end_headers()

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

    def log_message(self, format, *args):
        print(f'🌐 {format % args}')

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

def find_free_port(start_port=8080, max_attempts=10):
    for port in range(start_port, start_port + max_attempts):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('', port))
                return port
        except OSError:
            continue
    return None

PORT = find_free_port(8080, 20)
if not PORT:
    print('❌ No free port found')
    exit(1)

print(f'🚀 Server running at http://localhost:{PORT}')
with socketserver.TCPServer(('', PORT), CORSHTTPRequestHandler) as httpd:
    httpd.serve_forever()
" &
SERVER_PID=$!

# Wait for server to start
sleep 3

# Open browser with CORS disabled
echo "🌐 Opening browser with CORS disabled..."
if command -v open &> /dev/null; then
    # macOS
    open -n -a "Google Chrome" --args --disable-web-security --user-data-dir=/tmp/chrome_dev --disable-features=VizDisplayCompositor http://localhost:8080
elif command -v google-chrome &> /dev/null; then
    # Linux
    google-chrome --disable-web-security --user-data-dir=/tmp/chrome_dev --disable-features=VizDisplayCompositor http://localhost:8080 &
else
    echo "⚠️  Chrome not found. Please open manually: http://localhost:8080"
fi

echo ""
echo "✅ Setup complete!"
echo "🌐 Web app: http://localhost:8080"
echo "🔧 CORS disabled in browser for development"
echo "📋 Retry limit: 3 attempts for Super App data"
echo ""
echo "Press Ctrl+C to stop the server"

# Wait for user to stop
wait $SERVER_PID
