#!/usr/bin/env bash
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$DIR/.pid"
SERVER="$DIR/server.js"
PORT=3000

cmd="${1:-start}"

# Check if our tracked PID is still alive
pid_running() {
    [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
}

# Get PID of whatever is currently listening on PORT (empty if nothing)
port_pid() {
    lsof -ti ":$PORT" 2>/dev/null | head -1 || true
}

do_start() {
    # If our tracked process is alive, already running
    if pid_running; then
        echo "Already running (PID $(cat "$PID_FILE")) — http://localhost:$PORT"
        return
    fi

    # Kill any stale process squatting on the port
    local stale
    stale="$(port_pid)"
    if [[ -n "$stale" ]]; then
        echo "Clearing stale process on :$PORT (PID $stale)"
        kill "$stale" 2>/dev/null || true
        sleep 0.3
    fi

    rm -f "$PID_FILE"
    node "$SERVER" > "$DIR/.log" 2>&1 &
    local pid=$!
    echo "$pid" > "$PID_FILE"

    # Wait up to 2s for server to bind
    local i=0
    while [[ $i -lt 8 ]]; do
        sleep 0.25
        if kill -0 "$pid" 2>/dev/null; then
            echo "Started (PID $pid) — http://localhost:$PORT"
            if command -v xdg-open &>/dev/null; then
                xdg-open "http://localhost:$PORT" &>/dev/null &
            elif command -v open &>/dev/null; then
                open "http://localhost:$PORT" &>/dev/null &
            fi
            return
        fi
        (( i++ )) || true
    done

    echo "Failed to start — check .log for details"
    rm -f "$PID_FILE"
    exit 1
}

do_stop() {
    local stopped=0

    if pid_running; then
        kill "$(cat "$PID_FILE")"
        stopped=1
    fi

    # Belt-and-suspenders: kill anything still on the port
    local stale
    stale="$(port_pid)"
    if [[ -n "$stale" ]]; then
        kill "$stale" 2>/dev/null || true
        stopped=1
    fi

    rm -f "$PID_FILE"
    [[ $stopped -eq 1 ]] && echo "Stopped" || echo "Not running"
}

do_status() {
    if pid_running; then
        echo "Running (PID $(cat "$PID_FILE")) — http://localhost:$PORT"
    else
        local stale
        stale="$(port_pid)"
        if [[ -n "$stale" ]]; then
            echo "Port $PORT occupied by stale PID $stale (not tracked) — run ./run restart"
        else
            echo "Not running"
        fi
    fi
}

case "$cmd" in
    start)   do_start ;;
    stop)    do_stop ;;
    restart) do_stop; sleep 0.3; do_start ;;
    status)  do_status ;;
    logs)    tail -f "$DIR/.log" ;;
    *)
        echo "Usage: ./run [start|stop|restart|status|logs]"
        exit 1
        ;;
esac
