$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
$deleted = @()

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 ($caseId -like "S-MAIN-*" -or $caseId -like "S-SUB-*" -or $caseId -like "S-COMBO-*") {
                $deleted += "$caseId@$row"
                $worksheet.Rows.Item($row).Delete() | Out-Null
            }
        }
    }

    $workbook.Save()
    Write-Host "Deleted generic status cases: $($deleted.Count)"
    if ($deleted.Count -gt 0) {
        Write-Host ($deleted -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()
}
