$ErrorActionPreference = 'Stop'

$Root = (Resolve-Path '.').Path
$Sorted = Join-Path $Root 'runtime\testcase_excel_sorted_rows.json'
if (-not (Test-Path $Sorted)) {
    throw 'Sorted rows json not found.'
}

function Read-JsonUtf8 {
    param([string]$Path)
    $text = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
    return $text | ConvertFrom-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.'
}

$payload = Read-JsonUtf8 $Sorted
$rows = @($payload.rows)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
try {
    $wb = $excel.Workbooks.Open($item.FullName)
    $ws = $wb.Worksheets.Item(1)
    $colCount = $ws.UsedRange.Columns.Count

    for ($i = 0; $i -lt $rows.Count; $i++) {
        $targetRow = $i + 2
        $values = @($rows[$i].values)
        for ($c = 1; $c -le $colCount; $c++) {
            $value = ''
            if (($c - 1) -lt $values.Count) {
                $value = [string]$values[$c - 1]
            }
            $ws.Cells.Item($targetRow, $c).Value2 = $value
        }
        $ws.Rows.Item($targetRow).WrapText = $true
        $ws.Rows.Item($targetRow).VerticalAlignment = -4160
    }

    $currentRows = $ws.UsedRange.Rows.Count
    $expectedRows = $rows.Count + 1
    if ($currentRows -gt $expectedRows) {
        for ($r = $currentRows; $r -gt $expectedRows; $r--) {
            $ws.Rows.Item($r).Delete() | Out-Null
        }
    }

    $wb.Save()
    $wb.Close($true)
    Write-Output ('sorted_rows=' + $rows.Count)
}
finally {
    $excel.Quit()
}
