@echo off
chcp 65001 >nul
setlocal enableextensions enabledelayedexpansion

set "TOOL_DIR=%~dp0"
set "PYTHONW=%TOOL_DIR%python\pythonw.exe"
set "SERVER=%TOOL_DIR%server.py"
set "RUNNER=%TOOL_DIR%_run_service.ps1"
set "REG_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Run"
set "REG_NAME=MediaDownloader"

if not exist "!PYTHONW!" (
  echo [ERROR] !PYTHONW! not found.
  echo Please re-download and extract ALL files.
  pause
  exit /b 1
)
if not exist "!SERVER!" (
  echo [ERROR] !SERVER! not found.
  echo Please re-download and extract ALL files.
  pause
  exit /b 1
)
if not exist "!RUNNER!" (
  echo [ERROR] !RUNNER! not found.
  echo Please re-download and extract ALL files.
  pause
  exit /b 1
)

echo Registering Media Downloader to Windows startup...
reg add "!REG_KEY!" /v "!REG_NAME!" /t REG_SZ /d "\"!PYTHONW!\" \"!SERVER!\"" /f >nul
if errorlevel 1 (
  echo [ERROR] Failed to register. Try right-click and "Run as administrator".
  pause
  exit /b 1
)
echo [OK] Startup registration done. The service will start on every login.

echo Starting service now...
powershell -NoProfile -ExecutionPolicy Bypass -File "!RUNNER!" -Python "!PYTHONW!" -Server "!SERVER!"
timeout /t 3 /nobreak >nul

netstat -ano | findstr /R /C":8765 " >nul 2>&1
if not errorlevel 1 (
  echo [OK] Service is running on http://127.0.0.1:8765
) else (
  echo [WARN] Service did not start. Try right-click and "Run as administrator".
  echo         If the problem persists, check Windows Defender or your antivirus.
)

echo.
echo Done. You can close this window now.
echo To remove autostart later, run the uninstall script included in this folder.
pause
endlocal
