param(
    [string[]]$CaseIds
)

$ErrorActionPreference = "Stop"

$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."
}

$excel = $null
$workbook = $null

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
        for ($row = $used.Rows.Count; $row -ge 2; $row--) {
            $caseId = ([string]$worksheet.Cells.Item($row, 1).Text).Trim()
            if ($CaseIds -contains $caseId) {
                $worksheet.Rows.Item($row).Delete() | Out-Null
                Write-Host "Removed $caseId from $($worksheet.Name)"
            }
        }
    }

    $workbook.Save()
}
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()
}
