[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'

$tag = 'v1.0.0'
$packageRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$temporaryRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('osqp-' + [Guid]::NewGuid().ToString('N'))
$sourceRoot = Join-Path $temporaryRoot 'source'
$buildRoot = Join-Path $temporaryRoot 'build'
$outputDirectory = Join-Path $packageRoot 'win-x64'
$outputDll = Join-Path $outputDirectory 'osqp.dll'
$licenseDestination = Join-Path $packageRoot 'LICENSE'
$noticeDestination = Join-Path $packageRoot 'NOTICE'
$versionDestination = Join-Path $packageRoot 'VERSION'
$hashDestination = Join-Path $packageRoot 'SHA256SUMS'

if ($null -eq (Get-Command cmake -ErrorAction SilentlyContinue)) {
    $installedCmakeDirectory = Join-Path ${env:ProgramFiles} 'CMake\bin'
    if (Test-Path -LiteralPath (Join-Path $installedCmakeDirectory 'cmake.exe')) {
        $env:Path = $installedCmakeDirectory + ';' + $env:Path
    }
}
if ($null -eq (Get-Command cmake -ErrorAction SilentlyContinue)) {
    throw 'CMake 3.18 or later must be installed and available to the native build script.'
}

function Invoke-Checked {
    param([scriptblock]$Command, [string]$Description)

    & $Command
    if ($LASTEXITCODE -ne 0) {
        throw "$Description failed with exit code $LASTEXITCODE."
    }
}

function Assert-ByteIdentical {
    param([string]$ExpectedPath, [string]$ActualPath, [string]$Description)

    [byte[]]$expected = [System.IO.File]::ReadAllBytes($ExpectedPath)
    [byte[]]$actual = [System.IO.File]::ReadAllBytes($ActualPath)
    if ($expected.Length -ne $actual.Length) {
        throw "$Description differs in length."
    }

    for ($index = 0; $index -lt $expected.Length; $index++) {
        if ($expected[$index] -ne $actual[$index]) {
            throw "$Description differs at byte $index."
        }
    }
}

try {
    New-Item -ItemType Directory -Path $temporaryRoot | Out-Null

    Invoke-Checked { git clone --depth 1 --branch $tag --single-branch https://github.com/osqp/osqp.git $sourceRoot } 'OSQP source checkout'

    Invoke-Checked {
        cmake -S $sourceRoot -B $buildRoot -A x64 `
            -DOSQP_ALGEBRA_BACKEND=builtin `
            -DOSQP_BUILD_SHARED_LIB=ON `
            -DOSQP_BUILD_STATIC_LIB=OFF `
            -DOSQP_BUILD_DEMO_EXE=OFF `
            -DOSQP_BUILD_UNITTESTS=OFF `
            -DOSQP_USE_FLOAT=OFF `
            -DOSQP_USE_LONG=OFF `
            -DOSQP_PACK_SETTINGS=OFF `
            -DOSQP_ENABLE_PRINTING=OFF `
            -DOSQP_CODEGEN=OFF `
            -DOSQP_ENABLE_DERIVATIVES=OFF
    } 'OSQP CMake configuration'

    Invoke-Checked { cmake --build $buildRoot --config Release --target osqp } 'OSQP x64 build'

    $dllCandidates = @(Get-ChildItem -LiteralPath $buildRoot -Recurse -File -Filter 'osqp.dll')
    if ($dllCandidates.Count -ne 1) {
        throw "Expected exactly one generated osqp.dll, found $($dllCandidates.Count)."
    }

    $sourceLicense = Join-Path $sourceRoot 'LICENSE'
    $sourceNotice = Join-Path $sourceRoot 'NOTICE'
    if (!(Test-Path -LiteralPath $sourceLicense) -or !(Test-Path -LiteralPath $sourceNotice)) {
        throw 'Pinned OSQP source is missing LICENSE or NOTICE.'
    }

    New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null
    Copy-Item -LiteralPath $dllCandidates[0].FullName -Destination $outputDll -Force
    Copy-Item -LiteralPath $sourceLicense -Destination $licenseDestination -Force
    Copy-Item -LiteralPath $sourceNotice -Destination $noticeDestination -Force
    Assert-ByteIdentical $sourceLicense $licenseDestination 'LICENSE copied from the pinned tag'
    Assert-ByteIdentical $sourceNotice $noticeDestination 'NOTICE copied from the pinned tag'

    $versionText = @(
        "OSQP $tag",
        'Platform: win-x64',
        'OSQP_ALGEBRA_BACKEND=builtin',
        'OSQP_BUILD_SHARED_LIB=ON',
        'OSQP_BUILD_STATIC_LIB=OFF',
        'OSQP_BUILD_DEMO_EXE=OFF',
        'OSQP_BUILD_UNITTESTS=OFF',
        'OSQP_USE_FLOAT=OFF',
        'OSQP_USE_LONG=OFF',
        'OSQP_PACK_SETTINGS=OFF',
        'OSQP_ENABLE_PRINTING=OFF',
        'OSQP_CODEGEN=OFF',
        'OSQP_ENABLE_DERIVATIVES=OFF'
    ) -join [Environment]::NewLine
    [System.IO.File]::WriteAllText($versionDestination, $versionText + [Environment]::NewLine, (New-Object System.Text.UTF8Encoding($false)))

    $hash = (Get-FileHash -LiteralPath $outputDll -Algorithm SHA256).Hash.ToLowerInvariant()
    [System.IO.File]::WriteAllText($hashDestination, "$hash  win-x64/osqp.dll$([Environment]::NewLine)", (New-Object System.Text.UTF8Encoding($false)))

    Write-Output 'OSQP v1.0.0 win-x64 package ready'
}
finally {
    if (Test-Path -LiteralPath $temporaryRoot) {
        Remove-Item -LiteralPath $temporaryRoot -Recurse -Force
    }
}
