$tsDir = "d:\aoyiduo\woterm\woterm\private\languages\ts"
$outFile = Join-Path $tsDir "missing_translations_report.txt"

function Get-TranslationText {
    param($transNode)
    if ($null -eq $transNode) { return $null }
    if ($transNode -is [string]) {
        if ([string]::IsNullOrWhiteSpace($transNode)) { return $null }
        return $transNode
    }
    if ($transNode.InnerText -and -not [string]::IsNullOrWhiteSpace($transNode.InnerText)) {
        return $transNode.InnerText
    }
    if ($transNode.'#text' -and -not [string]::IsNullOrWhiteSpace($transNode.'#text')) {
        return $transNode.'#text'
    }
    return $null
}

$enFile = Join-Path $tsDir "woterm_en.ts.xml"
$enXml = [xml](Get-Content $enFile -Encoding UTF8)
$enMessages = @{}
foreach ($ctx in $enXml.TS.context) {
    $ctxName = $ctx.name
    foreach ($msg in $ctx.message) {
        $key = "$ctxName||$($msg.source)"
        $enMessages[$key] = $msg.source
    }
}

$files = Get-ChildItem $tsDir -Filter "woterm_*.ts.xml" | Sort-Object Name
$allMissing = @{}

foreach ($file in $files) {
    if ($file.Name -eq "woterm_en.ts.xml") { continue }
    $lang = $file.Name -replace 'woterm_(.*)\.ts\.xml', '$1'
    $xml = [xml](Get-Content $file.FullName -Encoding UTF8)
    $missing = @()
    
    foreach ($ctx in $xml.TS.context) {
        $ctxName = $ctx.name
        foreach ($msg in $ctx.message) {
            $transText = Get-TranslationText $msg.translation
            if ($null -eq $transText) {
                $missing += "$ctxName||$($msg.source)"
                $key = "$ctxName||$($msg.source)"
                if (-not $allMissing.ContainsKey($key)) {
                    $allMissing[$key] = @{}
                }
                $allMissing[$key][$lang] = $true
            }
        }
    }
    
    Write-Host "$lang : $($missing.Count) missing"
}

Write-Host ""
Write-Host "Total unique missing keys: $($allMissing.Count)"
Write-Host ""

$sortedKeys = $allMissing.Keys | Sort-Object

$report = @()
$report += "=== MISSING TRANSLATIONS REPORT ==="
$report += ""
$report += "Total unique missing entries: $($allMissing.Count)"
$report += ""

$langs = @("de", "es", "fr", "hi", "id", "ja", "ko", "ru", "zh_CN", "zh_TW")
$header = "Context`tSource`t" + ($langs -join "`t")
$report += $header

foreach ($key in $sortedKeys) {
    $parts = $key -split '\|\|', 2
    $ctx = $parts[0]
    $src = $parts[1]
    $row = "$ctx`t$src"
    foreach ($lang in $langs) {
        if ($allMissing[$key].ContainsKey($lang)) {
            $row += "`tMISSING"
        } else {
            $row += "`tOK"
        }
    }
    $report += $row
}

$report | Out-File -FilePath $outFile -Encoding UTF8
Write-Host "Report saved to: $outFile"

$uniqueMissingFile = Join-Path $tsDir "unique_missing_sources.txt"
$sortedKeys | ForEach-Object {
    $parts = $_ -split '\|\|', 2
    "[$($parts[0])] $($parts[1])"
} | Out-File -FilePath $uniqueMissingFile -Encoding UTF8
Write-Host "Unique missing list saved to: $uniqueMissingFile"
