# Check the absolute latest log entries for SCP PUSH ERROR messages
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    $logFile = "C:\Shares\test\scripts\sync-from-nas.log"

    Write-Host "=== Latest Log Analysis ===" -ForegroundColor Cyan
    Write-Host ""

    Write-Host "[1] Log file size and last modified" -ForegroundColor Yellow
    $logInfo = Get-Item $logFile
    Write-Host "Size: $([math]::Round($logInfo.Length / 1MB, 2)) MB" -ForegroundColor Gray
    Write-Host "Last Modified: $($logInfo.LastWriteTime)" -ForegroundColor Gray

    Write-Host ""
    Write-Host "[2] Last 50 lines of log" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    Get-Content $logFile -Tail 50 | ForEach-Object {
        if ($_ -match "SCP PUSH ERROR|SCP ERROR") {
            Write-Host $_ -ForegroundColor Red
        } elseif ($_ -match "ERROR") {
            Write-Host $_ -ForegroundColor Yellow
        } elseif ($_ -match "Starting sync|Sync complete") {
            Write-Host $_ -ForegroundColor Cyan
        } else {
            Write-Host $_ -ForegroundColor Gray
        }
    }

    Write-Host ""
    Write-Host "[3] Searching entire log for 'SCP PUSH ERROR'" -ForegroundColor Yellow
    Write-Host "=" * 80 -ForegroundColor Gray

    $scpErrors = Get-Content $logFile | Select-String -Pattern "SCP PUSH ERROR"

    if ($scpErrors) {
        Write-Host "[SUCCESS] Found $($scpErrors.Count) detailed SCP error(s)!" -ForegroundColor Green
        Write-Host ""
        Write-Host "First 10 occurrences:" -ForegroundColor Cyan
        $scpErrors | Select-Object -First 10 | ForEach-Object {
            Write-Host $_ -ForegroundColor Red
        }
    } else {
        Write-Host "[INFO] No 'SCP PUSH ERROR' messages found in entire log file" -ForegroundColor Yellow
        Write-Host "This means either:" -ForegroundColor Gray
        Write-Host "  1. No sync has run since the fix was applied" -ForegroundColor Gray
        Write-Host "  2. No errors occurred (all files pushed successfully)" -ForegroundColor Gray
        Write-Host "  3. The fix hasn't taken effect yet" -ForegroundColor Gray
    }
}

Write-Host ""
Write-Host "=== Analysis Complete ===" -ForegroundColor Cyan
