Add-Type -AssemblyName System.Drawing

$inputPath = Resolve-Path ".\assets\logo.jpeg"
$outputPath = Join-Path (Get-Location) "assets\logo.png"

$img = [System.Drawing.Image]::FromFile($inputPath)
$bitmap = New-Object System.Drawing.Bitmap($img)

$width = $img.Width
$height = $img.Height

# We only want the ZV mark. We will scan only the top 55% to be safe and find bounding box.
$scanHeight = [math]::Floor($height * 0.55)

$minX = $width
$minY = $height
$maxX = 0
$maxY = 0

# First pass: find the bounding box of non-dark pixels in the top 55%
for ($x = 0; $x -lt $width; $x++) {
    for ($y = 0; $y -lt $scanHeight; $y++) {
        $pixel = $bitmap.GetPixel($x, $y)
        if ($pixel.R -ge 25 -or $pixel.G -ge 25 -or $pixel.B -ge 25) {
            if ($x -lt $minX) { $minX = $x }
            if ($x -gt $maxX) { $maxX = $x }
            if ($y -lt $minY) { $minY = $y }
            if ($y -gt $maxY) { $maxY = $y }
        }
    }
}

# If nothing found, fallback
if ($minX -gt $maxX) {
    $minX = 0; $maxX = $width - 1; $minY = 0; $maxY = $scanHeight - 1;
}

# Add a tiny 2px padding
$minX = [math]::Max(0, $minX - 2)
$minY = [math]::Max(0, $minY - 2)
$maxX = [math]::Min($width - 1, $maxX + 2)
$maxY = [math]::Min($scanHeight - 1, $maxY + 2)

$cropW = $maxX - $minX + 1
$cropH = $maxY - $minY + 1

$newBitmap = New-Object System.Drawing.Bitmap($cropW, $cropH)
$newBitmap.MakeTransparent()

for ($x = 0; $x -lt $cropW; $x++) {
    for ($y = 0; $y -lt $cropH; $y++) {
        $sourceX = $minX + $x
        $sourceY = $minY + $y
        $pixel = $bitmap.GetPixel($sourceX, $sourceY)
        
        # Exact background removal
        if ($pixel.R -lt 25 -and $pixel.G -lt 25 -and $pixel.B -lt 25) {
            $newBitmap.SetPixel($x, $y, [System.Drawing.Color]::FromArgb(0, 0, 0, 0))
        } else {
            $newBitmap.SetPixel($x, $y, [System.Drawing.Color]::FromArgb(255, $pixel.R, $pixel.G, $pixel.B))
        }
    }
}

$newBitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)

$img.Dispose()
$bitmap.Dispose()
$newBitmap.Dispose()

Write-Host "Auto-cropped properly! Saved to $outputPath"
