#!/bin/bash
# ============================================================
# Start Mission Control Dashboard + Ollama
#
# Usage:
#   bash start-dashboard.sh          # start dashboard + ensure Ollama running
#   bash start-dashboard.sh stop     # stop dashboard
#   bash start-dashboard.sh status   # check status
# ============================================================

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DASHBOARD_DIR="$SCRIPT_DIR/dashboard"
PORT=3000

# Ollama URL: respect OLLAMA_HOST env var, auto-detect WSL2 gateway if needed
OLLAMA_URL="${OLLAMA_HOST:-http://localhost:11434}"
OLLAMA_URL="${OLLAMA_URL%/}"
if ! curl -s --max-time 2 "$OLLAMA_URL/api/tags" &>/dev/null; then
    if [ -r /proc/version ] && grep -qi microsoft /proc/version 2>/dev/null; then
        GW=$(ip route show default 2>/dev/null | awk '{print $3}' | head -1)
        if [ -n "$GW" ] && curl -s --max-time 2 "http://${GW}:11434/api/tags" &>/dev/null; then
            OLLAMA_URL="http://${GW}:11434"
        fi
    fi
fi
export OLLAMA_HOST="$OLLAMA_URL"

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'
ok()   { echo -e "${GREEN}[OK]${NC} $1"; }
warn() { echo -e "${YELLOW}[!!]${NC} $1"; }
fail() { echo -e "${RED}[FAIL]${NC} $1"; }

case "${1:-start}" in
    stop)
        echo "Stopping dashboard..."
        PID=$(lsof -ti :$PORT 2>/dev/null)
        if [ -n "$PID" ]; then
            kill "$PID" 2>/dev/null
            ok "Dashboard stopped (PID $PID)"
        else
            warn "Dashboard not running on port $PORT"
        fi
        exit 0
        ;;

    status)
        echo "=== Status ==="
        # Ollama
        if curl -s --max-time 2 "$OLLAMA_URL/api/tags" &>/dev/null; then
            MODELS=$(curl -s "$OLLAMA_URL/api/tags" | python3 -c "import sys,json; print(len(json.load(sys.stdin).get('models',[])))" 2>/dev/null || echo "?")
            ok "Ollama running at $OLLAMA_URL ($MODELS models)"
        else
            fail "Ollama not running at $OLLAMA_URL"
        fi
        # Dashboard
        if curl -s --max-time 2 "http://localhost:$PORT" &>/dev/null; then
            ok "Dashboard running at http://localhost:$PORT"
        else
            fail "Dashboard not running"
        fi
        exit 0
        ;;

    start)
        echo "=== Starting Mission Control ==="
        echo ""

        # 1. Check Ollama connectivity (don't try to start it -- on WSL2 it runs on Windows)
        if curl -s --max-time 2 "$OLLAMA_URL/api/tags" &>/dev/null; then
            ok "Ollama running at $OLLAMA_URL"
        else
            if command -v ollama &>/dev/null; then
                echo "Starting Ollama..."
                ollama serve &>/dev/null &
                sleep 2
                if curl -s --max-time 2 "$OLLAMA_URL/api/tags" &>/dev/null; then
                    ok "Ollama started"
                else
                    warn "Could not start Ollama. It may be running on Windows already."
                fi
            else
                warn "Ollama not reachable at $OLLAMA_URL (on WSL2, ensure it is running on Windows with OLLAMA_HOST=0.0.0.0:11434)"
            fi
        fi

        # 2. Check if dashboard already running
        if curl -s --max-time 2 "http://localhost:$PORT" &>/dev/null; then
            ok "Dashboard already running at http://localhost:$PORT"
            exit 0
        fi

        # 3. Install deps if needed
        if [ ! -d "$DASHBOARD_DIR/node_modules" ]; then
            echo "Installing dependencies..."
            (cd "$DASHBOARD_DIR" && npm install --silent)
            ok "Dependencies installed"
        fi

        # 4. Start dashboard (use node directly -- npx/next may lack +x on /mnt/ NTFS)
        echo "Starting dashboard on port $PORT..."
        LOGFILE="$DASHBOARD_DIR/.next-dev.log"
        (cd "$DASHBOARD_DIR" && OLLAMA_HOST="$OLLAMA_URL" node node_modules/next/dist/bin/next dev > "$LOGFILE" 2>&1 &)

        # Wait for it to be ready (Next.js on /mnt/d can be slow to compile)
        echo "  Waiting for Next.js to compile (this can take 1-2 min on /mnt/d)..."
        for i in $(seq 1 90); do
            if curl -s --max-time 1 "http://localhost:$PORT" &>/dev/null; then
                ok "Dashboard ready at http://localhost:$PORT"
                echo ""
                echo "Open: http://localhost:$PORT"
                echo "Stop: bash start-dashboard.sh stop"
                exit 0
            fi
            sleep 1
        done

        warn "Dashboard did not respond within 90s."
        echo "  It may still be compiling. Check the log:"
        echo "    tail -f $LOGFILE"
        echo "  Or start manually:"
        echo "    cd $DASHBOARD_DIR && npx next dev"
        exit 1
        ;;

    *)
        echo "Usage: bash start-dashboard.sh [start|stop|status]"
        exit 1
        ;;
esac
