#!/bin/bash

set -euo pipefail

FOLDER="${1:-build/web}"
PORT="${2:-8080}"

if [ ! -d "$FOLDER" ]; then
  echo "❌ Folder '$FOLDER' not found."
  exit 1
fi

pushd "$FOLDER" >/dev/null

python3 - <<'PY'
import http.server
import socketserver
import socket
import os
import sys

PORT = int(sys.argv[1])

class SPARequestHandler(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 do_GET(self):
        path = self.translate_path(self.path)
        if not os.path.exists(path):
            self.path = '/index.html'
        return super().do_GET()

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

with socketserver.TCPServer(('', PORT), SPARequestHandler) as httpd:
    print(f'🚀 Serving {os.getcwd()} at http://localhost:{PORT}')
    print('💡 Keep this terminal open. Ctrl+C to stop.')
    httpd.serve_forever()
PY "$PORT"

popd >/dev/null
