# Fix multi-line IF blocks with parentheses - not supported in DOS 6.22
# Convert to single-line IF statements with GOTO labels

$BATFiles = @(
    "DEPLOY.BAT",
    "DEPLOY_VERIFY.BAT",
    "DEPLOY_TEST.BAT",
    "DEPLOY_FROM_NAS.BAT",
    "DEPLOY_FROM_AD2.BAT"
)

Write-Host "[INFO] Fixing multi-line IF blocks (not in DOS 6.22)" -ForegroundColor Cyan
Write-Host ""

foreach ($File in $BATFiles) {
    $FilePath = "D:\ClaudeTools\$File"

    if (-not (Test-Path $FilePath)) {
        Write-Host "[SKIP] $File - not found" -ForegroundColor Yellow
        continue
    }

    Write-Host "Processing: $File" -ForegroundColor White

    $Content = Get-Content $FilePath -Raw

    # Fix 1: AUTOEXEC.BAT backup block (lines 164-171)
    # Convert multi-line IF ( ... ) ELSE ( ... ) to single-line IF with GOTO
    $OldBlock1 = @'
REM Backup current AUTOEXEC.BAT
IF EXIST C:\AUTOEXEC.BAT (
    ECHO Backing up AUTOEXEC.BAT...
    COPY C:\AUTOEXEC.BAT C:\AUTOEXEC.SAV >NUL
    IF ERRORLEVEL 1 GOTO BACKUP_ERROR
    ECHO [OK] Backup created: C:\AUTOEXEC.SAV
) ELSE (
    ECHO [WARNING] No existing AUTOEXEC.BAT found
)
ECHO.
'@

    $NewBlock1 = @'
REM Backup current AUTOEXEC.BAT
IF NOT EXIST C:\AUTOEXEC.BAT GOTO NO_AUTOEXEC_BACKUP

ECHO Backing up AUTOEXEC.BAT...
COPY C:\AUTOEXEC.BAT C:\AUTOEXEC.SAV >NUL
IF ERRORLEVEL 1 GOTO BACKUP_ERROR
ECHO [OK] Backup created: C:\AUTOEXEC.SAV
GOTO AUTOEXEC_BACKUP_DONE

:NO_AUTOEXEC_BACKUP
ECHO [WARNING] No existing AUTOEXEC.BAT found

:AUTOEXEC_BACKUP_DONE
ECHO.
'@

    # Fix 2: MACHINE variable check block (lines 244-247)
    # Convert multi-line IF ( ... ) to single-line IF with GOTO
    $OldBlock2 = @'
REM Check if MACHINE variable already exists in AUTOEXEC.BAT
IF EXIST C:\AUTOEXEC.BAT (
    FIND "SET MACHINE=" C:\AUTOEXEC.BAT >NUL
    IF NOT ERRORLEVEL 1 GOTO MACHINE_EXISTS
)
'@

    $NewBlock2 = @'
REM Check if MACHINE variable already exists in AUTOEXEC.BAT
IF NOT EXIST C:\AUTOEXEC.BAT GOTO ADD_MACHINE_VAR

FIND "SET MACHINE=" C:\AUTOEXEC.BAT >NUL
IF NOT ERRORLEVEL 1 GOTO MACHINE_EXISTS

:ADD_MACHINE_VAR
'@

    $Content = $Content -replace [regex]::Escape($OldBlock1), $NewBlock1
    $Content = $Content -replace [regex]::Escape($OldBlock2), $NewBlock2

    Set-Content $FilePath $Content -NoNewline

    Write-Host "  [OK] Fixed multi-line IF blocks" -ForegroundColor Green
}

Write-Host ""
Write-Host "[SUCCESS] All IF blocks converted to DOS 6.22 syntax" -ForegroundColor Green
Write-Host ""
Write-Host "DOS 6.22 IF syntax:" -ForegroundColor Cyan
Write-Host "  IF condition command        (single line only)" -ForegroundColor White
Write-Host "  IF condition GOTO label     (for multi-step logic)" -ForegroundColor White
Write-Host ""
Write-Host "  NOT SUPPORTED:" -ForegroundColor Red
Write-Host "    IF condition ( ... )      (parentheses)" -ForegroundColor Red
Write-Host "    IF condition ... ELSE ... (ELSE clause)" -ForegroundColor Red
Write-Host ""
