#!/bin/sh
# Cross-platform script to serve current directory via HTTP and open browser
# Works on Windows (PowerShell), macOS, and Linux (Python)
# Port can be configured at the top of the script

# ===== CONFIGURATION =====
PORT=8181  # Change this to your desired port (e.g., 8080, 3000)
# =========================

# Check if Python is available (macOS/Linux)
if command -v python3 >/dev/null 2>&1; then
    python3 -m http.server "$PORT" --bind 127.0.0.1 & sleep 1
    python3 -c "import webbrowser; webbrowser.open('http://localhost:$PORT')"
    wait
elif command -v python >/dev/null 2>&1; then
    python -m http.server "$PORT" --bind 127.0.0.1 & sleep 1
    python -c "import webbrowser; webbrowser.open('http://localhost:$PORT')"
    wait
# Fallback to PowerShell on Windows
elif [ "$OSTYPE" = "msys" ] || [ "$OSTYPE" = "win32" ] || [ -n "$COMSPEC" ]; then
    powershell -Command "& {
        \$port = $PORT;
        \$listener = New-Object System.Net.HttpListener;
        \$listener.Prefixes.Add(\"http://localhost:\$port/\");
        \$listener.Start();
        Start-Process \"http://localhost:\$port\";
        while (\$true) {
            \$context = \$listener.GetContext();
            \$request = \$context.Request;
            \$response = \$context.Response;
            \$localPath = \$request.Url.LocalPath.TrimStart('/');
            if (\$localPath -eq '') { \$localPath = '.' }
            if (Test-Path -Path \$localPath -PathType Container) {
                \$files = Get-ChildItem -Path \$localPath | ForEach-Object { '<li><a href=\"' + \$_.Name + '\">' + \$_.Name + '</a></li>' };
                \$html = '<html><body><h1>Directory Listing</h1><ul>' + (\$files -join '') + '</ul></body></html>';
                \$buffer = [System.Text.Encoding]::UTF8.GetBytes(\$html);
                \$response.ContentLength64 = \$buffer.Length;
                \$response.OutputStream.Write(\$buffer, 0, \$buffer.Length);
            } elseif (Test-Path -Path \$localPath -PathType Leaf) {
                \$buffer = [System.IO.File]::ReadAllBytes((Resolve-Path \$localPath));
                \$response.ContentLength64 = \$buffer.Length;
                \$response.OutputStream.Write(\$buffer, 0, \$buffer.Length);
            } else {
                \$response.StatusCode = 404;
                \$buffer = [System.Text.Encoding]::UTF8.GetBytes('404 - Not Found');
                \$response.ContentLength64 = \$buffer.Length;
                \$response.OutputStream.Write(\$buffer, 0, \$buffer.Length);
            }
            \$response.Close();
        }
    }"
else
    echo "Error: Python or PowerShell not found. Cannot serve directory."
    exit 1
fi
