param(
    [string]$langCode = "zh_CN"
)

$tsDir = "d:\aoyiduo\woterm\woterm\private\languages\ts"
$tsFile = Join-Path $tsDir "woterm_$langCode.ts.xml"
$transFile = Join-Path $tsDir "trans_zhcn.txt"

Write-Host "Processing $langCode..." -ForegroundColor Yellow

$translations = @{}

$lines = Get-Content $transFile -Encoding UTF8
foreach ($line in $lines) {
    if ([string]::IsNullOrWhiteSpace($line)) { continue }
    $parts = $line -split '\|\|\|', 3
    if ($parts.Length -ne 3) { continue }
    $ctx = $parts[0] -replace '\\n', "`n"
    $src = $parts[1] -replace '\\n', "`n"
    $trans = $parts[2] -replace '\\n', "`n"
    $key = $ctx + "||" + $src
    $translations[$key] = $trans
}

Write-Host "  Loaded $($translations.Count) translations"

$xml = New-Object System.Xml.XmlDocument
$xml.Load($tsFile)
$updated = 0

foreach ($ctx in $xml.TS.context) {
    $ctxName = $ctx.name
    foreach ($msg in $ctx.message) {
        $src = $msg.source
        $key = $ctxName + "||" + $src
        
        $transNode = $msg.translation
        $hasTranslation = $false
        
        if ($transNode -ne $null) {
            $txt = $transNode.InnerText
            if ($txt -ne $null -and $txt -ne "") {
                $hasTranslation = $true
            }
        }
        
        if (-not $hasTranslation -and $translations.ContainsKey($key)) {
            $newValue = $translations[$key]
            if ($transNode -eq $null) {
                $transNode = $xml.CreateElement("translation")
                $msg.AppendChild($transNode)
            }
            $transNode.InnerText = $newValue
            if ($transNode.type -eq "unfinished") {
                $transNode.RemoveAttribute("type")
            }
            $updated++
        }
    }
}

if ($updated -gt 0) {
    $xml.Save($tsFile)
    Write-Host "  Updated $updated translations" -ForegroundColor Green
} else {
    Write-Host "  No updates needed" -ForegroundColor Gray
}

Write-Host "Done!" -ForegroundColor Cyan
