@echo off
:: RepairIQ Sync Agent - Windows Service Installer v1.3.7
:: ONE-CLICK INSTALLER: Automatically installs Node.js if needed
:: Double-click this file (Run as Administrator) to install

setlocal enabledelayedexpansion

:: Define paths
set "INSTALL_DIR=C:\Program Files\RepairIQ"
set "SOURCE_DIR=%~dp0"
set "WATCH_DIR=C:\RepairIQ-EMS"
set "UPDATES_DIR=%WATCH_DIR%\updates"
set "LOG_FILE=%WATCH_DIR%\logs\install.log"

:: Node.js configuration
set "NODE_VERSION=20.11.0"
set "NODE_MSI=node-v%NODE_VERSION%-x64.msi"
set "NODE_URL=https://nodejs.org/dist/v%NODE_VERSION%/%NODE_MSI%"
set "NODE_INSTALLER=%TEMP%\%NODE_MSI%"

echo =====================================
echo RepairIQ Sync Agent - One-Click Installer
echo Version 1.3.7
echo =====================================
echo.

:: Check for Administrator privileges
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo ERROR: Administrator privileges required!
    echo.
    echo Please right-click this file and select "Run as administrator"
    echo.
    pause
    exit /b 1
)

:: Create log directory early
if not exist "%WATCH_DIR%\logs" mkdir "%WATCH_DIR%\logs"

:: Log start
echo [%date% %time%] Installation started >> "%LOG_FILE%"

echo [1/9] Checking Node.js installation...
echo [%date% %time%] Checking Node.js... >> "%LOG_FILE%"

:: Check if Node.js is installed
node --version >nul 2>&1
if %errorLevel% equ 0 (
    for /f "tokens=*" %%i in ('node --version') do set NODE_VER=%%i
    echo       Node.js found: !NODE_VER!
    echo [%date% %time%] Node.js found: !NODE_VER! >> "%LOG_FILE%"
    goto :nodejs_ready
)

echo       Node.js NOT found - installing automatically...
echo [%date% %time%] Node.js not found, starting auto-install >> "%LOG_FILE%"
echo.

echo [2/9] Downloading Node.js v%NODE_VERSION%...
echo       URL: %NODE_URL%
echo       This may take 1-2 minutes...
echo [%date% %time%] Downloading from %NODE_URL% >> "%LOG_FILE%"

:: Download Node.js with retry logic
set DOWNLOAD_ATTEMPTS=0

:download_retry
set /a DOWNLOAD_ATTEMPTS+=1
if %DOWNLOAD_ATTEMPTS% gtr 3 (
    echo.
    echo ERROR: Failed to download Node.js after 3 attempts!
    echo [%date% %time%] ERROR: Download failed after 3 attempts >> "%LOG_FILE%"
    echo.
    echo Please install Node.js manually from: https://nodejs.org
    echo Then run this installer again.
    echo.
    pause
    exit /b 1
)

echo       Attempt %DOWNLOAD_ATTEMPTS%/3...

:: Use PowerShell to download (more reliable than bitsadmin)
powershell -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest -Uri '%NODE_URL%' -OutFile '%NODE_INSTALLER%' -UseBasicParsing; exit 0 } catch { Write-Host $_.Exception.Message; exit 1 }"

if %errorLevel% neq 0 (
    echo       Download attempt %DOWNLOAD_ATTEMPTS% failed, retrying...
    timeout /t 3 /nobreak >nul
    goto :download_retry
)

:: Verify download exists and has size > 0
if not exist "%NODE_INSTALLER%" (
    echo       Download file not found, retrying...
    timeout /t 3 /nobreak >nul
    goto :download_retry
)

for %%A in ("%NODE_INSTALLER%") do set NODE_SIZE=%%~zA
if %NODE_SIZE% lss 1000000 (
    echo       Download too small (%NODE_SIZE% bytes), retrying...
    del "%NODE_INSTALLER%" >nul 2>&1
    timeout /t 3 /nobreak >nul
    goto :download_retry
)

echo       Downloaded successfully (%NODE_SIZE% bytes)
echo [%date% %time%] Downloaded %NODE_SIZE% bytes >> "%LOG_FILE%"
echo.

echo [3/9] Installing Node.js (this takes 2-3 minutes)...
echo       Please wait, do not close this window...
echo [%date% %time%] Starting Node.js installation >> "%LOG_FILE%"

:: Run silent installation
msiexec /i "%NODE_INSTALLER%" /quiet /norestart /log "%WATCH_DIR%\logs\nodejs-install.log"

if %errorLevel% neq 0 (
    echo.
    echo ERROR: Node.js installation failed! (Error code: %errorLevel%)
    echo [%date% %time%] ERROR: MSI installation failed with code %errorLevel% >> "%LOG_FILE%"
    echo.
    echo Please check the log at: %WATCH_DIR%\logs\nodejs-install.log
    echo Or install Node.js manually from: https://nodejs.org
    echo.
    pause
    exit /b 1
)

echo       MSI installation completed
echo [%date% %time%] MSI installation completed >> "%LOG_FILE%"

:: Wait for installation to fully complete and PATH to update
echo       Waiting for installation to finalize...
timeout /t 10 /nobreak >nul

:: Refresh environment variables (PATH)
echo       Refreshing environment...
call refreshenv >nul 2>&1

:: If refreshenv doesn't exist, manually add Node.js to PATH for this session
set "PATH=%PATH%;C:\Program Files\nodejs;%APPDATA%\npm"

:: Verify Node.js is now available
echo       Verifying installation...

node --version >nul 2>&1
if %errorLevel% neq 0 (
    :: Try direct path
    "C:\Program Files\nodejs\node.exe" --version >nul 2>&1
    if %errorLevel% neq 0 (
        echo.
        echo ERROR: Node.js installed but not accessible!
        echo [%date% %time%] ERROR: Node.js not accessible after install >> "%LOG_FILE%"
        echo.
        echo Please restart your computer and run this installer again.
        echo.
        pause
        exit /b 1
    )
    :: Use direct path for remainder of script
    set "NODE_CMD=C:\Program Files\nodejs\node.exe"
) else (
    set "NODE_CMD=node"
)

for /f "tokens=*" %%i in ('"%NODE_CMD%" --version') do set NODE_VER=%%i
echo       Node.js %NODE_VER% installed successfully!
echo [%date% %time%] Node.js %NODE_VER% installed successfully >> "%LOG_FILE%"

:: Cleanup installer
del "%NODE_INSTALLER%" >nul 2>&1
echo.

:nodejs_ready
:: Set NODE_CMD if not already set
if not defined NODE_CMD set "NODE_CMD=node"

echo [4/9] Creating directories with full permissions...
if not exist "%INSTALL_DIR%" (
    mkdir "%INSTALL_DIR%"
    echo       Created: %INSTALL_DIR%
) else (
    echo       Exists: %INSTALL_DIR%
)
if not exist "%WATCH_DIR%" mkdir "%WATCH_DIR%"
if not exist "%WATCH_DIR%\Processed" mkdir "%WATCH_DIR%\Processed"
if not exist "%WATCH_DIR%\logs" mkdir "%WATCH_DIR%\logs"
if not exist "%UPDATES_DIR%" mkdir "%UPDATES_DIR%"

:: CRITICAL: Grant full permissions to Everyone for CCC ONE to write files
echo       Setting permissions for CCC ONE...
icacls "%WATCH_DIR%" /grant "Everyone:(OI)(CI)F" /T >nul 2>&1
if %errorLevel% equ 0 (
    echo       Permissions: Everyone has full access to %WATCH_DIR%
    echo [%date% %time%] Permissions set for %WATCH_DIR% >> "%LOG_FILE%"
) else (
    echo       WARNING: Could not set permissions - CCC ONE may not be able to write files
    echo [%date% %time%] WARNING: icacls failed >> "%LOG_FILE%"
)

:: Create empty customers.xlsx with headers (for Excel dual-feed)
if not exist "%WATCH_DIR%\customers.xlsx" (
    echo       Creating customers.xlsx template...
    powershell -ExecutionPolicy Bypass -Command "$excel = New-Object -ComObject Excel.Application; $excel.Visible = $false; $excel.DisplayAlerts = $false; $wb = $excel.Workbooks.Add(); $ws = $wb.Worksheets.Item(1); $ws.Name = 'Customers'; $headers = @('Customer Name', 'Phone', 'Email', 'VIN', 'Year', 'Make', 'Model', 'Color', 'License Plate', 'Insurance Company', 'Check-In Date'); for ($i = 0; $i -lt $headers.Length; $i++) { $ws.Cells.Item(1, $i + 1) = $headers[$i]; $ws.Cells.Item(1, $i + 1).Font.Bold = $true }; $ws.Columns.AutoFit() | Out-Null; $wb.SaveAs('%WATCH_DIR%\customers.xlsx', 51); $wb.Close(); $excel.Quit(); [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null" >nul 2>&1
    if exist "%WATCH_DIR%\customers.xlsx" (
        echo       Created: customers.xlsx with headers
        echo [%date% %time%] Created customers.xlsx template >> "%LOG_FILE%"
    ) else (
        echo       NOTE: Could not create customers.xlsx - will be created on first export
        echo [%date% %time%] NOTE: customers.xlsx creation skipped >> "%LOG_FILE%"
    )
) else (
    echo       Exists: customers.xlsx
)

echo       Created watch folders: %WATCH_DIR%
echo       Created updates folder: %UPDATES_DIR%
echo [%date% %time%] Directories created >> "%LOG_FILE%"
echo.

echo [5/9] Copying files to %INSTALL_DIR%...
echo       This may take a moment (node_modules is large)...
echo [%date% %time%] Copying files >> "%LOG_FILE%"

:: Copy dist folder
if exist "%SOURCE_DIR%dist" (
    xcopy "%SOURCE_DIR%dist" "%INSTALL_DIR%\dist\" /E /I /Y /Q >nul
    echo       Copied: dist\
) else (
    echo ERROR: dist folder not found!
    echo [%date% %time%] ERROR: dist folder not found >> "%LOG_FILE%"
    pause
    exit /b 1
)

:: Copy node_modules folder
if exist "%SOURCE_DIR%node_modules" (
    xcopy "%SOURCE_DIR%node_modules" "%INSTALL_DIR%\node_modules\" /E /I /Y /Q >nul
    echo       Copied: node_modules\
) else (
    echo ERROR: node_modules folder not found!
    echo [%date% %time%] ERROR: node_modules folder not found >> "%LOG_FILE%"
    pause
    exit /b 1
)

:: Copy package.json
if exist "%SOURCE_DIR%package.json" (
    copy /Y "%SOURCE_DIR%package.json" "%INSTALL_DIR%\" >nul
    echo       Copied: package.json
) else (
    echo ERROR: package.json not found!
    echo [%date% %time%] ERROR: package.json not found >> "%LOG_FILE%"
    pause
    exit /b 1
)

:: Copy service-install.js
if exist "%SOURCE_DIR%service-install.js" (
    copy /Y "%SOURCE_DIR%service-install.js" "%INSTALL_DIR%\" >nul
    echo       Copied: service-install.js
)

:: Copy service-uninstall.js
if exist "%SOURCE_DIR%service-uninstall.js" (
    copy /Y "%SOURCE_DIR%service-uninstall.js" "%INSTALL_DIR%\" >nul
    echo       Copied: service-uninstall.js
)

:: Copy updater-task.ps1
if exist "%SOURCE_DIR%updater-task.ps1" (
    copy /Y "%SOURCE_DIR%updater-task.ps1" "%INSTALL_DIR%\" >nul
    echo       Copied: updater-task.ps1
) else (
    echo WARNING: updater-task.ps1 not found - auto-updates may not work
)

:: Copy .env if exists, otherwise create default with all settings
if exist "%SOURCE_DIR%.env" (
    copy /Y "%SOURCE_DIR%.env" "%INSTALL_DIR%\" >nul
    echo       Copied: .env
) else if exist "%INSTALL_DIR%\.env" (
    echo       Using existing .env
) else (
    (
        echo # RepairIQ Sync Agent Configuration
        echo WATCH_FOLDER=%WATCH_DIR%
        echo API_URL=https://www.repairiq.app
        echo COMPANY_ID=default
        echo WAIT_TIME=5000
        echo.
        echo # Excel Dual-Feed - ENABLED BY DEFAULT for enterprise deployment
        echo EXCEL_ENABLED=true
        echo EXCEL_OUTPUT_PATH=%WATCH_DIR%\customers.xlsx
        echo EXCEL_MAX_ROWS=1000
    ) > "%INSTALL_DIR%\.env"
    echo       Created default .env with Excel ENABLED
)

echo [%date% %time%] Files copied >> "%LOG_FILE%"
echo.

echo [6/9] Stopping existing service (if running)...
sc stop RepairIQSyncAgent >nul 2>&1
timeout /t 2 /nobreak >nul
sc delete RepairIQSyncAgent >nul 2>&1
timeout /t 2 /nobreak >nul
echo       Ready for fresh install
echo [%date% %time%] Old service removed >> "%LOG_FILE%"
echo.

echo [7/9] Installing Windows Service from %INSTALL_DIR%...
echo [%date% %time%] Installing Windows Service >> "%LOG_FILE%"

:: Change to install directory so service installs from correct location
cd /d "%INSTALL_DIR%"
"%NODE_CMD%" service-install.js
if %errorLevel% neq 0 (
    echo ERROR: Service installation failed!
    echo [%date% %time%] ERROR: Service installation failed >> "%LOG_FILE%"
    echo.
    pause
    exit /b 1
)
echo [%date% %time%] Windows Service installed >> "%LOG_FILE%"
echo.

echo [8/9] Creating Scheduled Task for auto-updates...
echo [%date% %time%] Creating scheduled task >> "%LOG_FILE%"

:: Remove existing task if present
schtasks /Delete /TN "RepairIQUpdater" /F >nul 2>&1

:: Create the scheduled task that runs as SYSTEM with highest privileges
:: Use DAILY trigger at 23:59 to allow on-demand execution (ONCE trigger stays queued)
:: The daily trigger also serves as a safety fallback check
:: /IT = Allow running on battery (needed for laptops)
:: Note: /NP removed - incompatible with /IT, and not needed for SYSTEM account
schtasks /Create /TN "RepairIQUpdater" /TR "powershell.exe -ExecutionPolicy Bypass -NoProfile -File \"%INSTALL_DIR%\updater-task.ps1\"" /SC DAILY /ST 23:59 /RU "SYSTEM" /RL HIGHEST /IT /F >nul 2>&1

if %errorLevel% neq 0 (
    echo WARNING: Failed to create scheduled task
    echo          Auto-updates may not work correctly
    echo [%date% %time%] WARNING: Scheduled task creation failed >> "%LOG_FILE%"
) else (
    echo       Created: RepairIQUpdater task
    echo       Runs as: SYSTEM
    echo       Script: %INSTALL_DIR%\updater-task.ps1
    echo [%date% %time%] Scheduled task created >> "%LOG_FILE%"
)
echo.

echo [9/9] Verifying installation...
echo [%date% %time%] Verifying installation >> "%LOG_FILE%"

:: Check service exists and is running
sc query RepairIQSyncAgent >nul 2>&1
if %errorLevel% neq 0 (
    echo WARNING: Service may not be installed correctly
    echo [%date% %time%] WARNING: Service verification failed >> "%LOG_FILE%"
) else (
    echo       Service: RepairIQSyncAgent - OK
)

:: Check scheduled task exists
schtasks /Query /TN "RepairIQUpdater" >nul 2>&1
if %errorLevel% neq 0 (
    echo WARNING: Scheduled task may not be installed correctly
    echo [%date% %time%] WARNING: Task verification failed >> "%LOG_FILE%"
) else (
    echo       Task: RepairIQUpdater - OK
)
echo.

echo [%date% %time%] Installation completed successfully >> "%LOG_FILE%"

echo =====================================
echo       INSTALLATION SUCCESSFUL!
echo =====================================
echo.
echo Service installed from: %INSTALL_DIR%
echo Watch folder: %WATCH_DIR%
echo Updates folder: %UPDATES_DIR%
echo Logs folder: %WATCH_DIR%\logs\
echo.
echo The RepairIQ Sync Agent is now installed and running.
echo It will start automatically when Windows boots.
echo.
echo What it does:
echo   - Watches %WATCH_DIR% for new CCC ONE files
echo   - Automatically uploads them to https://www.repairiq.app
echo   - Auto-updates itself every 6 hours via scheduled task
echo.
echo Auto-Update Architecture:
echo   - Service downloads update ZIP
echo   - Service triggers RepairIQUpdater task
echo   - Task stops service, updates files, restarts service
echo   - Automatic rollback on failure
echo.
echo To check the service status:
echo   1. Press Windows + R
echo   2. Type: services.msc
echo   3. Look for "RepairIQSyncAgent"
echo.
echo To check logs:
echo   - Service log: %WATCH_DIR%\logs\sync-agent.log
echo   - Updater log: %WATCH_DIR%\logs\updater-task.log
echo   - Install log: %WATCH_DIR%\logs\install.log
echo.
echo =====================================
echo.
pause
