$ErrorActionPreference = 'Stop'
Set-Location -LiteralPath $PSScriptRoot

$safeDir = $PSScriptRoot.Replace('\', '/')
$commit = git -c "safe.directory=$safeDir" rev-parse --short HEAD
if ($LASTEXITCODE -ne 0) {
    throw 'No Git commit exists.'
}
$dirty = git -c "safe.directory=$safeDir" status --porcelain --untracked-files=no
if ($dirty) {
    throw 'Tracked files have uncommitted changes. Commit before packaging.'
}

$sourceDir = Join-Path $PSScriptRoot 'dist\MotorCADParameterScanV2'
$targetDir = Join-Path $PSScriptRoot 'dist\MotorCADMagnetArcScan'
$sourceExe = Join-Path $sourceDir 'MotorCADParameterScanV2.exe'
$targetExe = Join-Path $targetDir 'MotorCADMagnetArcScan.exe'

if (-not (Test-Path -LiteralPath $sourceExe)) {
    throw "V2 executable not found: $sourceExe"
}
if (Test-Path -LiteralPath $targetDir) {
    throw "Target already exists: $targetDir"
}

Copy-Item -LiteralPath $sourceDir -Destination $targetDir -Recurse
Rename-Item -LiteralPath (Join-Path $targetDir 'MotorCADParameterScanV2.exe') -NewName 'MotorCADMagnetArcScan.exe'
Copy-Item -LiteralPath '.\scan_parameters_magnet_arc.json' -Destination (Join-Path $targetDir 'scan_parameters.json') -Force

Write-Host "Git commit: $commit"
Write-Host "Package complete: $targetExe"
