param(
    [string]$ModsPath = ""
)

$ErrorActionPreference = "Stop"

$modName = "FS25_Mine"
$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectZip = Join-Path $projectRoot "$modName.zip"
$tempZip = Join-Path ([System.IO.Path]::GetTempPath()) "$modName-build.zip"

if ([string]::IsNullOrWhiteSpace($ModsPath)) {
    $candidates = @(
        (Join-Path $env:USERPROFILE "OneDrive\Dokumente\My Games\FarmingSimulator2025\mods"),
        (Join-Path $env:USERPROFILE "Documents\My Games\FarmingSimulator2025\mods")
    )

    foreach ($candidate in $candidates) {
        if (Test-Path -LiteralPath $candidate) {
            $ModsPath = $candidate
            break
        }
    }
}

if ([string]::IsNullOrWhiteSpace($ModsPath)) {
    throw "Kein FarmingSimulator2025 mods Ordner gefunden. Starte z.B.: .\build.ps1 -ModsPath 'C:\Users\pasca\OneDrive\Dokumente\My Games\FarmingSimulator2025\mods'"
}

if (-not (Test-Path -LiteralPath $ModsPath)) {
    New-Item -ItemType Directory -Force -Path $ModsPath | Out-Null
}

Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem

if (Test-Path -LiteralPath $tempZip) {
    Remove-Item -LiteralPath $tempZip -Force
}

if (Test-Path -LiteralPath $projectZip) {
    Remove-Item -LiteralPath $projectZip -Force
}

$zip = [System.IO.Compression.ZipFile]::Open($tempZip, [System.IO.Compression.ZipArchiveMode]::Create)
try {
    $files = Get-ChildItem -LiteralPath $projectRoot -Recurse -File -Force | Where-Object {
        $relative = $_.FullName.Substring($projectRoot.Length + 1)
        -not ($relative -like ".git\*") -and
        -not ($relative -like ".vscode\*") -and
        $relative -ne "$modName.zip" -and
        $relative -ne "build.ps1" -and
        $relative -ne "build.cmd"
    }

    foreach ($file in $files) {
        $relative = $file.FullName.Substring($projectRoot.Length + 1).Replace("\", "/")
        [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $file.FullName, $relative, [System.IO.Compression.CompressionLevel]::Optimal) | Out-Null
    }
}
finally {
    $zip.Dispose()
}

Move-Item -LiteralPath $tempZip -Destination $projectZip -Force
Copy-Item -LiteralPath $projectZip -Destination (Join-Path $ModsPath "$modName.zip") -Force

Write-Host "Build fertig: $projectZip"
Write-Host "Kopiert nach: $(Join-Path $ModsPath "$modName.zip")"