$ErrorActionPreference = "Stop"

function Decode-Utf16Base64($Value) {
    return [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Value))
}

$WorkbookPath = Get-ChildItem -Path (Get-Location) -Filter "*.xlsx" |
    Where-Object { $_.Name -like "SaaS_E2E*" -and $_.Name -notlike "*副本*" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1 -ExpandProperty FullName
if (-not $WorkbookPath) {
    throw "Workbook not found."
}

$updates = @{
    (Decode-Utf16Base64 "ZWeQbi8AxH4IVJ1PbmM=") = Decode-Utf16Base64 "QQAtAE8AUgBEAEUAUgAtADAAMAAxACAALQA+ACAAQQAtAFQAQQBTAEsALQAwADAAMQAgAC0APgAgAEEALQBEAEUATABJAFYARQBSAFkALQAwADAAMQAgAC0APgAgAEEALQBEAEUATABJAFYARQBSAFkALQAwADAAMgAgAC0APgAgAEIALQBTAEUAVABUAEwARQAtAFAATABBAFkARQBSAC0AQQBDAEMATwBVAE4AVAAtADAAMAAxACAALQA+ACAAQgAtAFMARQBUAFQATABFAC0AUABMAEEAWQBFAFIALQBBAFAAUABMAFkALQAwADAAMQA="
    (Decode-Utf16Base64 "KHWLTwdomJg=") = Decode-Utf16Base64 "O05BbQt6LQA4Toxj3GfRU1VTMFJTYktiDP9TYktiY2s4XoxbEGKii1VTdl7QY6RO036XeyaNVVM="
    (Decode-Utf16Base64 "TVJuf2Fn9k4=") = Decode-Utf16Base64 "OE6MY9xn8l2MWxBiOE7LU8aWiGNDZ4xUqGNVU02Rbn8b/zhOy1PGlu9TKFeiYlVTJ1mFU6VjVVMb/1NiS2ImjfdT71Pbj2VRomJVUydZhVMBMFNiS2Kii1VTATARYoR2NmVlURv/U2JLYlNiPmsmjTdi71OMW4RVAjA="
    (Decode-Utf16Base64 "S23Vi3BlbmM=") = Decode-Utf16Base64 "ZWeQblVT91MBMKKLVVMHaJiYATBQW1VT91MBMFNiS2ImjfdTATCMmjZlKmL+VgEwNmVlUdGRnZgBMFNiPmsmjTdi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ANAAuACAAglkAl+d+7X44TstTxpahWzhojFRTYj5rDP8OVO1+5lNMiGdiTIjscst6036XeydZQW0Legz/DU6zfmVRLGdtAGEAaQBuAF8AMAAwADIAAjA="
    (Decode-Utf16Base64 "hJgfZ9N+nGc=") = Decode-Utf16Base64 "OE6MY9xnootVU89+OE7LU8aW0VPZflNiS2IOVAz/U2JLYoxbEGJlXKZ+G/84TstTxpaMWxBiMQCnfi0AMgCnfoyaNmV2Xh91EGJTYktiNmVlURv/U2JLYoxbhFVTYj5rJo03Yg5U71MoVxFihHY2ZWVRLU75W+WLootVU9FTd40ATi6V036Xe3ZeEGKfUtBjpE7Tfpd7Jo1VUwIw"
    (Decode-Utf16Base64 "6I3vei8AtnIBYK1lAIo=") = Decode-Utf16Base64 "OE6MY9xnZWeQblVT91MBMDhOy1PGlqKLVVMBMFNiS2IRYoR2ootVUwEwU2JLYhFihHY2ZWVRsItVXwBO9IEb/1BbVVOMmjZltnIBYPJdjFsQYhv/U2JLYjZlZVHRkZ2YY2tueBv/036XeyaNVVPyXdBjpE52XtuPZVGFXzhOy1PGlqFbOGgvAA5U7X7Tfpd7BFkGdLZyAWACMA=="
    (Decode-Utf16Base64 "71PEfghULwCriBVfKHVzUft8") = Decode-Utf16Base64 "xH4IVD5OwYsa/20AYQBpAG4AXwAwADAAMgDjTgF4O05BbQt6G/+GidZ2OE6MY9xn0VNVUzBSU2JLYgEwU2JLYmVcpn4BMDhOy1PGloyaNmUBMFNiS2I2ZWVRH3UQYoxUU2JLYtBjpE7Tfpd7Jo1VUxv/DU4FUytUOE7LU8aW2X5TYktijFsQYtN+l3sCMA5U7X7Tfpd771MxdUYALQBTAEUAVABUAEwARQAtAFAAQQBZAC0AMAAwADEASXvscst6036XeydZQW0Len9ipWMCMA=="
    (Decode-Utf16Base64 "B1nobA==") = Decode-Utf16Base64 "nU9uYyAAZQAyAGUALwB0AGUAcwB0AHMALwDEfghUJ1lBbQt6LwB0AGUAcwB0AF8AZQAyAGUAXwBtAGEAaQBuAF8AMAAwADIAXwBvAHIAZABlAHIAXwB0AG8AXwBwAGwAYQB5AGUAcgBfAHMAZQB0AHQAbABlAG0AZQBuAHQALgBwAHkAIAD0ZrBlG//yXc5ObQBhAGkAbgBfADAAMAAyAPt5ZJZCAC0AUwBFAFQAVABMAEUALQBXAEEATgBZAE8AVQBKAEkALQBQAEEAWQAtADAAMAAxAAz/036Xe6FbOGgvAFNiPmsOVO1+7HLLehBiJ1lBbQt6AjA="
}

$excel = $null
$workbook = $null
$updatedRows = @()

try {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false
    $excel.DisplayAlerts = $false
    $workbook = $excel.Workbooks.Open($WorkbookPath)
    if ($workbook.ReadOnly) {
        throw "Workbook is read-only. Please close it in Excel and retry: $WorkbookPath"
    }

    foreach ($worksheet in $workbook.Worksheets) {
        $used = $worksheet.UsedRange
        $headers = @{}
        for ($column = 1; $column -le $used.Columns.Count; $column++) {
            $header = [string]$worksheet.Cells.Item(1, $column).Text
            if ($header) {
                $headers[$header] = $column
            }
        }
        $caseHeader = Decode-Utf16Base64 "KHWLTxZ/91M="
        if (-not $headers.ContainsKey($caseHeader)) {
            continue
        }

        for ($row = 2; $row -le $used.Rows.Count; $row++) {
            $caseId = ([string]$worksheet.Cells.Item($row, $headers[$caseHeader]).Text).Trim()
            if ($caseId -ne "F-MAIN-002") {
                continue
            }

            foreach ($entry in $updates.GetEnumerator()) {
                if ($headers.ContainsKey($entry.Key)) {
                    $cell = $worksheet.Cells.Item($row, $headers[$entry.Key])
                    $cell.Value2 = [string]$entry.Value
                    $cell.WrapText = $true
                }
            }
            $worksheet.Rows.Item($row).AutoFit() | Out-Null
            $updatedRows += "$($worksheet.Name)!$row"
        }
    }

    if ($updatedRows.Count -eq 0) {
        throw "F-MAIN-002 row was not found in workbook: $WorkbookPath"
    }

    $workbook.Save()
    Write-Host "Updated F-MAIN-002 in: $($updatedRows -join ', ')"
}
finally {
    if ($workbook -ne $null) {
        $workbook.Close($false)
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    }
    if ($excel -ne $null) {
        $excel.Quit()
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    }
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
