param(
    [string]$JsonPath
)

$ErrorActionPreference = "Stop"

$root = Split-Path $PSScriptRoot -Parent
if (-not $JsonPath) {
    throw "JsonPath is required"
}
$resolvedJson = Resolve-Path -LiteralPath $JsonPath
$item = Get-ChildItem -Path $root -File -Filter "*.xlsx" |
    Where-Object { $_.Name -like "*Sheet*.xlsx" } |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1

if (-not $item) {
    throw "Workbook 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 Delete-Case {
    param($Worksheet, [string]$CaseId)
    for ($row = $Worksheet.UsedRange.Rows.Count; $row -ge 2; $row--) {
        if (([string]$Worksheet.Cells.Item($row, 1).Text).Trim() -eq $CaseId) {
            $Worksheet.Rows.Item($row).Delete() | Out-Null
            Write-Output ("deleted=" + $Worksheet.Name + "|" + $CaseId + "|row=" + $row)
        }
    }
}

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)
    $caseId = [string]$Values[0]
    $row = Find-Row $Worksheet $caseId
    if ($row -le 0) {
        $row = $Worksheet.UsedRange.Rows.Count + 1
    }
    Write-Values $Worksheet $row $Values
    return $row
}

$payload = Read-JsonUtf8 $resolvedJson.Path
$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 ($caseId in @($payload.delete_case_ids)) {
        Delete-Case $caseWs ([string]$caseId)
        Delete-Case $flowWs ([string]$caseId)
    }
    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()
}
