#!/usr/bin/env bash
set -e

echo "================================================"
echo "  DraftKings Login Server - Setup & Start"
echo "================================================"

# ── 1. Python deps ────────────────────────────────────────────────────────────
echo "[1/4] Installing Python dependencies..."
pip install flask playwright requests --user -q

# ── 2. Playwright browser ─────────────────────────────────────────────────────
echo "[2/4] Installing Playwright Chromium..."
python3 -m playwright install chromium 2>&1 | grep -E "downloaded|already|Chromium" || true

# ── 3. cloudflared ────────────────────────────────────────────────────────────
echo "[3/4] Setting up cloudflared..."
if ! command -v cloudflared &>/dev/null; then
    wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -O /tmp/cloudflared
    chmod +x /tmp/cloudflared
    CF_CMD="/tmp/cloudflared"
else
    CF_CMD="cloudflared"
fi
echo "      cloudflared: $($CF_CMD --version)"

# ── 4. Kill any previous instances ───────────────────────────────────────────
pkill -f login_server.py 2>/dev/null || true
pkill -f cloudflared     2>/dev/null || true
sleep 1

# ── 5. Start Flask in background ─────────────────────────────────────────────
echo "[4/4] Starting Flask server..."
export PATH=$PATH:/home/user/.local/bin
python3 "$(dirname "$0")/login_server.py" > /tmp/flask.log 2>&1 &
FLASK_PID=$!

# Wait for Flask to be ready
for i in $(seq 1 20); do
    if curl -s http://localhost:5000 &>/dev/null || grep -q "Running on" /tmp/flask.log 2>/dev/null; then
        break
    fi
    sleep 1
done

echo ""
echo "✅ Flask running (PID $FLASK_PID)"
echo ""

# ── 6. Start cloudflared tunnel ───────────────────────────────────────────────
echo "🌐 Creating public tunnel..."
$CF_CMD tunnel --url http://localhost:5000 --no-autoupdate > /tmp/tunnel.log 2>&1 &
CF_PID=$!

# Wait for tunnel URL
PUBLIC_URL=""
for i in $(seq 1 30); do
    PUBLIC_URL=$(grep -o 'https://[^ ]*trycloudflare.com' /tmp/tunnel.log 2>/dev/null | head -1)
    if [ -n "$PUBLIC_URL" ]; then break; fi
    sleep 1
done

if [ -z "$PUBLIC_URL" ]; then
    echo "❌ Tunnel failed. Check /tmp/tunnel.log"
    exit 1
fi

echo ""
echo "================================================"
echo "  ✅ READY!"
echo "================================================"
echo ""
echo "  📡 Public URL:  $PUBLIC_URL"
echo ""
echo "  🧪 Test (GET):  $PUBLIC_URL/login?email=YOUR_EMAIL&password=YOUR_PASS"
echo ""
echo "  📋 Example:"
echo "     $PUBLIC_URL/login?email=user%40gmail.com&password=secret"
echo ""
echo "  Logs:  tail -f /tmp/flask.log"
echo "         tail -f /tmp/tunnel.log"
echo ""
echo "  Stop:  kill $FLASK_PID $CF_PID"
echo "================================================"

# Keep script alive (tunnel dies if parent exits)
wait $CF_PID
