@echo off
title Instalador Frota Trucks
color 0A

net session >nul 2>&1
if not %errorlevel%==0 (
echo ==========================================
echo   PRECISA SER ADMINISTRADOR
echo ==========================================
echo.
echo Clique com o botao direito neste arquivo e escolha
echo "Executar como administrador".
echo.
pause
exit /b 1
)

set SERVICE_NAME=FrotaTrucks
set BASE_DIR=%~dp0
set BASE_DIR=%BASE_DIR:~0,-1%
set PYTHON_EXE=%BASE_DIR%\python\python.exe
set NSSM_EXE=%BASE_DIR%\nssm.exe

echo ==========================================
echo   INSTALACAO FROTA TRUCKS
echo ==========================================
echo.

if not exist "%PYTHON_EXE%" (
echo [ERRO] Python nao encontrado em:
echo %PYTHON_EXE%
pause
exit /b 1
)

if not exist "%NSSM_EXE%" (
echo [ERRO] NSSM nao encontrado em:
echo %NSSM_EXE%
pause
exit /b 1
)

echo Liberando firewall...

netsh advfirewall firewall add rule name="Frota Trucks 8642 TCP" dir=in action=allow protocol=TCP localport=8642 >nul 2>&1
netsh advfirewall firewall add rule name="Frota Trucks Python" dir=in action=allow program="%PYTHON_EXE%" enable=yes >nul 2>&1

echo Firewall configurado.

echo.
echo Ajustando rede para PRIVADA...

powershell -Command "Get-NetConnectionProfile | ForEach-Object { Set-NetConnectionProfile -Name $_.Name -NetworkCategory Private }" >nul 2>&1

echo.
echo Removendo servico antigo (se existir)...

sc query "%SERVICE_NAME%" >nul 2>&1
if %errorlevel%==0 (
net stop "%SERVICE_NAME%" >nul 2>&1
"%NSSM_EXE%" remove "%SERVICE_NAME%" confirm >nul 2>&1
timeout /t 2 >nul
)

echo.
echo Instalando servico...

"%NSSM_EXE%" install "%SERVICE_NAME%" "%PYTHON_EXE%"
"%NSSM_EXE%" set "%SERVICE_NAME%" AppParameters "-m uvicorn app.main:app --host 0.0.0.0 --port 8642"
"%NSSM_EXE%" set "%SERVICE_NAME%" AppDirectory "%BASE_DIR%"
"%NSSM_EXE%" set "%SERVICE_NAME%" Start SERVICE_AUTO_START
"%NSSM_EXE%" set "%SERVICE_NAME%" AppExit Default Restart
"%NSSM_EXE%" set "%SERVICE_NAME%" AppStdout "%BASE_DIR%\servico.log"
"%NSSM_EXE%" set "%SERVICE_NAME%" AppStderr "%BASE_DIR%\servico.log"
"%NSSM_EXE%" set "%SERVICE_NAME%" AppRotateFiles 1
"%NSSM_EXE%" set "%SERVICE_NAME%" AppRotateBytes 1048576

echo.
echo Iniciando servico...

net start "%SERVICE_NAME%"

if errorlevel 1 (
echo [ERRO] Servico nao iniciou. Veja %BASE_DIR%servico.log
pause
exit /b 1
)

echo.
echo ==========================================
echo   INSTALADO COM SUCESSO
echo ==========================================
echo.
echo O programa agora roda sozinho em segundo plano, sem
echo nenhuma janela, e inicia automaticamente com o Windows.
echo.

timeout /t 2 /nobreak >nul
start http://localhost:8642
exit /b 0
