#Requires -Version 5.1
<#
.SYNOPSIS
    Baut den DesTEngS-Lebenslauf aus source/cv.md in PDF und DOCX.

.DESCRIPTION
    Deterministischer Build ohne GUI oder Komfortfunktionen.
    - PDF via Pandoc + LuaLaTeX, nutzt templates/template.tex
    - DOCX via Pandoc, nutzt templates/reference.docx
    - Log in output/build.log (überschrieben pro Build)
    - Exit-Code 0 = beide Ausgaben erfolgreich, 1 = ein oder beide Schritte fehlgeschlagen

.NOTES
    Voraussetzungen auf dem System:
    - Pandoc (im PATH)
    - MiKTeX mit LuaLaTeX und den Paketen fontspec, microtype, polyglossia,
      geometry, xcolor, hyperref, graphicx, enumitem, titlesec, fancyhdr,
      lastpage, xurl, plex-otf (für IBM Plex Sans).
    MiKTeX mit "Install missing packages on the fly: Yes" zieht Fehlende
    beim ersten Lauf automatisch.
#>

$ErrorActionPreference = 'Continue'
$PSNativeCommandUseErrorActionPreference = $false

# --- Pfade (alle relativ zum Speicherort dieses Skripts) ---------------------
$scriptDir    = Split-Path -Parent $MyInvocation.MyCommand.Path
$baseDir      = Split-Path -Parent $scriptDir
$sourceFile   = Join-Path $baseDir 'source\cv.md'
$sourceDir    = Join-Path $baseDir 'source'
$templateTex  = Join-Path $baseDir 'templates\template.tex'
$referenceDoc = Join-Path $baseDir 'templates\reference.docx'
$outputDir    = Join-Path $baseDir 'output'
$outputPdf    = Join-Path $outputDir 'Lebenslauf_Dr-Ing_Thomas_Langer.pdf'
$outputDocx   = Join-Path $outputDir 'Lebenslauf_Dr-Ing_Thomas_Langer.docx'
$logFile      = Join-Path $outputDir 'build.log'

# --- Output-Ordner sicherstellen ---------------------------------------------
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}

# --- Log initialisieren (UTF-8 ohne BOM) --------------------------------------
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
function Write-Log {
    param([string]$Line)
    [System.IO.File]::AppendAllText($logFile, $Line + [Environment]::NewLine, $utf8NoBom)
}
[System.IO.File]::WriteAllText($logFile, '', $utf8NoBom)

Write-Log "===== Build gestartet: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ====="
Write-Log "Source:       $sourceFile"
Write-Log "Template-TEX: $templateTex"
Write-Log "Reference:    $referenceDoc"
Write-Log "Output-Dir:   $outputDir"
Write-Log ''

$overallExit = 0

# --- Pflichtdateien prüfen ----------------------------------------------------
foreach ($f in @($sourceFile, $templateTex, $referenceDoc)) {
    if (-not (Test-Path $f)) {
        Write-Log "FEHLER: Pflichtdatei fehlt: $f"
        $overallExit = 1
    }
}
if ($overallExit -ne 0) {
    Write-Log "===== Abbruch: Pflichtdateien fehlen ====="
    exit $overallExit
}

# --- PDF-Build ----------------------------------------------------------------
Write-Log '--- Pandoc -> PDF (LuaLaTeX) ---'
$pdfArgs = @(
    '--from=markdown+smart',
    '--pdf-engine=lualatex',
    "--template=$templateTex",
    "--resource-path=$sourceDir",
    "--output=$outputPdf",
    $sourceFile
)
Write-Log ('Cmd: pandoc ' + ($pdfArgs -join ' '))
$pdfOutput = & pandoc @pdfArgs 2>&1
$pdfExit = $LASTEXITCODE
$pdfOutput | ForEach-Object { Write-Log ([string]$_) }
if ($pdfExit -eq 0 -and (Test-Path $outputPdf)) {
    $sizeKB = [math]::Round((Get-Item $outputPdf).Length / 1KB, 1)
    Write-Log "PDF OK: $outputPdf ($sizeKB KB)"
} else {
    Write-Log "PDF FEHLER (Exit $pdfExit)"
    $overallExit = 1
}
Write-Log ''

# --- DOCX-Build ---------------------------------------------------------------
Write-Log '--- Pandoc -> DOCX ---'
$docxArgs = @(
    '--from=markdown+smart',
    "--reference-doc=$referenceDoc",
    "--resource-path=$sourceDir",
    "--output=$outputDocx",
    $sourceFile
)
Write-Log ('Cmd: pandoc ' + ($docxArgs -join ' '))
$docxOutput = & pandoc @docxArgs 2>&1
$docxExit = $LASTEXITCODE
$docxOutput | ForEach-Object { Write-Log ([string]$_) }
if ($docxExit -eq 0 -and (Test-Path $outputDocx)) {
    $sizeKB = [math]::Round((Get-Item $outputDocx).Length / 1KB, 1)
    Write-Log "DOCX OK: $outputDocx ($sizeKB KB)"
} else {
    Write-Log "DOCX FEHLER (Exit $docxExit)"
    $overallExit = 1
}
Write-Log ''

Write-Log "===== Build beendet: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), Exit-Code $overallExit ====="

exit $overallExit
