param(
    [string]$langCode = "zh_CN",
    [string]$csvFile = "translations_zh_CN.csv"
)

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

Write-Host "Processing $langCode..." -ForegroundColor Yellow
Write-Host "  TS file: $tsFile"
Write-Host "  CSV file: $csvPath"

$translations = @{}
$csvData = Import-Csv $csvPath
foreach ($row in $csvData) {
    $key = $row.context + "||" + $row.source
    $translations[$key] = $row.translation
}

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

$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) {
            if ($transNode.InnerText -ne $null -and $transNode.InnerText -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
