#!/bin/bash
# Print the current public URL for the villa decision app.
# The URL changes each time the cloudflared tunnel restarts (e.g., on reboot).

LOG="/tmp/villa-tunnel.log"

if [ ! -f "$LOG" ]; then
    echo "❌ السيرفر مو شغّال. شغّله بـ:" >&2
    echo "   launchctl load -w ~/Library/LaunchAgents/com.muath.villa-tunnel.plist" >&2
    exit 1
fi

URL=$(grep -oE "https://[a-z0-9-]+\.trycloudflare\.com" "$LOG" 2>/dev/null | tail -1)

if [ -z "$URL" ]; then
    echo "⏳ التنل يحضّر نفسه. جرّب مرة ثانية بعد كم ثانية." >&2
    exit 1
fi

# Quick health check
HTTP=$(curl -s -o /dev/null -w "%{http_code}" --max-time 3 "$URL/villa-plan.html" 2>/dev/null)
if [ "$HTTP" = "200" ]; then
    echo "✅ $URL/villa-plan.html"
else
    echo "⚠️  الرابط موجود لكن ما يجاوب (HTTP $HTTP):"
    echo "$URL/villa-plan.html"
fi
