# Fix error logging in Copy-ToNAS function in AD2 Sync-FromNAS.ps1
# Target: 192.168.0.6 (AD2)
# Script: C:\Shares\test\scripts\Sync-FromNAS.ps1

param(
    [string]$ComputerName = "192.168.0.6",
    [string]$Username = "INTRANET\sysadmin",
    [string]$Password = "Paper123!@#",
    [string]$ScriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
)

# Create credential object
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($Username, $securePassword)

Write-Host "[INFO] Connecting to AD2 ($ComputerName) to fix error logging..." -ForegroundColor Cyan

try {
    # Execute remote script block
    $result = Invoke-Command -ComputerName $ComputerName -Credential $credential -ScriptBlock {
        param($ScriptPath)

        $output = @{
            Success = $false
            Message = ""
            Before = ""
            After = ""
            BackupPath = ""
        }

        # Check if script exists
        if (-not (Test-Path $ScriptPath)) {
            $output.Message = "Script not found at $ScriptPath"
            return $output
        }

        # Create backup with timestamp
        $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
        $backupPath = "$ScriptPath.backup_$timestamp"
        try {
            Copy-Item -Path $ScriptPath -Destination $backupPath -Force
            $output.BackupPath = $backupPath
        } catch {
            $output.Message = "Failed to create backup: $_"
            return $output
        }

        # Read script content
        $content = Get-Content -Path $ScriptPath -Raw
        $output.Before = $content

        # Find and replace the error logging section
        # Original pattern (lines 90-91):
        # if ($LASTEXITCODE -ne 0) { Write-Log "  SCP ERROR (exit ): $result" }

        $originalPattern = '\s*if\s*\(\$LASTEXITCODE\s+-ne\s+0\)\s*\{\s*Write-Log\s+"[^"]*SCP ERROR[^"]*"\s*\}'

        $replacement = @"
    if (`$LASTEXITCODE -ne 0) {
        `$errorMsg = `$result | Out-String
        Write-Log "  SCP PUSH ERROR (exit `$LASTEXITCODE): `$errorMsg"
    }
"@

        # Perform replacement
        $newContent = $content -replace $originalPattern, $replacement

        # Verify something changed
        if ($newContent -eq $content) {
            # Try alternative pattern match
            if ($content -match 'Write-Log\s+"[^"]*SCP ERROR[^"]*exit\s*\)[^"]*"\s*\}') {
                # Pattern found but not replaced, try more specific replacement
                $lines = $content -split "`r?`n"
                $newLines = @()
                $i = 0
                $replaced = $false

                while ($i -lt $lines.Count) {
                    $line = $lines[$i]

                    # Look for the error logging line in Copy-ToNAS function
                    if ($line -match '^\s*if\s*\(\$LASTEXITCODE\s+-ne\s+0\)\s*\{.*SCP ERROR.*\}') {
                        # Replace this line with multi-line version
                        $indent = ($line -replace '^(\s*).*', '$1')
                        $newLines += "$indent`if (`$LASTEXITCODE -ne 0) {"
                        $newLines += "$indent    `$errorMsg = `$result | Out-String"
                        $newLines += "$indent    Write-Log `"  SCP PUSH ERROR (exit `$LASTEXITCODE): `$errorMsg`""
                        $newLines += "$indent}"
                        $replaced = $true
                    } else {
                        $newLines += $line
                    }
                    $i++
                }

                if ($replaced) {
                    $newContent = $newLines -join "`r`n"
                } else {
                    $output.Message = "Could not find the exact error logging pattern to replace"
                    return $output
                }
            } else {
                $output.Message = "Could not find the error logging pattern in the script"
                return $output
            }
        }

        $output.After = $newContent

        # Write updated content
        try {
            Set-Content -Path $ScriptPath -Value $newContent -Force
            $output.Success = $true
            $output.Message = "Successfully updated error logging in Copy-ToNAS function"
        } catch {
            $output.Message = "Failed to write updated script: $_"
            # Restore backup
            Copy-Item -Path $backupPath -Destination $ScriptPath -Force
            return $output
        }

        # Verify syntax by attempting to parse
        try {
            $errors = $null
            $null = [System.Management.Automation.PSParser]::Tokenize($newContent, [ref]$errors)
            if ($errors) {
                $output.Message = "Syntax validation found errors: $($errors -join '; ')"
                $output.Success = $false
                # Restore backup
                Copy-Item -Path $backupPath -Destination $ScriptPath -Force
            }
        } catch {
            $output.Message = "Syntax validation failed: $_"
            $output.Success = $false
            # Restore backup
            Copy-Item -Path $backupPath -Destination $ScriptPath -Force
        }

        return $output

    } -ArgumentList $ScriptPath

    # Display results
    if ($result.Success) {
        Write-Host "`n[SUCCESS] $($result.Message)" -ForegroundColor Green
        Write-Host "[INFO] Backup created at: $($result.BackupPath)" -ForegroundColor Cyan

        # Show before/after comparison
        Write-Host "`n--- BEFORE ---" -ForegroundColor Yellow
        $beforeLines = $result.Before -split "`r?`n"
        $startLine = 0
        for ($i = 0; $i -lt $beforeLines.Count; $i++) {
            if ($beforeLines[$i] -match 'if\s*\(\$LASTEXITCODE\s+-ne\s+0\).*SCP ERROR') {
                $startLine = [Math]::Max(0, $i - 2)
                break
            }
        }
        $beforeLines[$startLine..([Math]::Min($startLine + 5, $beforeLines.Count - 1))] | ForEach-Object { Write-Host $_ }

        Write-Host "`n--- AFTER ---" -ForegroundColor Green
        $afterLines = $result.After -split "`r?`n"
        $startLine = 0
        for ($i = 0; $i -lt $afterLines.Count; $i++) {
            if ($afterLines[$i] -match 'if\s*\(\$LASTEXITCODE\s+-ne\s+0\).*\{' -and $afterLines[$i + 1] -match 'errorMsg') {
                $startLine = [Math]::Max(0, $i - 2)
                break
            }
        }
        $afterLines[$startLine..([Math]::Min($startLine + 7, $afterLines.Count - 1))] | ForEach-Object { Write-Host $_ }

        Write-Host "`n[OK] Error logging fix applied successfully" -ForegroundColor Green
    } else {
        Write-Host "`n[ERROR] $($result.Message)" -ForegroundColor Red
        exit 1
    }

} catch {
    Write-Host "`n[ERROR] Failed to connect or execute on AD2: $_" -ForegroundColor Red
    Write-Host "Error Details: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host "`n[COMPLETE] AD2 error logging fix completed" -ForegroundColor Cyan
