# Nimmt ein Bildschirmfoto auf - gedacht fuer den Start ueber die
# Desktop-Bridge (tools\Bridge-Run.ps1).
#
# Warum ueber die Bridge: Eine SSH-Sitzung laeuft in Session 0 und hat gar
# keinen Desktop - dort kommt nur ein schwarzes Pseudobild heraus. Die
# Bridge laeuft in der angemeldeten Sitzung und sieht die echten Monitore.
param(
    [string]$Path = (Join-Path $env:TEMP 'pilotng-shot.png'),
    # Leer = alle Bildschirme nebeneinander, sonst z. B. '\\.\DISPLAY1'
    [string]$Screen = '',
    # Breite begrenzen: spart Uebertragungszeit, ohne Details zu verlieren.
    [int]$MaxWidth = 1920
)

$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms

if ($Screen) {
    $target = [System.Windows.Forms.Screen]::AllScreens |
        Where-Object { $_.DeviceName -eq $Screen } | Select-Object -First 1
    if (!$target) {
        $known = ([System.Windows.Forms.Screen]::AllScreens.DeviceName) -join ', '
        throw "Bildschirm '$Screen' gibt es nicht. Vorhanden: $known"
    }
    $bounds = $target.Bounds
} else {
    $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
}

$shot = New-Object Drawing.Bitmap $bounds.Width, $bounds.Height
try {
    $graphics = [Drawing.Graphics]::FromImage($shot)
    try {
        $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.Size)
    } finally {
        $graphics.Dispose()
    }

    if ($MaxWidth -gt 0 -and $bounds.Width -gt $MaxWidth) {
        $height = [int]($bounds.Height * $MaxWidth / $bounds.Width)
        $small = New-Object Drawing.Bitmap $MaxWidth, $height
        try {
            $scaler = [Drawing.Graphics]::FromImage($small)
            try {
                $scaler.InterpolationMode = 'HighQualityBicubic'
                $scaler.DrawImage($shot, 0, 0, $MaxWidth, $height)
            } finally {
                $scaler.Dispose()
            }
            $small.Save($Path, [Drawing.Imaging.ImageFormat]::Png)
        } finally {
            $small.Dispose()
        }
    } else {
        $shot.Save($Path, [Drawing.Imaging.ImageFormat]::Png)
    }
} finally {
    $shot.Dispose()
}

Write-Output "$Path $($bounds.Width)x$($bounds.Height) bei $($bounds.X),$($bounds.Y)"
