param(
    [string]$langCode = "zh_CN",
    [string]$csvFile = "translations_utf8.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

$translations = @{}

$reader = New-Object System.IO.StreamReader($csvPath, [System.Text.Encoding]::UTF8)
$lineNum = 0
while ($null -ne ($line = $reader.ReadLine())) {
    $lineNum++
    if ($lineNum -eq 1) { continue }
    if ([string]::IsNullOrWhiteSpace($line)) { continue }
    
    $idx1 = $line.IndexOf(',')
    if ($idx1 -lt 0) { continue }
    $idx2 = $line.IndexOf(',', $idx1 + 1)
    if ($idx2 -lt 0) { continue }
    
    $ctx = $line.Substring(0, $idx1)
    $src = $line.Substring($idx1 + 1, $idx2 - $idx1 - 1)
    $trans = $line.Substring($idx2 + 1)
    
    if ($ctx.StartsWith('"') -and $ctx.EndsWith('"')) {
        $ctx = $ctx.Substring(1, $ctx.Length - 2)
    }
    if ($src.StartsWith('"') -and $src.EndsWith('"')) {
        $src = $src.Substring(1, $src.Length - 2)
    }
    if ($trans.StartsWith('"') -and $trans.EndsWith('"')) {
        $trans = $trans.Substring(1, $trans.Length - 2)
    }
    
    $key = $ctx + "||" + $src
    $translations[$key] = $trans
}
$reader.Close()

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
