param(
  [string]$Root = (Split-Path -Parent $PSScriptRoot)
)

$ErrorActionPreference = "Stop"
$manifest = Get-Content -Raw -LiteralPath (Join-Path $Root "manifest.json") | ConvertFrom-Json
$version = $manifest.version
$outputDir = Join-Path $Root "store-assets\ready-to-upload"
$package = Join-Path $outputDir "Lildra-v$version-chrome-web-store.zip"
$stage = Join-Path $Root ".store-package-staging"

if (Test-Path -LiteralPath $stage) {
  throw "Staging directory already exists: $stage"
}

New-Item -ItemType Directory -Force -Path (Join-Path $stage "icons") | Out-Null
try {
  Copy-Item -LiteralPath (Join-Path $Root "manifest.json"), (Join-Path $Root "background.js"), (Join-Path $Root "lildra.js") -Destination $stage
  foreach ($size in 16, 32, 48, 128) {
    Copy-Item -LiteralPath (Join-Path $Root "icons\LildraLogo$size.png") -Destination (Join-Path $stage "icons")
  }

  if (Test-Path -LiteralPath $package) { Remove-Item -LiteralPath $package }
  Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $package -CompressionLevel Optimal
} finally {
  if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
}

Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [System.IO.Compression.ZipFile]::OpenRead($package)
try {
  $inventory = @($zip.Entries | ForEach-Object { $_.FullName.Replace("\", "/") })
  if ($inventory -notcontains "manifest.json") { throw "manifest.json is not at the ZIP root" }
  $expected = @(
    "manifest.json", "background.js", "lildra.js",
    "icons/LildraLogo16.png", "icons/LildraLogo32.png",
    "icons/LildraLogo48.png", "icons/LildraLogo128.png"
  )
  if (Compare-Object $expected $inventory) { throw "Unexpected ZIP inventory" }
} finally {
  $zip.Dispose()
}

$hash = Get-FileHash -Algorithm SHA256 -LiteralPath $package
[pscustomobject]@{
  Path = $package
  Size = (Get-Item -LiteralPath $package).Length
  SHA256 = $hash.Hash
  Inventory = $inventory -join ", "
}
