<#
Nama Script   : AddOrReplaceEachMDFrontmatterToIndex.ps1
Deskripsi     :
Scan semua index.md secara rekursif dari folder yang dipilih.
- Kalau index.md sudah ada frontmatter (---) → inject/update field title
- Kalau index.md belum ada frontmatter → tambahkan frontmatter baru
- Kalau title sudah ada → tanya: 1 = replace, 2 = skip
Title diambil dari nama folder parent index.md itu berada.
#>

# ========================================================
# 📂 Input path folder target
# ========================================================
do {
    $targetFolder = Read-Host "📂 Masukkan path folder (contoh: D:\vault\02-Universitas)"
    if (-not (Test-Path $targetFolder)) {
        Write-Host "`n❌ Path tidak ditemukan. Periksa kembali!" -ForegroundColor Red
        $retry = $true
    } else {
        $retry = $false
    }
} while ($retry)

# ========================================================
# 🔍 Cari semua index.md secara rekursif
# ========================================================
$indexFiles = Get-ChildItem -Path $targetFolder -Filter "index.md" -Recurse -File | Sort-Object FullName

if ($indexFiles.Count -eq 0) {
    Write-Host "`n⚠️  Tidak ada index.md ditemukan di folder ini." -ForegroundColor Red
    exit
}

Write-Host "`n─────────────────────────────────────────" -ForegroundColor DarkGray
Write-Host "  Ditemukan $($indexFiles.Count) index.md" -ForegroundColor Cyan
Write-Host "─────────────────────────────────────────`n" -ForegroundColor DarkGray

# ========================================================
# 🔎 Pre-scan: deteksi file yang sudah punya title
# ========================================================
$filesWithTitle = @()
foreach ($file in $indexFiles) {
    $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8
    if (-not $content) { $content = "" }
    if ($content -match "^---\r?\n" -and $content -match "(?m)^title:") {
        # Ambil nilai title yang ada
        $existingTitle = ""
        if ($content -match "(?m)^title:\s*(.+)") {
            $existingTitle = $Matches[1].Trim()
        }
        $filesWithTitle += [PSCustomObject]@{
            File          = $file
            ExistingTitle = $existingTitle
            NewTitle      = (Split-Path $file.DirectoryName -Leaf)
        }
    }
}

# ========================================================
# ❓ Kalau ada file dengan title → tanya global dulu
# ========================================================
$globalChoice = $null

if ($filesWithTitle.Count -gt 0) {
    Write-Host "─────────────────────────────────────────" -ForegroundColor DarkGray
    Write-Host "  ⚠️  $($filesWithTitle.Count) file sudah punya title:" -ForegroundColor Yellow
    Write-Host "─────────────────────────────────────────" -ForegroundColor DarkGray

    foreach ($item in $filesWithTitle) {
        Write-Host "  📄 $($item.File.FullName)" -ForegroundColor DarkGray
        Write-Host "     title lama : `"$($item.ExistingTitle)`"" -ForegroundColor DarkGray
        Write-Host "     title baru : `"$($item.NewTitle)`"" -ForegroundColor Cyan
    }

    Write-Host ""
    Write-Host "  Pilih aksi untuk semua file di atas:" -ForegroundColor White
    Write-Host "  1 → Replace semua (pakai title baru dari nama folder)" -ForegroundColor Green
    Write-Host "  2 → Skip semua   (pertahankan title lama)" -ForegroundColor Yellow
    Write-Host "  3 → Tanya satu-satu per file" -ForegroundColor Cyan
    Write-Host ""

    do {
        $globalChoice = Read-Host "Pilih (1/2/3)"
        $globalChoice = $globalChoice.Trim()
    } while ($globalChoice -notin @("1", "2", "3"))

    Write-Host ""
}

# ========================================================
# 🚀 Eksekusi
# ========================================================
$successCount = 0
$skippedCount = 0
$errorCount   = 0

foreach ($file in $indexFiles) {

    $title   = Split-Path $file.DirectoryName -Leaf
    $content = Get-Content -Path $file.FullName -Raw -Encoding UTF8
    if (-not $content) { $content = "" }

    try {
        $newContent = $null

        # ── Sudah ada frontmatter ──────────────────────────
        if ($content -match "^---\r?\n") {

            # Sudah ada title
            if ($content -match "(?m)^title:") {

                $existingTitle = ""
                if ($content -match "(?m)^title:\s*(.+)") {
                    $existingTitle = $Matches[1].Trim()
                }

                # Tentukan choice per file
                $choice = $globalChoice

                if ($globalChoice -eq "3") {
                    # Tanya satu-satu
                    Write-Host "  📄 $($file.FullName)" -ForegroundColor DarkGray
                    Write-Host "     title lama : `"$existingTitle`"" -ForegroundColor DarkGray
                    Write-Host "     title baru : `"$title`"" -ForegroundColor Cyan
                    do {
                        $choice = Read-Host "     1 = Replace | 2 = Skip"
                        $choice = $choice.Trim()
                    } while ($choice -notin @("1", "2"))
                    Write-Host ""
                }

                if ($choice -eq "1") {
                    $newContent = $content -replace "(?m)^title:.*", "title: $title"
                    Write-Host "  🔄 Replaced  [$existingTitle] → [$title]" -ForegroundColor Cyan
                    Write-Host "     $($file.FullName)" -ForegroundColor DarkGray
                }
                else {
                    Write-Host "  ⏭️  Skipped   [$existingTitle] dipertahankan" -ForegroundColor Yellow
                    Write-Host "     $($file.FullName)" -ForegroundColor DarkGray
                    $skippedCount++
                    continue
                }
            }
            else {
                # Ada frontmatter tapi belum ada title → inject
                $newContent = $content -replace "^---\r?\n", "---`ntitle: $title`n"
                Write-Host "  ➕ Injected  title → [$title]" -ForegroundColor Green
                Write-Host "     $($file.FullName)" -ForegroundColor DarkGray
            }
        }
        else {
            # Belum ada frontmatter sama sekali → prepend
            $frontmatter = "---`ntitle: $title`n---`n"
            $newContent  = $frontmatter + $content
            Write-Host "  ✨ Created   frontmatter → [$title]" -ForegroundColor Green
            Write-Host "     $($file.FullName)" -ForegroundColor DarkGray
        }

        Set-Content -Path $file.FullName -Value $newContent -Encoding UTF8 -NoNewline
        $successCount++
    }
    catch {
        Write-Host "  ❌ Gagal: $($file.FullName) — $_" -ForegroundColor Red
        $errorCount++
    }
}

# ========================================================
# 📊 Summary
# ========================================================
Write-Host "`n─────────────────────────────────────────" -ForegroundColor DarkGray
Write-Host "  ✅ Berhasil  : $successCount file" -ForegroundColor Green
Write-Host "  ⏭️  Dilewati  : $skippedCount file" -ForegroundColor Yellow
Write-Host "  ❌ Gagal     : $errorCount file" -ForegroundColor Red
Write-Host "─────────────────────────────────────────`n" -ForegroundColor DarkGray