@echo off
chcp 65001 > nul
title Setup - ContabilitaFamily
cd /d "%~dp0"

echo.
echo  ============================================
echo    ContabilitaFamily - Setup iniziale
echo  ============================================
echo.
echo  Scarica Python portatile e installa le librerie.
echo  Richiede connessione internet (una sola volta).
echo.
pause

set PYVER=3.11.9
set PYDIR=python
set PWSH=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe

if exist "%PYDIR%\python.exe" (
    echo  Python locale gia presente. Aggiorno le dipendenze...
    goto :install_deps
)

echo  [1/3] Scarico Python %PYVER%...
%PWSH% -NoProfile -Command "Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/%PYVER%/python-%PYVER%-embed-amd64.zip' -OutFile 'python-embed.zip' -UseBasicParsing"
if %ERRORLEVEL% NEQ 0 ( echo  ERRORE: download fallito. & pause & exit /b 1 )
echo         OK

echo  [2/3] Estraggo Python...
%PWSH% -NoProfile -Command "Expand-Archive -Path 'python-embed.zip' -DestinationPath 'python' -Force"
del "python-embed.zip"
%PWSH% -NoProfile -Command "$f=Get-ChildItem 'python' -Filter 'python*._pth' | Select-Object -First 1; (Get-Content $f.FullName) -replace '#import site','import site' | Set-Content $f.FullName"
echo         OK

echo  [3/3] Installo pip e dipendenze...
%PWSH% -NoProfile -Command "Invoke-WebRequest -Uri 'https://bootstrap.pypa.io/get-pip.py' -OutFile 'get-pip.py' -UseBasicParsing"
python\python.exe get-pip.py --quiet
del "get-pip.py"

:install_deps
python\python.exe -m pip install flask openpyxl werkzeug pywebview --quiet --upgrade
if %ERRORLEVEL% NEQ 0 ( echo  ERRORE: installazione dipendenze fallita. & pause & exit /b 1 )

echo.
echo  ============================================
echo    Setup completato! Usa avvia.bat per partire.
echo  ============================================
echo.
pause
