$ErrorActionPreference = "Stop"

$root = Split-Path $PSScriptRoot -Parent
$item = Get-ChildItem -Path $root -File -Filter "*.xlsx" |
    Where-Object { $_.Name -like "*Sheet*.xlsx" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1

if (-not $item) {
    throw "Workbook not found"
}

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false

try {
    $wb = $excel.Workbooks.Open($item.FullName)
    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        for ($row = 2; $row -le $ws.UsedRange.Rows.Count; $row++) {
            $caseId = [string]$ws.Cells.Item($row, 1).Text
            if ($caseId -eq "B-PENALTY-002") {
                $text = [string]$ws.Cells.Item($row, 9).Value2
                $text = $text.Replace("F-CANCEL-001", "B-CANCEL-002")
                $text = $text.Replace("F-CANCEL-002", "B-CANCEL-003")
                $text = $text.Replace("F-CANCEL-003", "B-CANCEL-004")
                $ws.Cells.Item($row, 9).Value2 = $text
            }
        }
    }
    $wb.Save()
}
finally {
    if ($wb) {
        $wb.Close($true)
    }
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
