@echo off
chcp 936 >nul 2>&1
title Live Delay Player

echo ============================================
echo   Live Delay Player
echo   Open: http://localhost:8090
echo ============================================
echo.

cd /d "%~dp0"

:: ---- find python ----
set "PY="
where python >nul 2>&1 && set "PY=python"
if not defined PY where py >nul 2>&1 && set "PY=py"
if not defined PY (
    echo [ERROR] Python not found!
    echo.
    echo Please install Python 3.9+ from:
    echo   https://www.python.org/downloads/
    echo.
    echo IMPORTANT: Check "Add Python to PATH" during install!
    echo.
    pause
    exit /b 1
)

%PY% --version

:: ---- auto-install flask if missing ----
%PY% -c "import flask" >nul 2>&1
if errorlevel 1 (
    echo Installing Flask...
    %PY% -m pip install flask -q
)

:: ---- check ffmpeg ----
where ffmpeg >nul 2>&1
if errorlevel 1 (
    if exist "tools\ffmpeg\ffmpeg.exe" (
        echo [OK] FFmpeg: local bundle
    ) else (
        echo [WARN] FFmpeg not found!
        echo   Bilibili streams need FFmpeg.
        echo.
        choice /C YN /M "Download FFmpeg now (~80MB)?"
        if errorlevel 1 call :DL_FFMPEG
        if errorlevel 2 (
            echo.
            echo OK, continuing without FFmpeg...
            echo   Only direct m3u8/flv links will work.
            echo.
            choice /C YN /M "Continue anyway?"
            if errorlevel 2 exit /b 0
        )
    )
) else (
    echo [OK] FFmpeg: system
)

echo.
echo Starting server...  Open http://localhost:8090 in browser
echo Press Ctrl+C to stop.
echo.

%PY% -B -u scripts/server_portable.py

pause
goto :eof

:DL_FFMPEG
mkdir tools\ffmpeg 2>nul
echo Downloading FFmpeg (~80MB), please wait...
powershell -Command "$ProgressPreference='SilentlyContinue';[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;Invoke-WebRequest 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip' -OutFile '%TEMP%\ff.zip' -UseBasicParsing"
if errorlevel 1 (
    echo [!] Download failed. Manual download:
    echo   https://www.gyan.dev/ffmpeg/builds/
    goto :eof
)
echo Extracting...
powershell -Command "Expand-Archive '%TEMP%\ff.zip' '%TEMP%\ff_ex' -Force"
for /d %%d in ("%TEMP%\ff_ex\ffmpeg-*") do (
    copy /Y "%%d\bin\ffmpeg.exe" "tools\ffmpeg\" >nul 2>&1
    copy /Y "%%d\bin\ffprobe.exe" "tools\ffmpeg\" >nul 2>&1
)
del "%TEMP%\ff.zip" 2>nul & rmdir /s /q "%TEMP%\ff_ex" 2>nul
if exist "tools\ffmpeg\ffmpeg.exe" (
    echo [OK] FFmpeg installed!
) else (
    echo [!] Extract failed, please manual install
)
goto :eof
