$ErrorActionPreference = 'Stop'

$Root = (Resolve-Path '.').Path
$WorkbookItem = Get-ChildItem -Path $Root -File -Filter '*.xlsx' | Where-Object { $_.Name -like '*Sheet*.xlsx' } | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$Workbook = if ($WorkbookItem) { $WorkbookItem.FullName } else { '' }
$JsonPath = Join-Path $Root 'runtime\testcase_excel_incremental_updates.json'

if (-not (Test-Path $Workbook)) {
    throw "Workbook not found: $Workbook"
}
if (-not (Test-Path $JsonPath)) {
    throw "Update json not found: $JsonPath"
}

function Read-JsonUtf8 {
    param([string]$Path)
    $text = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
    return $text | ConvertFrom-Json
}

function Find-CaseRow {
    param($Worksheet, [string]$CaseId)
    $maxRow = $Worksheet.UsedRange.Rows.Count
    for ($row = 2; $row -le $maxRow; $row++) {
        if ([string]$Worksheet.Cells.Item($row, 1).Text -eq $CaseId) {
            return $row
        }
    }
    return 0
}

function Write-Values {
    param($Worksheet, [int]$Row, $Values)
    for ($i = 0; $i -lt $Values.Count; $i++) {
        $Worksheet.Cells.Item($Row, $i + 1).Value2 = [string]$Values[$i]
    }
    $Worksheet.Rows.Item($Row).WrapText = $true
    $Worksheet.Rows.Item($Row).VerticalAlignment = -4160
}

function Append-Like-Previous {
    param($Worksheet, $Values)
    $row = $Worksheet.UsedRange.Rows.Count + 1
    Write-Values $Worksheet $row $Values
    return $row
}

function Update-Or-Append {
    param($Worksheet, $Values)
    $caseId = [string]$Values[0]
    $row = Find-CaseRow $Worksheet $caseId
    if ($row -gt 0) {
        Write-Values $Worksheet $row $Values
        return "updated $caseId at row $row"
    }
    $newRow = Append-Like-Previous $Worksheet $Values
    return "appended $caseId at row $newRow"
}

function Delete-CaseRows {
    param($Worksheet, [string[]]$CaseIds)
    for ($row = $Worksheet.UsedRange.Rows.Count; $row -ge 2; $row--) {
        $caseId = [string]$Worksheet.Cells.Item($row, 1).Text
        if ($CaseIds -contains $caseId) {
            $Worksheet.Rows.Item($row).Delete() | Out-Null
            Write-Output ("deleted misplaced " + $caseId + " at row " + $row)
        }
    }
}

$payload = Read-JsonUtf8 $JsonPath

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
try {
    $wb = $excel.Workbooks.Open($Workbook)
    $caseWs = $wb.Worksheets.Item(1)
    $flowWs = $wb.Worksheets.Item(2)

    Delete-CaseRows $caseWs @('F-ACCEPTANCE-L1L2-001', 'F-ACCEPTANCE-L2L3-001')
    if ($payload.delete_case_ids) {
        Delete-CaseRows $caseWs @($payload.delete_case_ids)
    }

    foreach ($item in $payload.case_updates) {
        Write-Output (Update-Or-Append $caseWs @($item))
    }
    foreach ($item in $payload.case_new_rows) {
        Write-Output (Update-Or-Append $caseWs @($item))
    }
    foreach ($item in $payload.flow_updates) {
        Write-Output (Update-Or-Append $flowWs @($item))
    }

    $wb.Save()
    $wb.Close($true)
}
finally {
    $excel.Quit()
}
