@echo off
setlocal enabledelayedexpansion

:: ---- Check/Install cloudflared ----
where cloudflared >nul 2>nul
if errorlevel 1 (
    echo cloudflared not found. Downloading...
    set "CF_URL=https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe"
    set "CF_PATH=%~dp0cloudflared.exe"
    
    :: Try PowerShell download
    powershell -Command "Invoke-WebRequest -Uri '!CF_URL!' -OutFile '!CF_PATH!'" 2>nul
    if not exist "!CF_PATH!" (
        :: Fallback to curl
        curl -Lo "!CF_PATH!" "!CF_URL!" 2>nul
    )
    if not exist "!CF_PATH!" (
        echo Failed to download cloudflared.
        echo Please install manually from:
        echo https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/
        pause
        exit /b 1
    )
    set "PATH=%~dp0;!PATH!"
    echo cloudflared downloaded to !CF_PATH!
)
echo cloudflared is ready.
echo.

:: ---- Start tunnel ----
:: NOTE: Quick Tunnels (trycloudflare.com) auto-assign a subdomain.
:: You cannot choose a custom subdomain with --hostname unless you have
:: a configured named tunnel. The --hostname flag is ignored for quick tunnels.
echo Starting Cloudflare Quick Tunnel on localhost:80 ...
echo.

:: cloudflared outputs to stderr, so we redirect 2>&1 to capture it.
:: We use a temp file approach since for /f won't reliably stream long-running processes.
set "TUNNEL_LOG=%TEMP%\cfd_tunnel_%RANDOM%.log"

start "" /b cmd /c "cloudflared tunnel --protocol http2 --url http://localhost 2>&1 > "!TUNNEL_LOG!""

:: Poll the log for the tunnel URL
set "TUNNEL_URL="
echo Waiting for tunnel URL...
for /l %%i in (1,1,60) do (
    if not defined TUNNEL_URL (
        timeout /t 2 /nobreak >nul
        for /f "tokens=*" %%L in ('findstr /i "https://.*trycloudflare.com" "!TUNNEL_LOG!" 2^>nul') do (
            set "LINE=%%L"
            for %%W in (!LINE!) do (
                echo %%W | findstr /i "^https://.*trycloudflare.com" >nul
                if not errorlevel 1 (
                    set "TUNNEL_URL=%%W"
                )
            )
        )
    )
)

if defined TUNNEL_URL (
    echo.
    echo ========================================
    echo   Tunnel is live:
    echo   !TUNNEL_URL!
    echo ========================================
    echo.
    start "" "!TUNNEL_URL!"
) else (
    echo.
    echo Could not detect tunnel URL within 120 seconds.
    echo Check the log: !TUNNEL_LOG!
)

echo Press any key to stop the tunnel...
pause >nul

:: Kill cloudflared on exit
taskkill /f /im cloudflared.exe >nul 2>nul
del "!TUNNEL_LOG!" >nul 2>nul

endlocal