# Downloads FFmpeg essentials build for Windows and installs as Tauri sidecars.
param(
    [string]$Version = "release",
    [string]$Build = "essentials",
    [string]$OutputDir = "$PSScriptRoot\..\src-tauri\binaries"
)

$ErrorActionPreference = "Stop"
$Triple = "x86_64-pc-windows-msvc"
$Root = (Resolve-Path "$PSScriptRoot\..").Path

# Pinned identity for the bundled commercial release (gyan.dev essentials 8.1.2).
$ExpectedVersionSubstring = "8.1.2-essentials_build-www.gyan.dev"
$ExpectedArchiveSha256 = "DB580001CAA24AC104C8CB856CD113A87B0A443F7BDF47D8C12B1D740584A2EC"
$ExpectedFfmpegSha256 = "1326DDE4C84FF1F96FE6B8916C5BED29E163E9B5DCCF995F6F3DB069D143EC5E"
$ExpectedFfprobeSha256 = "B49CCC7C6547B141AD5A2F6EC69CC04323D7133D7704D70B331B904C63EECB07"
$ExpectedSourceCommit = "38b88335f9"

New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null

function Get-FileSha256 {
    param([string]$Path)

    $Stream = [System.IO.File]::OpenRead($Path)
    try {
        $Hasher = [System.Security.Cryptography.SHA256]::Create()
        try {
            return ([System.BitConverter]::ToString($Hasher.ComputeHash($Stream))).Replace("-", "")
        } finally {
            $Hasher.Dispose()
        }
    } finally {
        $Stream.Dispose()
    }
}

$ZipName = "ffmpeg-release-essentials.zip"
$Url = "https://www.gyan.dev/ffmpeg/builds/$ZipName"
$TempZip = Join-Path $env:TEMP $ZipName
$TempExtract = Join-Path $env:TEMP "ffmpeg-extract-$Version"

Write-Host "Downloading FFmpeg $Version ($Build). Expected bundled release is $ExpectedVersionSubstring."
Invoke-WebRequest -Uri $Url -OutFile $TempZip -UseBasicParsing

function Assert-Sha256 {
    param(
        [string]$Path,
        [string]$Expected
    )

    $Actual = (Get-FileSha256 -Path $Path).ToUpperInvariant()
    if ($Actual -ne $Expected.ToUpperInvariant()) {
        throw "SHA256 mismatch for $Path. Expected $Expected, got $Actual. Update the pin only after verifying the new gyan.dev build."
    }
}

Assert-Sha256 -Path $TempZip -Expected $ExpectedArchiveSha256

if (Test-Path $TempExtract) {
    Remove-Item $TempExtract -Recurse -Force
}
Expand-Archive -Path $TempZip -DestinationPath $TempExtract -Force

$BinDir = Get-ChildItem -Path $TempExtract -Recurse -Directory -Filter "bin" | Select-Object -First 1
if (-not $BinDir) {
    throw "Could not find bin directory in FFmpeg archive"
}

$FfmpegDest = Join-Path $OutputDir "ffmpeg-$Triple.exe"
$FfprobeDest = Join-Path $OutputDir "ffprobe-$Triple.exe"

Copy-Item (Join-Path $BinDir.FullName "ffmpeg.exe") $FfmpegDest -Force
Copy-Item (Join-Path $BinDir.FullName "ffprobe.exe") $FfprobeDest -Force

Assert-Sha256 -Path $FfmpegDest -Expected $ExpectedFfmpegSha256
Assert-Sha256 -Path $FfprobeDest -Expected $ExpectedFfprobeSha256

$VersionLine = [string](& $FfmpegDest -version | Select-Object -First 1)
if (-not $VersionLine.Contains($ExpectedVersionSubstring)) {
    throw "FFmpeg version mismatch after download. Expected '$ExpectedVersionSubstring' in '$VersionLine'."
}

$BuildRoot = $BinDir.Parent.FullName
$BuildReadme = Join-Path $BuildRoot "README.txt"
if (-not (Test-Path $BuildReadme)) {
    throw "Gyan build README.txt is missing from the verified archive."
}

$ReadmeText = Get-Content $BuildReadme -Raw
if (-not $ReadmeText.Contains("Source Code: https://github.com/FFmpeg/FFmpeg/commit/$ExpectedSourceCommit")) {
    throw "Gyan build README does not identify the expected FFmpeg source commit $ExpectedSourceCommit."
}

Copy-Item $BuildReadme (Join-Path $Root "licenses\FFMPEG-GYAN-README.txt") -Force

Write-Host "Installed and verified:"
Write-Host "  archive ($ExpectedArchiveSha256)"
Write-Host "  ffmpeg-$Triple.exe ($ExpectedFfmpegSha256)"
Write-Host "  ffprobe-$Triple.exe ($ExpectedFfprobeSha256)"
Write-Host "  source commit $ExpectedSourceCommit"
