# 打包 Chrome / Edge 商店上架用 zip（不含 baseline、.git、备份）
# 用法：
#   .\scripts\build-store.ps1 -ApiBase "https://你的API域名"
# 示例：
#   .\scripts\build-store.ps1 -ApiBase "https://api.example.com" -OutZip "dist\biliindex-1.0.10-store.zip"

param(
  [Parameter(Mandatory = $true)]
  [string]$ApiBase,
  [string]$OutZip = ""
)

$ErrorActionPreference = "Stop"
$root = Resolve-Path (Join-Path $PSScriptRoot "..")
$manifestRaw = Get-Content (Join-Path $root "manifest.json") -Raw -Encoding UTF8
if ($manifestRaw -notmatch '"version"\s*:\s*"([^"]+)"') {
  throw "Cannot read version from manifest.json"
}
$version = $Matches[1]
if (-not $OutZip) {
  $OutZip = Join-Path $root "dist\biliindex-$version-store.zip"
}
$ApiBase = $ApiBase.Trim().TrimEnd("/")
if ($ApiBase -notmatch "^https://") {
  throw "ApiBase must be HTTPS, e.g. https://api.yourdomain.com"
}

$stage = Join-Path $root "dist\store-package"
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
New-Item -ItemType Directory -Path $stage -Force | Out-Null

$copyItems = @(
  "manifest.json",
  "_locales",
  "icons",
  "popup",
  "background",
  "src"
)
foreach ($item in $copyItems) {
  $src = Join-Path $root $item
  if (-not (Test-Path $src)) { throw "Missing: $src" }
  Copy-Item $src (Join-Path $stage $item) -Recurse -Force
}
Get-ChildItem $stage -Recurse -Include "*.bak*","*.bak" -File -ErrorAction SilentlyContinue | Remove-Item -Force

# 写入生产 API 默认值
$corePath = Join-Path $stage "src\lib\biliindex-core.js"
$core = Get-Content $corePath -Raw -Encoding UTF8
# UTF8 without BOM for JS
$core = $core -replace 'BiliIndex\.DEFAULT_API_BASE = "[^"]*"', "BiliIndex.DEFAULT_API_BASE = `"$ApiBase`""
Set-Content $corePath $core -Encoding UTF8 -NoNewline

# manifest：生产 host_permissions（去掉本地调试）
$manifestPath = Join-Path $stage "manifest.json"
$manifest = Get-Content $manifestPath -Raw -Encoding UTF8
$hostBlock = @"
  "host_permissions": [
    "$ApiBase/*",
    "https://api.bilibili.com/*"
  ]
"@
$manifest = $manifest -replace '(?s)\s*"host_permissions"\s*:\s*\[[^\]]*\]', "`n$hostBlock"
# Edge/Chrome 商店包不得含 update_url 或侧载更新（更新仅通过商店发布）
$manifest = $manifest -replace ',?\s*\r?\n\s*"update_url"\s*:\s*"[^"]*"', ""
Set-Content $manifestPath $manifest -Encoding UTF8 -NoNewline

$distDir = Split-Path $OutZip -Parent
if (-not (Test-Path $distDir)) { New-Item -ItemType Directory -Path $distDir -Force | Out-Null }
if (Test-Path $OutZip) { Remove-Item $OutZip -Force }
Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $OutZip -Force

Write-Host "Store zip: $OutZip"
Write-Host "API base: $ApiBase"
Write-Host "Test unpacked: dist\store-package"
