@echo off
REM Setup CNPERP Auto-Update Scheduled Task
REM This script must be run as Administrator

echo.
echo ========================================
echo CNPERP Auto-Update Scheduled Task Setup
echo ========================================
echo.

REM Check if running as Administrator
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo ERROR: This script must be run as Administrator.
    echo.
    echo Please:
    echo   1. Right-click this file (setup_auto_update.bat)
    echo   2. Select "Run as Administrator"
    echo.
    pause
    exit /b 1
)

REM Define paths
set "SCRIPT_PATH=C:\dev\cnperp-dimensions\deploy\auto_update.ps1"
set "LOG_PATH=C:\dev\cnperp-dimensions\logs\auto_update.log"
set "TASK_NAME=CNPERP Auto-Update"

REM Verify script exists
if not exist "%SCRIPT_PATH%" (
    echo ERROR: Script not found at:
    echo   %SCRIPT_PATH%
    echo.
    pause
    exit /b 1
)

echo [*] Creating scheduled task...
echo     Name: %TASK_NAME%
echo     Time: Daily at 2:00 AM
echo     Script: %SCRIPT_PATH%
echo.

REM Create the scheduled task using PowerShell
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "$Trigger = New-ScheduledTaskTrigger -Daily -At 2:00AM; " ^
  "$Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File \"%SCRIPT_PATH%\"'; " ^
  "$Settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RunOnlyIfNetworkAvailable -MultipleInstances IgnoreNew; " ^
  "Register-ScheduledTask -TaskName '%TASK_NAME%' -Trigger $Trigger -Action $Action -Settings $Settings -Description 'Automatic CNPERP updates: pulls latest code, updates dependencies, restarts service' -User 'SYSTEM' -RunLevel Highest -Force | Out-Null; " ^
  "Write-Host '✅ Scheduled task created successfully!' -ForegroundColor Green"

if %errorLevel% equ 0 (
    echo.
    echo ========================================
    echo SUCCESS: Scheduled Task Installed
    echo ========================================
    echo.
    echo The CNPERP application will automatically update every night at 2:00 AM.
    echo.
    echo What happens:
    echo   1. Pre-update database backup is created
    echo   2. Latest code is pulled from Git
    echo   3. Python dependencies are updated
    echo   4. CNPERP service is restarted
    echo   5. Log is written to: %LOG_PATH%
    echo.
    echo Duration: ~30-60 seconds
    echo.
    echo To verify it's running:
    echo   - Open Task Scheduler (taskschd.msc)
    echo   - Look for "%TASK_NAME%" in the CNPERP folder
    echo.
    echo To view logs:
    echo   notepad "%LOG_PATH%"
    echo.
) else (
    echo.
    echo ERROR: Failed to create scheduled task
    echo Please check the error messages above and try again.
    echo.
)

pause
