# ============================================================
# build-book.ps1 — Gabung semua Markdown → 1 PDF buku utama
# Spesifikasi: B5 (17.6×25 cm), Times New Roman 12pt, 1.5 sp
# ============================================================

$ErrorActionPreference = "Stop"

$ProjectRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$BuildDir    = Join-Path $ProjectRoot "build"
$TemplateDir = Join-Path $ProjectRoot "templates"
$ChapterDir  = Join-Path $ProjectRoot "chapters"
$BackDir     = Join-Path $ProjectRoot "backmatter"

$OutputFile  = Join-Path $BuildDir "SIM-Era-AI-Book.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 = @()

# Front matter: Kata Pengantar
$InputFiles += Join-Path $BackDir "kata-pengantar.md"

# 18 Bab berurutan
for ($i = 1; $i -le 18; $i++) {
    $chapFile = Join-Path $ChapterDir ("bab-{0:D2}.md" -f $i)
    if (Test-Path $chapFile) {
        $InputFiles += $chapFile
    } else {
        Write-Warning "File tidak ditemukan: $chapFile"
    }
}

# Back matter
$InputFiles += Join-Path $BackDir "references.md"
$InputFiles += Join-Path $BackDir "glosarium.md"
$InputFiles += Join-Path $BackDir "indeks.md"
$InputFiles += Join-Path $BackDir "tentang-penulis.md"

# ── Validasi file ──
$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 BUKU: 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 = @(
    # Input files
    $InputFiles

    # Output
    "-o", $OutputFile

    # PDF engine
    "--pdf-engine=xelatex"

    # Template
    "--template=$Template"

    # Metadata
    "--metadata", "title=Sistem Informasi Manajemen di Era AI"
    "--metadata", "subtitle=Perspektif Strategis dan Pengambilan Keputusan"
    "--metadata", "author=Helmi Bahar Alim, S.Kom., M.Kom."
    "--metadata", "date=2025"
    "--metadata", "lang=id"

    # Options
    "--toc"
    "--toc-depth=3"
    "--number-sections"
    "--top-level-division=chapter"
    "--shift-heading-level-by=-1"

    # Table handling
    "--columns=72"

    # Resource path (for images)
    "--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
}
