# ============================================================
# build-worksheets.ps1 — Gabung 18 worksheet → 1 PDF
# ============================================================

$ErrorActionPreference = "Stop"

$ProjectRoot   = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$BuildDir      = Join-Path $ProjectRoot "build"
$TemplateDir   = Join-Path $ProjectRoot "templates"
$WorksheetDir  = Join-Path $ProjectRoot "worksheets"

$OutputFile = Join-Path $BuildDir "SIM-Era-AI-Worksheets.pdf"
$Template   = Join-Path $TemplateDir "book-template.tex"

# ── Buat folder build ──
if (-not (Test-Path $BuildDir)) {
    New-Item -ItemType Directory -Path $BuildDir -Force | Out-Null
}

# ── Susun urutan file ──
$InputFiles = @()
for ($i = 1; $i -le 18; $i++) {
    $wsFile = Join-Path $WorksheetDir ("worksheet-A{0:D2}.md" -f $i)
    if (Test-Path $wsFile) {
        $InputFiles += $wsFile
    } else {
        Write-Warning "File tidak ditemukan: $wsFile"
    }
}

# ── Validasi ──
$missing = $InputFiles | Where-Object { -not (Test-Path $_) }
if ($missing) {
    Write-Error "File berikut tidak ditemukan:`n$($missing -join "`n")"
    exit 1
}

Write-Host "========================================" -ForegroundColor Cyan
Write-Host " BUILD WORKSHEET: SIM di Era AI"        -ForegroundColor Cyan
Write-Host " Output : $OutputFile"                   -ForegroundColor Cyan
Write-Host " Files  : $($InputFiles.Count) file"    -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

# ── Pandoc command ──
$pandocArgs = @(
    $InputFiles

    "-o", $OutputFile

    "--pdf-engine=xelatex"
    "--template=$Template"

    "--metadata", "title=Lembar Kerja Mahasiswa (Worksheet)"
    "--metadata", "subtitle=Pendamping Buku SIM di Era AI"
    "--metadata", "author=Helmi Bahar Alim, S.Kom., M.Kom."
    "--metadata", "date=2025"
    "--metadata", "lang=id"

    "--toc"
    "--toc-depth=2"
    "--number-sections"
    "--top-level-division=chapter"
    "--shift-heading-level-by=-1"

    "--columns=72"
    "--resource-path=$ProjectRoot"
)

Write-Host "`nMenjalankan Pandoc..." -ForegroundColor Yellow

& pandoc @pandocArgs

if ($LASTEXITCODE -eq 0) {
    $fileSize = [math]::Round((Get-Item $OutputFile).Length / 1MB, 2)
    Write-Host "`n✅ Build berhasil!" -ForegroundColor Green
    Write-Host "   File : $OutputFile" -ForegroundColor Green
    Write-Host "   Ukuran: $fileSize MB" -ForegroundColor Green
} else {
    Write-Error "❌ Pandoc gagal dengan exit code $LASTEXITCODE"
    exit 1
}
