$ProjectRoot = if ($PSScriptRoot) { Split-Path -Parent $PSScriptRoot } else { (Get-Location).Path }
Set-Location $ProjectRoot

$IconPath = Join-Path $ProjectRoot "icon.ico"
$DistPath = Join-Path $ProjectRoot "build\pyinstaller-tools"
$WorkRoot = Join-Path $ProjectRoot "build\pyinstaller-tools\work"
$SpecPath = Join-Path $ProjectRoot "build\pyinstaller-tools\spec"

$Tools = @(
    @{
        Name = "generate_offline_code"
        Script = Join-Path $ProjectRoot "tools\generate_offline_code.py"
    },
    @{
        Name = "print_device_id"
        Script = Join-Path $ProjectRoot "tools\print_device_id.py"
    }
)

foreach ($Tool in $Tools) {
    if (-not (Test-Path $Tool.Script)) {
        throw "Script bulunamadi: $($Tool.Script)"
    }

    $Args = @(
        "-m", "PyInstaller",
        "--noconfirm",
        "--clean",
        "--onefile",
        "--console",
        "--name", $Tool.Name,
        "--distpath", $DistPath,
        "--workpath", (Join-Path $WorkRoot $Tool.Name),
        "--specpath", $SpecPath,
        "--paths", $ProjectRoot,
        "--collect-submodules", "core"
    )

    if (Test-Path $IconPath) {
        $Args += @("--icon", $IconPath)
    }

    $Args += $Tool.Script

    Write-Host "Build basliyor: $($Tool.Name)" -ForegroundColor Cyan
    & python @Args

    if ($LASTEXITCODE -ne 0) {
        throw "PyInstaller build basarisiz: $($Tool.Name)"
    }
}

Write-Host "Tum tool build'leri tamamlandi: $DistPath" -ForegroundColor Green
