param(
    [string]$langCode = "zh_CN",
    [string]$transFile = "trans_zhcn.txt"
)

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

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

$translations = @{}

$lines = Get-Content $transPath -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

$ctxNodes = $xml.SelectNodes("/TS/context")
foreach ($ctxNode in $ctxNodes) {
    $ctxName = $ctxNode.SelectSingleNode("name").InnerText
    $msgNodes = $ctxNode.SelectNodes("message")
    foreach ($msgNode in $msgNodes) {
        $srcNode = $msgNode.SelectSingleNode("source")
        if ($srcNode -eq $null) { continue }
        $src = $srcNode.InnerText
        $key = $ctxName + "||" + $src
        
        $transNode = $msgNode.SelectSingleNode("translation")
        $hasTranslation = $false
        
        if ($transNode -ne $null) {
            $txt = $transNode.InnerText
            if (-not [string]::IsNullOrWhiteSpace($txt)) {
                $hasTranslation = $true
            }
        }
        
        if (-not $hasTranslation -and $translations.ContainsKey($key)) {
            $newValue = $translations[$key]
            if ($transNode -eq $null) {
                $transNode = $xml.CreateElement("translation")
                $msgNode.AppendChild($transNode)
            }
            $transNode.InnerText = $newValue
            $typeAttr = $transNode.GetAttributeNode("type")
            if ($typeAttr -ne $null -and $typeAttr.Value -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
