@echo off
setlocal EnableDelayedExpansion
title Gestione Colore - Bridge i1 Pro

:: ================================================================
::  DOPPIO CLICK — NON serve Amministratore
::  Installa Node + ArgyllCMS + npm + avvia bridge (tutto automatico)
:: ================================================================

cd /d "%~dp0"
set "BASE=%~dp0"
set "TOOLS=%BASE%tools"
set "NODE_DIR=%TOOLS%\node"
set "ARGYLL_DIR=%TOOLS%\argyll"
set "LOG=%TEMP%\gestione-colore-bridge.log"
set "GC_SERVER_URL=https://profiler.ktec.digital"
set "GC_WS_PORT=9876"

echo [%date% %time%] Avvio > "%LOG%"

if not exist package.json (
    echo.
    echo  ERRORE: package.json non trovato.
    echo  Questo file deve stare in:  C:\gestione-colore\client\
    echo.
    echo  Log: %LOG%
    pause
    exit /b 1
)

echo.
echo  =============================================
echo   GESTIONE COLORE - Bridge i1 Pro
echo   NON serve Amministratore
echo  =============================================
echo.

:: --- 1. Node.js portatile ---
if not exist "%NODE_DIR%\node.exe" (
    echo [1/4] Scarico Node.js ^(30 MB, solo prima volta^)...
    if not exist "%TOOLS%" mkdir "%TOOLS%"
    powershell -NoProfile -ExecutionPolicy Bypass -Command ^
      "try { $ProgressPreference='SilentlyContinue';" ^
      "Invoke-WebRequest -Uri 'https://nodejs.org/dist/v20.18.2/node-v20.18.2-win-x64.zip' -OutFile '%TOOLS%\node.zip';" ^
      "Expand-Archive -Path '%TOOLS%\node.zip' -DestinationPath '%TOOLS%' -Force;" ^
      "$d = Get-ChildItem '%TOOLS%' -Directory | Where-Object { $_.Name -like 'node-v*' } | Select-Object -First 1;" ^
      "if ($d) { if (Test-Path '%NODE_DIR%') { Remove-Item '%NODE_DIR%' -Recurse -Force };" ^
      "Move-Item $d.FullName '%NODE_DIR%' -Force };" ^
      "Remove-Item '%TOOLS%\node.zip' -Force -ErrorAction SilentlyContinue;" ^
      "exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"
    if errorlevel 1 (
        echo ERRORE scaricamento Node.js. Controlla internet.
        echo Log: %LOG%
        pause
        exit /b 1
    )
    if not exist "%NODE_DIR%\node.exe" (
        echo ERRORE Node.js non installato correttamente.
        pause
        exit /b 1
    )
    echo       OK - Node.js in tools\node\
) else (
    echo [1/4] Node.js gia presente.
)

set "PATH=%NODE_DIR%;%PATH%"
echo Node: >> "%LOG%"
"%NODE_DIR%\node.exe" -v >> "%LOG%" 2>&1

:: --- 2. ArgyllCMS portatile dal nostro server ---
set "ARGYLL_BIN="
if exist "%ARGYLL_DIR%\bin\spotread.exe" set "ARGYLL_BIN=%ARGYLL_DIR%\bin"
if exist "C:\Program Files\ArgyllCMS\bin\spotread.exe" set "ARGYLL_BIN=C:\Program Files\ArgyllCMS\bin"
if exist "C:\Program Files (x86)\ArgyllCMS\bin\spotread.exe" set "ARGYLL_BIN=C:\Program Files (x86)\ArgyllCMS\bin"

if not defined ARGYLL_BIN (
    echo [2/4] Scarico ArgyllCMS dal server ^(~35 MB, solo prima volta^)...
    if not exist "%TOOLS%" mkdir "%TOOLS%"
    powershell -NoProfile -ExecutionPolicy Bypass -Command ^
      "try { $ProgressPreference='SilentlyContinue';" ^
      "$url='%GC_SERVER_URL%/api/download/argyll';" ^
      "$zip='%TOOLS%\argyll.zip';" ^
      "Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing;" ^
      "if (-not (Test-Path $zip) -or (Get-Item $zip).Length -lt 1000000) { throw 'Download ArgyllCMS fallito o file troppo piccolo' };" ^
      "$tmp='%TOOLS%\_argyll_extract';" ^
      "if (Test-Path $tmp) { Remove-Item $tmp -Recurse -Force };" ^
      "Expand-Archive -Path $zip -DestinationPath $tmp -Force;" ^
      "$d = Get-ChildItem $tmp -Directory | Where-Object { $_.Name -like 'Argyll_V*' } | Select-Object -First 1;" ^
      "if (-not $d) { throw 'ZIP ArgyllCMS non valido' };" ^
      "if (Test-Path '%ARGYLL_DIR%') { Remove-Item '%ARGYLL_DIR%' -Recurse -Force };" ^
      "Move-Item $d.FullName '%ARGYLL_DIR%' -Force;" ^
      "Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue;" ^
      "Remove-Item $zip -Force -ErrorAction SilentlyContinue;" ^
      "if (-not (Test-Path '%ARGYLL_DIR%\bin\spotread.exe')) { throw 'spotread.exe non trovato dopo estrazione' };" ^
      "exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"
    if errorlevel 1 (
        echo ERRORE scaricamento ArgyllCMS da %GC_SERVER_URL%
        echo Verifica connessione internet e riprova.
        echo Log: %LOG%
        pause
        exit /b 1
    )
    set "ARGYLL_BIN=%ARGYLL_DIR%\bin"
    echo       OK - ArgyllCMS in tools\argyll\
) else (
    echo [2/4] ArgyllCMS gia presente: !ARGYLL_BIN!
)

set "ARGYLL_PATH=!ARGYLL_BIN!"

:: --- 3. Driver USB Argyll (una tantum, serve Admin) ---
if exist "%ARGYLL_DIR%\usb\ArgyllCMS_install_USB.exe" (
    if not exist "%TOOLS%\.argyll-usb-installed" (
        echo [3/4] Driver USB i1 Pro — serve Admin una sola volta.
        echo       Avvio install-argyll-usb.bat ^(accetta UAC se chiesto^)...
        call "%~dp0install-argyll-usb.bat"
    ) else (
        echo [3/4] Driver USB Argyll gia installato.
    )
) else if exist "C:\Program Files\ArgyllCMS\usb\ArgyllCMS_install_USB.exe" (
    if not exist "%TOOLS%\.argyll-usb-installed" (
        echo [3/4] Esegui come Admin: C:\Program Files\ArgyllCMS\usb\ArgyllCMS_install_USB.exe
    ) else (
        echo [3/4] Driver USB Argyll gia installato.
    )
) else (
    echo [3/4] Installer USB Argyll non trovato ^(opzionale se i1 gia funziona^).
)

:: --- 4. npm install ---
echo [4/4] Dipendenze npm...
if not exist node_modules (
    echo       Prima volta: 5-15 minuti, attendere...
    call npm install --no-fund --no-audit >> "%LOG%" 2>&1
    if errorlevel 1 (
        echo.
        echo  ERRORE npm install. Vedi log:
        echo  %LOG%
        type "%LOG%"
        pause
        exit /b 1
    )
    echo       OK
) else (
    echo       Gia installate.
)

:: --- Avvia bridge ---
echo.
echo  =============================================
echo   BRIDGE ATTIVO - NON CHIUDERE QUESTA FINESTRA
echo   Apri browser: %GC_SERVER_URL%
echo  =============================================
echo.

set "GC_SERVER_URL=%GC_SERVER_URL%"
set "GC_WS_PORT=%GC_WS_PORT%"

call npm start -- --bridge-only >> "%LOG%" 2>&1

echo.
echo  Bridge terminato. Log: %LOG%
pause
endlocal
