$ErrorActionPreference = "Stop"

$root = Split-Path $PSScriptRoot -Parent
$item = Get-ChildItem -Path $root -File -Filter "*.xlsx" |
    Where-Object { $_.Name -like "*Sheet*.xlsx" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1
$jsonPath = Join-Path $root "runtime\paycenter_settlement_config_update.json"

if (-not $item) {
    throw "Workbook not found"
}
if (-not (Test-Path -LiteralPath $jsonPath)) {
    throw "Update json not found"
}

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

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

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

function Update-Or-Append {
    param($Worksheet, $Values)
    $row = Find-Row $Worksheet ([string]$Values[0])
    if ($row -le 0) {
        $row = $Worksheet.UsedRange.Rows.Count + 1
    }
    Write-Values $Worksheet $row $Values
    return $row
}

$payload = Read-JsonUtf8 $jsonPath
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false

try {
    $wb = $excel.Workbooks.Open($item.FullName)
    $caseWs = $wb.Worksheets.Item(1)
    $flowWs = $wb.Worksheets.Item(2)

    foreach ($rowValues in $payload.case_updates) {
        $row = Update-Or-Append $caseWs @($rowValues)
        Write-Output ("case=" + [string]$rowValues[0] + "|row=" + $row)
    }
    foreach ($rowValues in $payload.flow_updates) {
        $row = Update-Or-Append $flowWs @($rowValues)
        Write-Output ("flow=" + [string]$rowValues[0] + "|row=" + $row)
    }

    $wb.Save()
}
finally {
    if ($wb) {
        $wb.Close($true)
    }
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
