param(
    [Parameter(Mandatory=$true)]
    [string]$SourcePath,
    
    [Parameter(Mandatory=$true)]
    [string]$TargetPath
)

try {
    # Validate paths
    if (-not (Test-Path $SourcePath)) {
        throw "Source path does not exist: $SourcePath"
    }
    if (-not (Test-Path $TargetPath)) {
        throw "Target path does not exist: $TargetPath"
    }

    # Create log file path
    $logFile = "$PSScriptRoot\MirrorLog_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

    Write-Host "[$(Get-Date)] Starting mirror operation..."
    Write-Host "Source: $SourcePath"
    Write-Host "Target: $TargetPath"
    Write-Host "Log file: $logFile"

    # Robocopy parameters:
    # /MIR = Mirror mode (purge files in destination not in source)
    # /NP = No progress percentage
    # /NDL = No directory logging
    # /LOG+: Append to log file
    # /TEE = Output to console and log file
    # /R:5 = 5 retries on failed files
    # /W:5 = 5 second wait between retries
    $robocopyArgs = @($SourcePath, $TargetPath, "/MIR", "/NP", "/NDL", "/LOG+:$logFile", "/TEE", "/R:5", "/W:5")
    
    $process = Start-Process robocopy -ArgumentList $robocopyArgs -NoNewWindow -PassThru -Wait

    # Robocopy exit codes: https://ss64.com/nt/robocopy-exit.html
    if ($process.ExitCode -ge 8) {
        throw "Robocopy failed with exit code $($process.ExitCode)"
    }

    Write-Host "[$(Get-Date)] Mirror operation completed successfully" -ForegroundColor Green
    Write-Host "Total processing time: $($process.ExitTime - $process.StartTime)"
}
catch {
    Write-Host "[ERROR] $_" -ForegroundColor Red
    exit 1
}