#!/bin/bash
set -e

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

# ─── Read .env (ignore shell env) ────────────────────────────────────
unset FAL_KEY FAL_COMFY_ENDPOINT
if [ -f .env ]; then
    set -a; source .env; set +a
fi

# ─── Always ask for config (press Enter to keep current) ─────────────
echo ""
echo "  ComfyUI Serverless — Configuration"
echo ""

echo "  API Key (get yours at https://fal.ai/dashboard/keys)"
if [ -n "$FAL_KEY" ]; then
    MASKED="${FAL_KEY:0:8}..."
    read -sp "  FAL_KEY [$MASKED]: " NEW_KEY
    echo ""
    [ -n "$NEW_KEY" ] && FAL_KEY="$NEW_KEY"
else
    read -sp "  FAL_KEY: " FAL_KEY
    echo ""
    [ -z "$FAL_KEY" ] && echo "  No key provided." && exit 1
fi

echo ""
echo "  Endpoint (ask your team lead if unsure)"
if [ -n "$FAL_COMFY_ENDPOINT" ]; then
    read -p "  FAL_COMFY_ENDPOINT [$FAL_COMFY_ENDPOINT]: " NEW_ENDPOINT
    [ -n "$NEW_ENDPOINT" ] && FAL_COMFY_ENDPOINT="$NEW_ENDPOINT"
else
    echo "  Example: my-team/comfy"
    read -p "  FAL_COMFY_ENDPOINT: " FAL_COMFY_ENDPOINT
    [ -z "$FAL_COMFY_ENDPOINT" ] && echo "  No endpoint provided." && exit 1
fi

cat > .env << EOF
FAL_KEY=$FAL_KEY
FAL_COMFY_ENDPOINT=$FAL_COMFY_ENDPOINT
EOF
set -a; source .env; set +a
echo ""

# ─── Check & install tools ────────────────────────────────────────────
install_brew() {
    if ! command -v brew >/dev/null 2>&1; then
        echo "  Installing Homebrew (required for dependencies)..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        # Add brew to PATH for Apple Silicon
        if [ -f /opt/homebrew/bin/brew ]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
        fi
    fi
}

MISSING=""
command -v uv >/dev/null 2>&1 || MISSING="$MISSING uv"
command -v ffmpeg >/dev/null 2>&1 || MISSING="$MISSING ffmpeg"

if [ -n "$MISSING" ]; then
    echo "  Installing dependencies:$MISSING"
    install_brew
    brew install $MISSING
fi

# ─── Download frontend if missing ─────────────────────────────────────
if [ ! -f "frontend/dist/index.html" ]; then
    echo "  Downloading ComfyUI frontend..."
    FRONTEND_URL="https://github.com/fal-ai-community/serverless-comfyui-v2/releases/download/v0.0.26/frontend-dist.zip"
    curl -sL "$FRONTEND_URL" -o /tmp/frontend-dist.zip
    unzip -qo /tmp/frontend-dist.zip -d .
    rm -f /tmp/frontend-dist.zip
    echo "  Frontend ready."
fi

# ─── Python env ──────────────────────────────────────────────────────
if [ ! -x ".venv/bin/python" ]; then
    echo "  Creating Python environment..."
    uv venv --seed .venv
fi
if ! .venv/bin/python -c "import fastapi, fal_client" >/dev/null 2>&1; then
    echo "  Installing dependencies..."
    uv pip install --python .venv/bin/python -r proxy/requirements.txt
fi

# ─── Kill previous & clean ───────────────────────────────────────────
kill $(lsof -ti:8188) 2>/dev/null || true
rm -f node_class_mappings.*.json

# ─── Info ────────────────────────────────────────────────────────────
ORG=$(echo "$FAL_COMFY_ENDPOINT" | cut -d'/' -f1)
APP=$(echo "$FAL_COMFY_ENDPOINT" | cut -d'/' -f2)

echo ""
echo "  ComfyUI Serverless"
echo "  Endpoint: $FAL_COMFY_ENDPOINT"
echo "  Runners:  https://fal.ai/dashboard/apps/$ORG/$APP/runners"
echo ""
echo "  Starting... (first launch takes ~5 minutes)"
echo "  ComfyUI will open at http://localhost:8188"
echo ""

# ─── Launch proxy (foreground — user sees all logs) ──────────────────
export FAL_KEY FAL_COMFY_ENDPOINT
exec .venv/bin/python proxy/fal_comfy_server.py
