$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$exportDir = Join-Path $projectRoot "App-export"
$zipPath = Join-Path $projectRoot "chrome-extension-full.zip"

$excludedTopLevel = @(
  ".git",
  "App-export",
  "node_modules",
  "dist"
)

function Should-SkipItem {
  param(
    [Parameter(Mandatory = $true)]
    [System.IO.FileSystemInfo]$Item
  )

  if ($excludedTopLevel -contains $Item.Name) {
    return $true
  }

  if ($Item.Name -like "tmpclaude-*-cwd") {
    return $true
  }

  if ($Item.Extension -eq ".zip") {
    return $true
  }

  return $false
}

if (Test-Path -LiteralPath $exportDir) {
  Remove-Item -LiteralPath $exportDir -Recurse -Force
}
New-Item -ItemType Directory -Path $exportDir | Out-Null

$itemsToCopy = Get-ChildItem -LiteralPath $projectRoot -Force | Where-Object { -not (Should-SkipItem $_) }
foreach ($item in $itemsToCopy) {
  Copy-Item -LiteralPath $item.FullName -Destination $exportDir -Recurse -Force
}

$requiredFiles = @(
  "manifest.json",
  "index.html",
  "app.js",
  "background.js",
  "content-script.js",
  "page-hook.js",
  "styles.css"
)

foreach ($required in $requiredFiles) {
  $requiredPath = Join-Path $exportDir $required
  if (-not (Test-Path -LiteralPath $requiredPath)) {
    throw "Export ontbreekt verplicht bestand: $required"
  }
}

if (Test-Path -LiteralPath $zipPath) {
  Remove-Item -LiteralPath $zipPath -Force
}

Compress-Archive -Path (Join-Path $exportDir "*") -DestinationPath $zipPath -Force

$fileCount = (Get-ChildItem -LiteralPath $exportDir -Recurse -File).Count
$zipSizeMb = [Math]::Round(((Get-Item -LiteralPath $zipPath).Length / 1MB), 2)

Write-Host "Export gereed:"
Write-Host " - Map: $exportDir"
Write-Host " - ZIP: $zipPath"
Write-Host " - Bestanden: $fileCount"
Write-Host " - ZIP grootte: $zipSizeMb MB"
