#!/usr/bin/env bash
# engine_dashboard.sh — Start/stop/check the Production Console dashboard
# Called by the /engine skill during initialization.
#
# Usage:
#   engine_dashboard.sh start <project> [--port 8430]
#   engine_dashboard.sh stop
#   engine_dashboard.sh status
#   engine_dashboard.sh open

set -euo pipefail

RECOIL_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
VENV_PYTHON="$RECOIL_ROOT/.venv/bin/python3"
SERVER_SCRIPT="$RECOIL_ROOT/pipeline/editors/review_server.py"
PID_FILE="/tmp/recoil-dashboard.pid"
LOG_FILE="/tmp/recoil-dashboard.log"
DEFAULT_PORT=8430

cmd="${1:-status}"
shift || true

case "$cmd" in
    start)
        project="${1:?Usage: engine_dashboard.sh start <project>}"
        shift || true
        port="$DEFAULT_PORT"
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --port) port="$2"; shift 2 ;;
                *) shift ;;
            esac
        done

        # Check if already running
        if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
            echo "Dashboard already running (PID $(cat "$PID_FILE")) at http://127.0.0.1:$port"
            exit 0
        fi

        # Start server
        cd "$RECOIL_ROOT/pipeline"
        nohup "$VENV_PYTHON" "$SERVER_SCRIPT" --project "$project" --port "$port" \
            > "$LOG_FILE" 2>&1 &
        echo $! > "$PID_FILE"

        # Wait for startup
        for i in $(seq 1 10); do
            if curl -s -o /dev/null -w "" "http://127.0.0.1:$port/console" 2>/dev/null; then
                echo "Dashboard started (PID $(cat "$PID_FILE")) at http://127.0.0.1:$port"
                exit 0
            fi
            sleep 0.5
        done

        echo "WARNING: Dashboard may not have started. Check $LOG_FILE"
        exit 1
        ;;

    stop)
        if [[ -f "$PID_FILE" ]]; then
            pid="$(cat "$PID_FILE")"
            if kill -0 "$pid" 2>/dev/null; then
                kill "$pid"
                rm -f "$PID_FILE"
                echo "Dashboard stopped (was PID $pid)"
            else
                rm -f "$PID_FILE"
                echo "Dashboard was not running (stale PID file removed)"
            fi
        else
            echo "Dashboard is not running (no PID file)"
        fi
        ;;

    status)
        if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
            echo "RUNNING (PID $(cat "$PID_FILE"))"
            exit 0
        else
            echo "NOT_RUNNING"
            exit 1
        fi
        ;;

    open)
        port="$DEFAULT_PORT"
        if [[ "${1:-}" == "--port" ]]; then port="$2"; fi
        open "http://127.0.0.1:$port/console"
        ;;

    *)
        echo "Usage: engine_dashboard.sh {start|stop|status|open} [args]"
        exit 1
        ;;
esac
