# Build Motor-CAD Scan Studio as a single-file Windows executable.
# Requires: git commit with clean working tree, Python 3.10+, PyQt5,
# ansys-motorcad-core, pyinstaller.
#
# Usage:
#   powershell -ExecutionPolicy Bypass -File .\build_studio_exe.ps1
#   powershell -ExecutionPolicy Bypass -File .\build_studio_exe.ps1 -AppName MotorCADScanStudio

param(
  [string]$AppName = 'MotorCADScanStudio',
  [string]$PythonExe = 'C:\Users\admin\AppData\Local\Programs\Python\Python312\python.exe'
)

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

# --- Git preflight: must have a commit and clean tracked files ---
$safeDir = $PSScriptRoot.Replace('\', '/')
$commit = git -c "safe.directory=$safeDir" rev-parse --short HEAD
if ($LASTEXITCODE -ne 0) {
    throw 'No Git commit exists. Commit before building.'
}
$dirty = git -c "safe.directory=$safeDir" status --porcelain --untracked-files=no
if ($dirty) {
    throw 'Tracked files have uncommitted changes. Commit before building.'
}
Write-Host "Git commit: $commit" -ForegroundColor Cyan

# --- Embed build info ---
$buildInfo = "BUILD_COMMIT = '$commit'`nAPP_VERSION = '1.0.0'`n"
[System.IO.File]::WriteAllText(
    (Join-Path $PSScriptRoot 'build_info.py'),
    $buildInfo,
    [System.Text.Encoding]::ASCII
)

# --- PyInstaller: one-file, windowed ---
if (-not (Test-Path -LiteralPath $PythonExe)) {
    throw "Python executable not found: $PythonExe"
}
$pyVersion = & $PythonExe --version 2>&1
Write-Host "Using Python: $PythonExe ($pyVersion)" -ForegroundColor Cyan
Write-Host 'Building with PyInstaller...' -ForegroundColor Cyan
& $PythonExe -m PyInstaller `
  --noconfirm `
  --clean `
  --onefile `
  --windowed `
  --name $AppName `
  --hidden-import solver `
  --collect-submodules ansys `
  --add-data "scan_parameters.json;." `
  main.py

if ($LASTEXITCODE -ne 0) {
    throw 'PyInstaller build failed.'
}

# --- Copy config next to exe ---
$distDir = Join-Path $PSScriptRoot "dist\$AppName"
if (-not (Test-Path -LiteralPath $distDir)) {
    # onefile mode puts exe directly in dist/
    $distDir = Join-Path $PSScriptRoot 'dist'
}
Copy-Item -LiteralPath '.\scan_parameters.json' -Destination (Join-Path $distDir 'scan_parameters.json') -Force

$exePath = Join-Path $distDir "$AppName.exe"
if (Test-Path -LiteralPath $exePath) {
    $sizeMB = [math]::Round((Get-Item -LiteralPath $exePath).Length / 1MB, 1)
    Write-Host ""
    Write-Host "Build complete: $exePath" -ForegroundColor Green
    Write-Host "Size: $sizeMB MB" -ForegroundColor Green
} else {
    Write-Host "Build finished but exe not found at $exePath" -ForegroundColor Yellow
}
