#requires -Version 7.2
[CmdletBinding()]
param(
    [string]$WorkshopRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
)

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

$dist = Join-Path $WorkshopRoot 'dist'
$stage = Join-Path $dist 'azure-virtual-network-manager-deep-dive-source'
$zip = Join-Path $dist 'azure-virtual-network-manager-deep-dive-source.zip'

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

foreach ($file in @('README.md', 'workshop.md', 'publishing-brief.md', 'sanitized-validation-transcript.md')) {
    Copy-Item -LiteralPath (Join-Path $WorkshopRoot $file) -Destination $stage
}

foreach ($directory in @('assets', 'scripts', 'terminal')) {
    Copy-Item -LiteralPath (Join-Path $WorkshopRoot $directory) -Destination $stage -Recurse
}

$screenshotTarget = Join-Path $stage 'screenshots'
New-Item -ItemType Directory -Path $screenshotTarget -Force | Out-Null
Get-ChildItem -LiteralPath (Join-Path $WorkshopRoot 'screenshots') -File -Filter '*.png' |
    Where-Object Name -Match '^\d{2}-' |
    Where-Object Name -NotMatch '^02-resource-group-topology\.png$' |
    Copy-Item -Destination $screenshotTarget

if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force }
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip -CompressionLevel Optimal

$forbidden = @(
    '(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b',
    '(?i)@[a-z0-9.-]+\.[a-z]{2,}',
    '(?i)access[_ -]?token',
    '(?i)refresh[_ -]?token'
)

$textFiles = Get-ChildItem -LiteralPath $stage -Recurse -File | Where-Object Extension -In @('.md', '.ps1', '.sh', '.html', '.css')
foreach ($file in $textFiles) {
    $content = Get-Content -LiteralPath $file.FullName -Raw
    foreach ($pattern in $forbidden) {
        if ($content -match $pattern) { throw "Forbidden distributable content detected in $($file.Name)." }
    }
}

Write-Host "[PASS] Sanitized source bundle created: $zip"
