@echo off
setlocal

set "ROOT=%~dp0"
set "VENV=%ROOT%.venv\Scripts\activate.bat"

if not exist "%VENV%" (
  echo No se encontro el entorno virtual en "%VENV%".
  echo Crea o corrige la carpeta .venv antes de iniciar el backend.
  pause
  exit /b 1
)

title Video Editor Backend
cd /d "%ROOT%backend"
call "%VENV%"

set "BACKEND_PORT=%VIDEO_EDITOR_BACKEND_PORT%"
if "%BACKEND_PORT%"=="" set "BACKEND_PORT=8000"

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$port = '%BACKEND_PORT%'; $listener = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1; if (-not $listener) { exit 0 }; $process = Get-CimInstance Win32_Process -Filter ('ProcessId = ' + $listener.OwningProcess) -ErrorAction SilentlyContinue; $commandLine = [string]($process.CommandLine ?? ''); if ($commandLine -match ('manage\.py\s+runserver\s+127\.0\.0\.1:' + [regex]::Escape($port) + '(?:\s|$)')) { Write-Host ('Deteniendo backend Django previo en puerto ' + $port + ' (PID ' + $listener.OwningProcess + ')...') -ForegroundColor DarkYellow; Stop-Process -Id $listener.OwningProcess -Force -ErrorAction SilentlyContinue; exit 0 }; Write-Host ('El puerto ' + $port + ' ya esta ocupado por otro proceso (PID ' + $listener.OwningProcess + ').') -ForegroundColor Red; exit 3"
if errorlevel 3 (
  echo Cierra ese proceso o cambia VIDEO_EDITOR_BACKEND_PORT antes de iniciar el backend.
  pause
  exit /b 1
)

echo Iniciando backend Django en http://127.0.0.1:%BACKEND_PORT%
if /I "%VIDEO_EDITOR_BACKEND_AUTORELOAD%"=="1" goto :run_autoreload
if /I "%VIDEO_EDITOR_BACKEND_AUTORELOAD%"=="true" goto :run_autoreload
if /I "%VIDEO_EDITOR_BACKEND_AUTORELOAD%"=="yes" goto :run_autoreload
if /I "%VIDEO_EDITOR_BACKEND_AUTORELOAD%"=="on" goto :run_autoreload

echo Autoreload desactivado por defecto para no interrumpir jobs en memoria como estabilización/export.
echo Usa VIDEO_EDITOR_BACKEND_AUTORELOAD=1 si quieres activarlo manualmente.
python manage.py runserver 127.0.0.1:%BACKEND_PORT% --noreload
goto :after_run

:run_autoreload
echo Autoreload activo por VIDEO_EDITOR_BACKEND_AUTORELOAD.
python manage.py runserver 127.0.0.1:%BACKEND_PORT%

:after_run

echo.
echo El backend se detuvo o devolvio un error.
echo Codigo de salida: %errorlevel%
pause