#!/bin/bash

# Script để export web app cho môi trường development và chạy với CORS

echo "🔧 Exporting Development Web App..."

# Kill server cũ
lsof -i :8080 | awk 'NR>1 {print $2}' | xargs kill -9 2>/dev/null || true

# Chuyển sang dev environment
./scripts/switch_env.sh dev

# Export web app
./export_web.sh

# Chạy server với CORS như run_dev
echo "🚀 Starting exported web app with CORS..."
EXPORT_DIRS=$(ls -d web_export_* 2>/dev/null | grep -v "\.zip$" | sort -r | head -1)

if [ -z "$EXPORT_DIRS" ]; then
    echo "❌ No web export directory found"
    exit 1
fi

echo "📁 Using export directory: $EXPORT_DIRS"
cd "$EXPORT_DIRS"

# Verify we're in the right directory
if [ ! -f "index.html" ]; then
    echo "❌ index.html not found in $EXPORT_DIRS"
    exit 1
fi

echo "✅ Found index.html in export directory"

# Start web server with CORS headers (same as run_web_complete.sh)
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 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}')
print(f'📁 Serving from: {os.getcwd()}')
print('🔧 CORS headers enabled for API calls')
print('')
print('Press Ctrl+C to stop the server')

with socketserver.TCPServer(('', PORT), CORSHTTPRequestHandler) as httpd:
    httpd.serve_forever()
" &
SERVER_PID=$!

# Wait for server to start
sleep 3

# Open browser with CORS disabled (same as run_web_complete.sh)
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 "📁 Export directory: $EXPORT_DIRS"
echo ""
echo "Press Ctrl+C to stop the server"

# Wait for user to stop
wait $SERVER_PID

