@echo off
rem ============================================================
rem  Instalador del agente de impresion - POS Empresarial
rem
rem  Doble-clic UNA SOLA VEZ en cada PC de caja. El instalador:
rem    1. Verifica que print_agent.py este en la misma carpeta;
rem       si falta, lo descarga solo desde posempresarial.com.
rem    2. Busca Python en la PC. Si NO hay, descarga el solo una
rem       version portatil (carpeta python-embed, ~15 MB) — el
rem       cliente NO necesita instalar ni saber que es Python.
rem    3. Instala la dependencia pywin32.
rem    4. Registra una tarea programada que arranca el agente
rem       automaticamente al iniciar sesion (oculto, sin ventana).
rem    5. Inicia el agente de inmediato y VERIFICA que responda.
rem
rem  Despues de esto, imprimir desde la app es transparente:
rem  el usuario no tiene que abrir nada nunca mas.
rem ============================================================
chcp 65001 >nul
cd /d "%~dp0"

set "EMBED_DIR=%~dp0python-embed"
set "PYVER=3.12.10"
set "AGENT_URL=https://posempresarial.com/static/landing/empresarial/descargas/print_agent.py"
set "HEALTH_URL=http://127.0.0.1:9100/health"

echo.
echo === Instalador del agente de impresion ===
echo.

rem --- 0. Verificar que print_agent.py este junto al instalador ---
if exist "%~dp0print_agent.py" goto :buscar_python
echo El archivo print_agent.py no esta en esta carpeta; descargandolo...
where curl >nul 2>nul
if %errorlevel%==0 (
    curl -L -sS -o "%~dp0print_agent.py" "%AGENT_URL%"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -Uri '%AGENT_URL%' -OutFile '%~dp0print_agent.py'"
)
if exist "%~dp0print_agent.py" (
    echo [OK] print_agent.py descargado.
) else (
    echo [ERROR] No se pudo descargar print_agent.py.
    echo         Descargalo manualmente desde posempresarial.com/soporte/
    echo         y guardalo en la misma carpeta que este instalador.
    echo.
    pause
    exit /b 1
)

rem --- 1. Buscar Python del sistema (ignorando el alias de la Microsoft Store) ---
:buscar_python
set "PYTHONW="
for /f "delims=" %%i in ('where pythonw 2^>nul ^| findstr /v /i "WindowsApps"') do if not defined PYTHONW set "PYTHONW=%%i"
if not defined PYTHONW (
    for /f "delims=" %%i in ('where pyw 2^>nul ^| findstr /v /i "WindowsApps"') do if not defined PYTHONW set "PYTHONW=%%i"
)

if defined PYTHONW goto :python_sistema
if exist "%EMBED_DIR%\pythonw.exe" goto :python_portatil
goto :descargar_python

:python_sistema
echo [OK] Python encontrado: %PYTHONW%
rem Derivar el ejecutable de consola para pip (pythonw->python, pyw->py)
set "PYEXE=%PYTHONW:pythonw.exe=python.exe%"
if /i "%PYEXE%"=="%PYTHONW%" set "PYEXE=%PYTHONW:pyw.exe=py.exe%"
echo Instalando dependencia pywin32...
"%PYEXE%" -m pip install --quiet pywin32
if errorlevel 1 goto :error_pywin32
echo [OK] pywin32 instalado.
goto :registrar_tarea

:python_portatil
echo [OK] Usando el Python portatil de la carpeta python-embed.
set "PYTHONW=%EMBED_DIR%\pythonw.exe"
goto :registrar_tarea

:descargar_python
echo Esta PC no tiene Python instalado.
echo Se descargara una version portatil (solo esta vez, ~15 MB).
echo No cierres esta ventana...
echo.

set "ARCH=amd64"
if /i "%PROCESSOR_ARCHITECTURE%"=="x86" set "ARCH=win32"
if /i "%PROCESSOR_ARCHITECTURE%"=="ARM64" set "ARCH=arm64"
set "PYZIP=%TEMP%\python-%PYVER%-embed-%ARCH%.zip"
set "PYURL=https://www.python.org/ftp/python/%PYVER%/python-%PYVER%-embed-%ARCH%.zip"

where curl >nul 2>nul
if %errorlevel%==0 (
    curl -L -sS -o "%PYZIP%" "%PYURL%"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -Uri '%PYURL%' -OutFile '%PYZIP%'"
)
if not exist "%PYZIP%" goto :error_descarga

if not exist "%EMBED_DIR%" mkdir "%EMBED_DIR%"
where tar >nul 2>nul
if %errorlevel%==0 (
    tar -xf "%PYZIP%" -C "%EMBED_DIR%"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Expand-Archive -Path '%PYZIP%' -DestinationPath '%EMBED_DIR%' -Force"
)
del "%PYZIP%" >nul 2>nul
if not exist "%EMBED_DIR%\pythonw.exe" goto :error_descarga

rem Habilitar pip/site-packages en la version portatil (descomentar "import site" en python*._pth)
for %%f in ("%EMBED_DIR%"\python*._pth) do (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "(Get-Content '%%f') -replace '#import site','import site' | Set-Content '%%f'"
)

set "PYEXE=%EMBED_DIR%\python.exe"
set "PYTHONW=%EMBED_DIR%\pythonw.exe"

echo Instalando componentes de impresion...
set "GETPIP=%TEMP%\get-pip.py"
where curl >nul 2>nul
if %errorlevel%==0 (
    curl -L -sS -o "%GETPIP%" "https://bootstrap.pypa.io/get-pip.py"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -Uri 'https://bootstrap.pypa.io/get-pip.py' -OutFile '%GETPIP%'"
)
if not exist "%GETPIP%" goto :error_descarga
"%PYEXE%" "%GETPIP%" --quiet --no-warn-script-location
del "%GETPIP%" >nul 2>nul
"%PYEXE%" -m pip install --quiet pywin32
if errorlevel 1 goto :error_pywin32
echo [OK] Python portatil listo.

rem --- 2. Registrar tarea programada (arranque al iniciar sesion, oculto) ---
:registrar_tarea
schtasks /create /tn "DistribuidorPrintAgent" /tr "\"%PYTHONW%\" \"%~dp0print_agent.py\"" /sc onlogon /f >nul
if errorlevel 1 (
    echo [ERROR] No se pudo registrar la tarea de inicio automatico.
    echo         Intenta ejecutar este archivo como Administrador.
    pause
    exit /b 1
)
echo [OK] El agente arrancara solo cada vez que se inicie sesion.

rem --- 3. Iniciar el agente ahora mismo ---
schtasks /run /tn "DistribuidorPrintAgent" >nul 2>nul
if errorlevel 1 (
    echo [AVISO] No se pudo iniciar desde el Programador de tareas; iniciando directo...
    start "" "%PYTHONW%" "%~dp0print_agent.py"
)

rem --- 4. Verificar que el agente responda (hasta ~20 segundos) ---
echo Verificando que el agente este funcionando...
set "TRIES=0"
:verificar_agente
powershell -NoProfile -Command "try { $r = Invoke-WebRequest -Uri '%HEALTH_URL%' -UseBasicParsing -TimeoutSec 3; if ($r.StatusCode -eq 200) { exit 0 } else { exit 1 } } catch { exit 1 }"
if not errorlevel 1 goto :agente_ok
set /a TRIES+=1
if %TRIES% lss 10 (
    timeout /t 2 /nobreak >nul
    goto :verificar_agente
)
echo.
echo [ERROR] El agente se instalo pero no esta respondiendo.
echo         Posibles causas: un antivirus lo bloqueo o falta algun componente.
echo         1. Revisa el archivo print_agent.log en esta carpeta.
echo         2. Reinicia la PC y vuelve a abrir la app.
echo         3. Si sigue sin funcionar, contacta a soporte: WhatsApp +506 8520-3610.
echo.
pause
exit /b 1

:agente_ok
echo [OK] Agente verificado y funcionando.
echo.
echo === Instalacion completa ===
echo Ya puedes configurar la impresora en la app:
echo   Configuracion del negocio -^> Dispositivos -^> Impresora termica
echo   -^> "Impresora de Windows (agente local)" -^> Buscar impresoras
echo.
pause
exit /b 0

:error_descarga
echo.
echo [ERROR] No se pudo descargar el Python portatil.
echo         Verifica la conexion a internet y vuelve a ejecutar este archivo.
echo.
pause
exit /b 1

:error_pywin32
echo.
echo [ERROR] No se pudo instalar el componente de impresion (pywin32).
echo         Verifica la conexion a internet y vuelve a ejecutar este archivo.
echo.
pause
exit /b 1
