$ErrorActionPreference = 'Stop'

$Root = (Resolve-Path '.').Path
$Out = Join-Path $Root 'runtime\testcase_excel_rows.json'
$item = Get-ChildItem -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)
    $ws = $wb.Worksheets.Item(1)
    $rowCount = $ws.UsedRange.Rows.Count
    $colCount = $ws.UsedRange.Columns.Count
    $rows = @()
    for ($r = 2; $r -le $rowCount; $r++) {
        $values = @()
        for ($c = 1; $c -le $colCount; $c++) {
            $values += [string]$ws.Cells.Item($r, $c).Text
        }
        $rows += [pscustomobject]@{
            row = $r
            values = $values
        }
    }
    $payload = [pscustomobject]@{
        workbook = $item.FullName
        rows = $rows
    }
    $json = $payload | ConvertTo-Json -Depth 8
    [System.IO.File]::WriteAllText($Out, $json, [System.Text.Encoding]::UTF8)
    $wb.Close($false)
    Write-Output $Out
}
finally {
    $excel.Quit()
}
