@echo off
rem Controlla se Python e VS Code sono gia' installati; installa solo quelli
rem mancanti (per tutto il sistema), sistema il PATH se serve, verifica,
rem esegue un hello world e installa l'estensione Python di VS Code.
rem Doppio click: chiede da solo i permessi di amministratore.
rem
rem Fonti:
rem  - winget install: https://learn.microsoft.com/windows/package-manager/winget/install
rem  - opzioni installer Python (InstallAllUsers, PrependPath):
rem    https://docs.python.org/3/using/windows.html#installing-without-ui
rem  - registro di Python (PEP 514): https://peps.python.org/pep-0514/
rem  - opzioni installer VS Code (Inno Setup, task addtopath):
rem    https://code.visualstudio.com/docs/setup/windows
rem  - code --install-extension: https://code.visualstudio.com/docs/configure/command-line
setlocal

set "PY_ID=Python.Python.3.14"
set "HELLO_DIR=%USERPROFILE%\dh101"

rem --- 1. Permessi di amministratore (net session riesce solo da admin) ---
net session >nul 2>&1
if errorlevel 1 (
    echo Servono i permessi di amministratore, li chiedo...
    powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

rem --- 2. winget presente? ---
where winget >nul 2>&1
if errorlevel 1 (
    echo [ERRORE] winget non trovato. Installa/aggiorna "App Installer" dal Microsoft Store e riprova.
    goto :fine
)

rem --- 3. Python: controllo, poi installo o sistemo il PATH ---
echo.
echo === Controllo Python ===
call :trova_python
if defined PY_OK (
    echo Python gia' installato e nel PATH, salto l'installazione.
    goto :vscode
)
if defined PY_DIR (
    echo Python gia' installato in "%PY_DIR%" ma non nel PATH: lo aggiungo.
    call :aggiungi_path "%PY_DIR%"
    call :aggiungi_path "%PY_DIR%\Scripts"
    goto :vscode
)
echo Python non trovato, lo installo...
winget install -e --id %PY_ID% --scope machine --accept-package-agreements --accept-source-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_launcher=1"
call :ricarica_path

:vscode
rem --- 4. VS Code: controllo, poi installo o sistemo il PATH ---
echo.
echo === Controllo Visual Studio Code ===
call :trova_code
if defined CODE_OK (
    echo VS Code gia' installato e nel PATH, salto l'installazione.
    goto :verifiche
)
if defined CODE_BIN (
    echo VS Code gia' installato ma "code" non e' nel PATH: aggiungo "%CODE_BIN%".
    call :aggiungi_path "%CODE_BIN%"
    goto :verifiche
)
echo VS Code non trovato, lo installo...
winget install -e --id Microsoft.VisualStudioCode --scope machine --accept-package-agreements --accept-source-agreements --override "/VERYSILENT /NORESTART /MERGETASKS=!runcode,addtopath,addcontextmenufiles,addcontextmenufolders"
call :ricarica_path

:verifiche
rem --- 5. Verifiche ---
echo.
echo === Verifico Python ===
rem Lo stub "python" del Microsoft Store (WindowsApps) fallisce con -c, quindi questo test lo esclude.
python -c "import sys; print(sys.version); print(sys.executable)"
if errorlevel 1 (
    echo [ERRORE] Python non risulta nel PATH. Riavvia il PC e rilancia lo script.
    goto :fine
)

echo.
echo === Verifico VS Code ===
call code --version
if errorlevel 1 (
    echo [ERRORE] VS Code ^(comando "code"^) non risulta nel PATH. Riavvia il PC e rilancia lo script.
    goto :fine
)

rem --- 6. Hello world ---
echo.
echo === Hello world ===
if not exist "%HELLO_DIR%" mkdir "%HELLO_DIR%"
> "%HELLO_DIR%\hello.py" echo print("Hello, world!")
python "%HELLO_DIR%\hello.py"
if errorlevel 1 (
    echo [ERRORE] hello.py non e' partito.
    goto :fine
)

rem --- 7. Estensione Python per VS Code ---
echo.
echo === Installo l'estensione Python per VS Code ===
call code --install-extension ms-python.python --force
call code --list-extensions | findstr /i /l /b /c:"ms-python.python" >nul
if errorlevel 1 (
    echo [ERRORE] Estensione ms-python.python non installata.
    goto :fine
)

echo.
echo ============================================
echo  Tutto ok! Il file di prova e' in:
echo  %HELLO_DIR%\hello.py
echo ============================================

:fine
echo.
pause
exit /b


rem ===================== Subroutine =====================

:trova_python
rem PY_OK = un Python vero risponde dal PATH (lo stub dello Store fallisce con -c).
rem PY_DIR = cartella di installazione trovata nel registro (PEP 514), versione piu' alta.
set "PY_OK="
set "PY_DIR="
python -c "import sys" >nul 2>&1
if not errorlevel 1 set "PY_OK=1"
for /f "usebackq delims=" %%d in (`powershell -NoProfile -Command "$r = foreach ($b in 'HKLM:\SOFTWARE\Python\PythonCore','HKCU:\SOFTWARE\Python\PythonCore','HKLM:\SOFTWARE\WOW6432Node\Python\PythonCore') { Get-ChildItem $b -ErrorAction SilentlyContinue | ForEach-Object { $p = (Get-ItemProperty (Join-Path $_.PSPath 'InstallPath') -ErrorAction SilentlyContinue).'(default)'; if ($p -and (Test-Path (Join-Path $p 'python.exe'))) { [pscustomobject]@{ V = [version](($_.PSChildName -split '-')[0] -replace '[^0-9.]',''); P = $p.TrimEnd('\') } } } }; ($r | Sort-Object V -Descending | Select-Object -First 1).P"`) do set "PY_DIR=%%d"
exit /b

:trova_code
rem CODE_OK = il comando "code" risponde dal PATH.
rem CODE_BIN = cartella bin di VS Code trovata nel registro o nei percorsi standard.
set "CODE_OK="
set "CODE_BIN="
call code --version >nul 2>&1
if not errorlevel 1 set "CODE_OK=1"
for /f "usebackq delims=" %%d in (`powershell -NoProfile -Command "$u = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*','HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like 'Microsoft Visual Studio Code*' } | ForEach-Object { $_.InstallLocation }; $d = @($u) + (Join-Path $env:ProgramFiles 'Microsoft VS Code') + (Join-Path $env:LOCALAPPDATA 'Programs\Microsoft VS Code') | Where-Object { $_ -and (Test-Path (Join-Path $_ 'bin\code.cmd')) } | Select-Object -First 1; if ($d) { Join-Path $d.TrimEnd('\') 'bin' }"`) do set "CODE_BIN=%%d"
exit /b

:aggiungi_path
rem Aggiunge %1 al PATH di sistema (se manca), mantenendo il tipo REG_EXPAND_SZ,
rem avvisa le altre finestre del cambio e ricarica il PATH di questa finestra.
set "ADD_DIR=%~1"
powershell -NoProfile -Command "$k = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true); $old = $k.GetValue('Path', '', 'DoNotExpandEnvironmentNames'); $dir = $env:ADD_DIR.TrimEnd('\'); $parti = $old -split ';' | Where-Object { $_ }; if ($parti | Where-Object { [Environment]::ExpandEnvironmentVariables($_).TrimEnd('\') -ieq $dir }) { Write-Host ('  gia'' nel PATH: ' + $dir) } else { $k.SetValue('Path', (@($parti) + $dir) -join ';', 'ExpandString'); [Environment]::SetEnvironmentVariable('DH101_TMP', '1', 'User'); [Environment]::SetEnvironmentVariable('DH101_TMP', $null, 'User'); Write-Host ('  aggiunto al PATH: ' + $dir) }"
call :ricarica_path
exit /b

:ricarica_path
rem Questa finestra non vede le modifiche al PATH: le rileggo dal registro (sistema + utente).
for /f "usebackq delims=" %%p in (`powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User')"`) do set "PATH=%%p"
exit /b
