#!/bin/bash
set -e

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

fail() { echo ""; echo "  ERROR: $1"; echo "  $2"; echo ""; exit 1; }

echo ""
echo "  ComfyUI Serverless — Deploy"
echo ""

# ─── Load .env (only for defaults, we always ask) ────────────────────
SAVED_KEY=""
SAVED_APP=""
if [ -f .env ]; then
    SAVED_KEY=$(grep "^FAL_KEY=" .env | cut -d= -f2-)
    SAVED_APP=$(grep "^APP_NAME=" .env | cut -d= -f2-)
fi

# ─── Always ask for API key (admin-scoped, team-specific) ────────────
echo "  Deploy needs an ADMIN API key."
echo ""
echo "  → Create one at: https://fal.ai/dashboard/keys"
echo "  → IMPORTANT: Switch to the right team (top-right on the dashboard)"
echo "    BEFORE creating the key. The team is encoded in the key."
echo "  → Enable the 'Admin' scope."
echo ""
echo "  Your endpoint will be: <team-or-user>/<app-name>"
echo "  The team comes from the key you paste below."
echo ""
if [ -n "$SAVED_KEY" ]; then
    MASKED="${SAVED_KEY:0:8}..."
    read -sp "  FAL_KEY [$MASKED]: " INPUT_KEY
    echo ""
    FAL_KEY="${INPUT_KEY:-$SAVED_KEY}"
else
    read -sp "  FAL_KEY (admin): " FAL_KEY
    echo ""
fi
[ -z "$FAL_KEY" ] && fail "No key provided." "Get one at https://fal.ai/dashboard/keys"

# ─── Ask for app name ────────────────────────────────────────────────
echo ""
echo "  App name"
if [ -n "$SAVED_APP" ]; then
    read -p "  APP_NAME [$SAVED_APP]: " INPUT_APP
    APP_NAME="${INPUT_APP:-$SAVED_APP}"
else
    read -p "  APP_NAME [comfy]: " INPUT_APP
    APP_NAME="${INPUT_APP:-comfy}"
fi

# ─── Save to .env ────────────────────────────────────────────────────
cat > .env << EOF
FAL_KEY=$FAL_KEY
APP_NAME=$APP_NAME
EOF

# ─── Check Python 3.11 ──────────────────────────────────────────────
PYTHON_BIN=$(which python3.11 || echo "")
if [ -z "$PYTHON_BIN" ]; then
    echo ""
    echo "  Python 3.11 not found — installing via Homebrew..."
    if command -v brew >/dev/null 2>&1; then
        brew install python@3.11
        PYTHON_BIN=$(which python3.11)
    else
        fail "Python 3.11 missing." "Install Python 3.11 first: https://www.python.org/downloads/"
    fi
fi

# ─── Setup venv (at root, same as deployment) ──────────────────────────
if [ ! -x ".venv/bin/python" ]; then
    echo ""
    echo "  Setting up Python environment (first time, ~2 min)..."
    $PYTHON_BIN -m venv .venv
    .venv/bin/pip install --quiet --upgrade pip setuptools
    .venv/bin/pip install --quiet -e '.[dev]'
fi

# ─── Login to fal (the key determines which team) ────────────────────
# Force logout of any user session to ensure FAL_KEY is used (not Google auth)
.venv/bin/fal auth logout >/dev/null 2>&1 || true

export FAL_KEY
echo ""
echo "  Verifying API key..."

# Test the key with apps list (only works for admin keys)
TEST=$(.venv/bin/fal apps list 2>&1 | head -1)
if echo "$TEST" | grep -q "Insufficient permissions"; then
    fail "Key doesn't have Admin scope." "Create an admin key at https://fal.ai/dashboard/keys (check the Admin box)"
fi
if echo "$TEST" | grep -q "must be authenticated"; then
    fail "Invalid API key." "Check the key value and try again."
fi

# Get team/user name from applications REST API
TEAM_NAME=$(curl -s -H "Authorization: Key $FAL_KEY" "https://rest.alpha.fal.ai/applications/?limit=1" 2>/dev/null | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    if isinstance(d, list) and d:
        print(d[0].get('app_user_nickname', ''))
except:
    pass
" 2>/dev/null)

echo "  ✓ Admin key OK"
if [ -n "$TEAM_NAME" ]; then
    echo "  ✓ Team/User: $TEAM_NAME"
    ENDPOINT="$TEAM_NAME/$APP_NAME"
else
    echo "  ? Team/User: (could not detect — first deploy?)"
    ENDPOINT="<your-team>/$APP_NAME"
fi

# ─── Confirm deploy target ───────────────────────────────────────────
echo ""
echo "  Deploy target:"
echo "    Endpoint: $ENDPOINT"
echo ""
read -p "  Confirm deploy? (y/n) " CONFIRM
[ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ] && fail "Cancelled." ""

echo ""
echo "  Deploying..."
.venv/bin/python -m fal deploy comfy_server/server.py::Comfy --app-name "$APP_NAME" --auth private

echo ""
echo "  ✅ Deploy complete!"
echo ""
if [ -n "$FAL_TEAM" ]; then
    echo "  Endpoint: $FAL_TEAM/$APP_NAME"
    echo "  Runners:  https://fal.ai/dashboard/apps/$FAL_TEAM/$APP_NAME/runners"
else
    echo "  Endpoint: <your-username>/$APP_NAME"
fi
echo ""
echo "  To force new code on active runners, terminate them from the dashboard."
echo ""
