#Requires -Version 5.1
<#
.SYNOPSIS
    mb_clouseau Package Script
    Uncovering clues with MusicBee Clouseau

.DESCRIPTION
    Packages the mb_clouseau plugin from /publish into distributable archives.
    Creates versioned archives with epoch timestamps in /deploy/archive
    and copies to /deploy/www/downloads for web distribution.

.PARAMETER Configuration
    Build configuration: Debug or Release (default: Release)

.EXAMPLE
    .\package.ps1
    Packages Release build

.EXAMPLE
    .\package.ps1 -Configuration Debug
    Packages Debug build
#>

[CmdletBinding()]
param(
    [Parameter(Position = 0)]
    [ValidateSet('Debug', 'Release')]
    [string]$Configuration = 'Release'
)

# ============================================================================
# Configuration
# ============================================================================

$ErrorActionPreference = 'Stop'

# Paths
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$DeployDir = $ScriptDir
$ProjectRoot = Split-Path -Parent $DeployDir
$PublishDir = Join-Path $ProjectRoot 'publish'
$ArchiveDir = Join-Path $DeployDir 'archive'
$WwwDir = Join-Path $DeployDir 'www'
$DownloadsDir = Join-Path $WwwDir 'downloads'

# Generate Unix epoch timestamp (hex)
$UnixTime = [int][double]::Parse((Get-Date -UFormat %s))
$HexEpoch = $UnixTime.ToString('X8')

# Product info
$ProductName = 'MusicBee-Clouseau'
$DllName = 'mb_clouseau.dll'

# Colors
function Write-Header { param($msg) Write-Host "`n$('=' * 60)" -ForegroundColor Magenta; Write-Host "  $msg" -ForegroundColor Magenta; Write-Host "$('=' * 60)" -ForegroundColor Magenta }
function Write-Step { param($msg) Write-Host "`n>> $msg" -ForegroundColor Cyan }
function Write-Success { param($msg) Write-Host "   [OK] $msg" -ForegroundColor Green }
function Write-Info { param($msg) Write-Host "   $msg" -ForegroundColor Gray }
function Write-Failure { param($msg) Write-Host "   [FAIL] $msg" -ForegroundColor Red }

# ============================================================================
# Main
# ============================================================================

Write-Header "mb_clouseau Package - $Configuration"
Write-Host "  Epoch: $HexEpoch ($UnixTime)" -ForegroundColor Yellow

# Ensure directories exist
@($ArchiveDir, $DownloadsDir) | ForEach-Object {
    if (-not (Test-Path $_)) {
        New-Item -ItemType Directory -Path $_ -Force | Out-Null
    }
}

# Check for publish output
Write-Step 'Checking build output...'
$dllPath = Join-Path $PublishDir $DllName
if (-not (Test-Path $dllPath)) {
    Write-Failure "Build output not found: $dllPath"
    Write-Host "`n   Run 'build.cmd $Configuration' first." -ForegroundColor Yellow
    exit 1
}
Write-Success "Found $DllName"

# Get version from DLL
$dllInfo = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($dllPath)
$version = $dllInfo.FileVersion
if (-not $version) { $version = '0.1.0.0' }
$version = $version -replace '\.0$', ''  # Remove trailing .0
Write-Success "Version: $version"

# Create plugin archive
Write-Step 'Creating plugin archive...'
$archiveName = "$ProductName-$version-$HexEpoch.zip"
$archivePath = Join-Path $ArchiveDir $archiveName

# Stage files for archive
$stagingDir = Join-Path $env:TEMP "clouseau_pkg_$HexEpoch"
if (Test-Path $stagingDir) { Remove-Item $stagingDir -Recurse -Force }
New-Item -ItemType Directory -Path $stagingDir | Out-Null

# Copy DLL and config files
Copy-Item $dllPath $stagingDir
@('NLog.config', 'settings.json') | ForEach-Object {
    $src = Join-Path $PublishDir $_
    if (Test-Path $src) {
        Copy-Item $src $stagingDir
    }
}

# Create archive
Compress-Archive -Path "$stagingDir\*" -DestinationPath $archivePath -CompressionLevel Optimal -Force
Remove-Item $stagingDir -Recurse -Force

$archiveSize = [math]::Round((Get-Item $archivePath).Length / 1KB, 2)
Write-Success "$archiveName ($archiveSize KB) -> archive"

# Copy to downloads
$downloadPath = Join-Path $DownloadsDir $archiveName
Copy-Item $archivePath $downloadPath -Force
Write-Success "$archiveName -> downloads"

# Create latest alias
$latestPath = Join-Path $DownloadsDir "$ProductName-latest.zip"
Copy-Item $archivePath $latestPath -Force
Write-Success "$ProductName-latest.zip -> downloads (alias)"

# Create source archive
Write-Step 'Creating source archive...'
$sourceArchiveName = "$ProductName-Source-$version-$HexEpoch.zip"
$sourceArchivePath = Join-Path $ArchiveDir $sourceArchiveName

# Stage source files
$sourceStagingDir = Join-Path $env:TEMP "clouseau_src_$HexEpoch"
if (Test-Path $sourceStagingDir) { Remove-Item $sourceStagingDir -Recurse -Force }
New-Item -ItemType Directory -Path $sourceStagingDir | Out-Null

# Copy source files
$sourcePatterns = @('*.csproj', '*.sln', '*.md', '*.png', 'LICENSE', 'build.cmd', 'build.ps1', '.gitignore')
foreach ($pattern in $sourcePatterns) {
    Get-ChildItem -Path $ProjectRoot -Filter $pattern -File -ErrorAction SilentlyContinue | ForEach-Object {
        Copy-Item $_.FullName $sourceStagingDir
    }
}

# Copy plugin folder
$pluginSrc = Join-Path $ProjectRoot 'plugin'
$pluginDst = Join-Path $sourceStagingDir 'plugin'
if (Test-Path $pluginSrc) {
    Copy-Item $pluginSrc $pluginDst -Recurse
}

# Copy deploy/www folder structure (without downloads content)
$deploySrc = Join-Path $ProjectRoot 'deploy'
$deployDst = Join-Path $sourceStagingDir 'deploy'
New-Item -ItemType Directory -Path $deployDst -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $deployDst 'www') -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $deployDst 'www\assets') -Force | Out-Null

# Copy www html/css files
Get-ChildItem -Path (Join-Path $deploySrc 'www') -Filter '*.html' -File -ErrorAction SilentlyContinue | ForEach-Object {
    Copy-Item $_.FullName (Join-Path $deployDst 'www')
}
$assetsDir = Join-Path $deploySrc 'www\assets'
if (Test-Path $assetsDir) {
    Get-ChildItem -Path $assetsDir -File -ErrorAction SilentlyContinue | ForEach-Object {
        Copy-Item $_.FullName (Join-Path $deployDst 'www\assets')
    }
}

# Copy deploy scripts
@('package.cmd', 'package.ps1', 'deploywww.cmd') | ForEach-Object {
    $src = Join-Path $deploySrc $_
    if (Test-Path $src) {
        Copy-Item $src $deployDst
    }
}

# Create source archive
Compress-Archive -Path "$sourceStagingDir\*" -DestinationPath $sourceArchivePath -CompressionLevel Optimal -Force
Remove-Item $sourceStagingDir -Recurse -Force

$sourceSize = [math]::Round((Get-Item $sourceArchivePath).Length / 1KB, 2)
Write-Success "$sourceArchiveName ($sourceSize KB) -> archive"

# Copy source to downloads
$sourceDownloadPath = Join-Path $DownloadsDir $sourceArchiveName
Copy-Item $sourceArchivePath $sourceDownloadPath -Force
Write-Success "$sourceArchiveName -> downloads"

# Create latest source alias
$latestSourcePath = Join-Path $DownloadsDir "$ProductName-Source-latest.zip"
Copy-Item $sourceArchivePath $latestSourcePath -Force
Write-Success "$ProductName-Source-latest.zip -> downloads (alias)"

# Copy docs to www
Write-Step 'Copying documentation...'
@('README.md', 'CHANGELOG.md', 'SPEC.md') | ForEach-Object {
    $src = Join-Path $ProjectRoot $_
    $dst = Join-Path $WwwDir $_
    if (Test-Path $src) {
        Copy-Item $src $dst -Force
        Write-Success "$_ -> www"
    }
}

# Summary
Write-Header 'Package Complete'
Write-Host "  Epoch:   $HexEpoch" -ForegroundColor White
Write-Host "  Version: $version" -ForegroundColor White
Write-Host "  Full:    $version-$HexEpoch" -ForegroundColor White
Write-Host ''
Write-Host '  Archive:' -ForegroundColor Yellow
Get-ChildItem "$ArchiveDir\*$HexEpoch*.zip" -ErrorAction SilentlyContinue | ForEach-Object {
    $size = [math]::Round($_.Length / 1KB, 2)
    Write-Host "    $($_.Name) ($size KB)"
}
Write-Host ''
Write-Host '  Downloads:' -ForegroundColor Yellow
Get-ChildItem "$DownloadsDir\*.zip" -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object {
    $size = [math]::Round($_.Length / 1KB, 2)
    Write-Host "    $($_.Name) ($size KB)"
}
Write-Host ''
Write-Host '  Next: Run deploywww.cmd to publish to Z:\mbClouseau' -ForegroundColor Cyan
Write-Host ''
