<#
.SYNOPSIS
    Checks Active Directory replication health across domain controllers.

.DESCRIPTION
    This script performs comprehensive AD replication health checks including
    replication status, partner connectivity, and identifies any replication failures.

.PARAMETER OutputPath
    Optional. Path to export results. If not specified, outputs to console.

.PARAMETER Detailed
    Switch to show detailed replication information per DC.

.EXAMPLE
    .\Get-ReplicationHealth.ps1
    Basic replication health check.

.EXAMPLE
    .\Get-ReplicationHealth.ps1 -Detailed -OutputPath "C:\ClaudeTools\Logs\repl-health.txt"
    Detailed check with output to file.

.NOTES
    Author: ClaudeTools Automation
    Version: 1.0
    Requires: ActiveDirectory PowerShell module, repadmin.exe
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory=$false)]
    [string]$OutputPath,

    [Parameter(Mandatory=$false)]
    [switch]$Detailed
)

# Import AD module
Import-Module ActiveDirectory -ErrorAction Stop

$output = @()
$output += "=" * 60
$output += "AD REPLICATION HEALTH REPORT"
$output += "Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$output += "=" * 60

Write-Host "Checking AD Replication Health..." -ForegroundColor Cyan

# Get all DCs
$dcs = Get-ADDomainController -Filter *
$output += "`nDomain Controllers Found: $($dcs.Count)"

foreach ($dc in $dcs) {
    $output += "`n--- $($dc.HostName) ---"
    Write-Host "Checking $($dc.HostName)..." -ForegroundColor Gray
}

# Check replication summary using repadmin
$output += "`n" + "=" * 60
$output += "REPLICATION SUMMARY (repadmin /replsummary)"
$output += "=" * 60

try {
    $replSummary = repadmin /replsummary 2>&1
    $output += $replSummary
    Write-Host "Replication summary retrieved." -ForegroundColor Green
} catch {
    $output += "ERROR: Unable to run repadmin /replsummary"
    Write-Host "Error running repadmin" -ForegroundColor Red
}

# Check for replication failures
$output += "`n" + "=" * 60
$output += "REPLICATION FAILURES (repadmin /showrepl * /errorsonly)"
$output += "=" * 60

try {
    $replErrors = repadmin /showrepl * /errorsonly 2>&1
    if ($replErrors -match "error" -or $replErrors -match "fail") {
        $output += $replErrors
        Write-Host "Replication ERRORS detected!" -ForegroundColor Red
    } else {
        $output += "No replication errors detected."
        Write-Host "No replication errors." -ForegroundColor Green
    }
} catch {
    $output += "ERROR: Unable to check replication errors"
}

# Queue length
$output += "`n" + "=" * 60
$output += "REPLICATION QUEUE (repadmin /queue)"
$output += "=" * 60

try {
    $replQueue = repadmin /queue 2>&1
    $output += $replQueue
} catch {
    $output += "ERROR: Unable to check replication queue"
}

if ($Detailed) {
    $output += "`n" + "=" * 60
    $output += "DETAILED REPLICATION STATUS (repadmin /showrepl)"
    $output += "=" * 60

    try {
        $replDetail = repadmin /showrepl 2>&1
        $output += $replDetail
    } catch {
        $output += "ERROR: Unable to get detailed replication status"
    }

    # DFSR Health (if applicable)
    $output += "`n" + "=" * 60
    $output += "DFSR SYSVOL REPLICATION STATUS"
    $output += "=" * 60

    try {
        $dfsrStatus = Get-DfsrMember -ErrorAction SilentlyContinue
        if ($dfsrStatus) {
            $output += "DFSR Members:"
            foreach ($member in $dfsrStatus) {
                $output += "  - $($member.ComputerName): $($member.DomainName)"
            }
        } else {
            $output += "DFSR not configured or FRS in use."
        }
    } catch {
        $output += "Unable to query DFSR status (may be using FRS)"
    }
}

# AD Database health
$output += "`n" + "=" * 60
$output += "AD DATABASE INTEGRITY"
$output += "=" * 60

$adDb = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Services\NTDS\Parameters" -ErrorAction SilentlyContinue
if ($adDb) {
    $dbPath = $adDb.'DSA Database file'
    $logPath = $adDb.'Database log files path'
    $output += "Database Path: $dbPath"
    $output += "Log Path: $logPath"

    if (Test-Path $dbPath) {
        $dbSize = (Get-Item $dbPath).Length / 1MB
        $output += "Database Size: $([math]::Round($dbSize, 2)) MB"
    }
}

# Final summary
$output += "`n" + "=" * 60
$output += "HEALTH CHECK COMPLETE"
$output += "=" * 60

# Output results
if ($OutputPath) {
    $output | Out-File -FilePath $OutputPath -Encoding UTF8
    Write-Host "`nReport saved to: $OutputPath" -ForegroundColor Green
} else {
    $output | ForEach-Object { Write-Host $_ }
}

# Quick status summary
Write-Host "`n--- Quick Status ---" -ForegroundColor Yellow
Write-Host "Domain Controllers: $($dcs.Count)"
$errorMatch = $replErrors -match "error|fail"
if ($errorMatch) {
    Write-Host "Replication Status: ERRORS DETECTED" -ForegroundColor Red
} else {
    Write-Host "Replication Status: HEALTHY" -ForegroundColor Green
}
