#!/bin/bash
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR/app"

# ─── Set up Python 3.11 venv (uv preferred, fall back to python3.11) ─
if [ ! -x ".venv/bin/python" ]; then
    PY311=$(command -v python3.11 2>/dev/null || true)

    if [ -z "$PY311" ] && ! command -v uv >/dev/null 2>&1; then
        echo "Python 3.11 not found; installing the 'uv' tool to manage it..."
        if command -v curl >/dev/null 2>&1; then
            curl -LsSf https://astral.sh/uv/install.sh | sh || true
        fi
        export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
    fi

    if command -v uv >/dev/null 2>&1; then
        echo "Creating Python 3.11 venv via uv (may download Python the first time)..."
        uv venv --seed --python 3.11 .venv
    elif [ -n "$PY311" ]; then
        echo "Setting up Python environment (first run, takes ~1 min)..."
        "$PY311" -m venv .venv
    else
        echo ""
        echo "  ERROR: Could not set up Python 3.11."
        echo "  Install Python 3.11 manually from https://www.python.org/downloads/"
        echo "  Or install uv:    curl -LsSf https://astral.sh/uv/install.sh | sh"
        echo ""
        read -n 1 -p "  Press any key to exit..."
        exit 1
    fi

    .venv/bin/pip install --quiet --upgrade pip setuptools
fi

# ─── Sync dependencies on every launch ───────────────────────────────
# Always run pip install so any new exact pin in pyproject.toml or
# proxy/requirements.txt is reflected in the venv. Cheap when nothing
# changed (a few seconds). We deliberately don't pass --upgrade — that
# would pull unpinned deps to "latest" and break pyproject.toml's pins
# (fastapi, pydantic, etc.). pip still re-resolves exact pins like
# `fal-client==0.5.9` even without --upgrade, so version corrections
# still happen automatically.
echo "Syncing dependencies..."
.venv/bin/pip install --quiet -e '.[dev]'
if [ -f proxy/requirements.txt ]; then
    .venv/bin/pip install --quiet -r proxy/requirements.txt
fi

# ─── Kill ANY process already holding our ports (admin + proxy) ──────
# Even if it came from a different install folder or a previous session —
# we want THIS launcher to own :9999 and :8188. Otherwise requests from
# the browser may hit a stale server and execute the wrong code.
for port in 9999 8188; do
    PIDS=$(lsof -ti:$port 2>/dev/null || true)
    if [ -n "$PIDS" ]; then
        echo "Stopping existing process(es) on port $port ($PIDS)..."
        echo "$PIDS" | xargs kill 2>/dev/null || true
        sleep 1
        echo "$PIDS" | xargs kill -9 2>/dev/null || true
    fi
done
pkill -f "proxy/fal_comfy_server.py" 2>/dev/null || true
rm -f .admin-ui.pid 2>/dev/null

echo "Starting admin UI on http://localhost:9999..."
echo "Close this terminal window to stop the server."
echo ""

.venv/bin/python admin-ui/server.py
