$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

if (-not $item) {
    throw "Workbook not found"
}

$doneStatus = -join @(
    [char]0x5DF2,
    [char]0x81EA,
    [char]0x52A8,
    [char]0x5316
)
$todoStatus = -join @(
    [char]0x5F85,
    [char]0x81EA,
    [char]0x52A8,
    [char]0x5316
)

$automatedIds = New-Object 'System.Collections.Generic.HashSet[string]'
@(
    "A-SAAS-001",
    "A-SAAS-003",
    "A-SAAS-004",
    "A-MEMBER-001",
    "A-AUTH-001",
    "A-PUSH-001",
    "A-PUSH-003",
    "A-ORDER-001",
    "A-ORDER-002",
    "A-TASK-001",
    "A-DELIVERY-001",
    "A-DELIVERY-002",
    "B-SETTLE-PAYCENTER-001",
    "B-SETTLE-PLAYER-ACCOUNT-001",
    "B-SETTLE-PLAYER-APPLY-001",
    "F-MAIN-001",
    "F-MAIN-002"
) | ForEach-Object { [void]$automatedIds.Add($_) }

$flowOrder = @(
    "F-MAIN-001",
    "F-MAIN-002",
    "F-REG-001",
    "F-CONFIG-001",
    "F-DISPATCH-001",
    "F-CANCEL-001",
    "F-MULTI-001",
    "F-PRICE-001",
    "F-ACCEPTANCE-L1L2-001",
    "F-ACCEPTANCE-L2L3-001",
    "F-WZG-AFTER-ACCEPT-BRANCH-001",
    "F-WYJ-SELF-FULFILL-L2L3-001",
    "F-PLAYER-BILLING-001",
    "F-PENALTY-001",
    "F-SETTLE-CONFIG-001",
    "F-SETTLE-L1L2-001",
    "F-SETTLE-PAY-001",
    "F-SETTLE-REJECT-001",
    "F-SETTLE-L2L3-001",
    "F-SETTLE-PAY-002",
    "F-SETTLE-REJECT-002",
    "F-SETTLE-REJECT-003",
    "F-SETTLE-REJECT-004",
    "F-SETTLE-REJECT-005",
    "F-SETTLE-REJECT-006",
    "F-SETTLE-REJECT-007"
)

function Sync-Status {
    param($Worksheet, $AutomatedIds, [string]$DoneStatus, [string]$TodoStatus)

    $rowCount = $Worksheet.UsedRange.Rows.Count
    for ($row = 2; $row -le $rowCount; $row++) {
        $caseId = ([string]$Worksheet.Cells.Item($row, 1).Text).Trim()
        if (-not $caseId) {
            continue
        }
        if ($AutomatedIds.Contains($caseId)) {
            $Worksheet.Cells.Item($row, 13).Value2 = $DoneStatus
        }
        else {
            $Worksheet.Cells.Item($row, 13).Value2 = $TodoStatus
        }
    }
}

function Reorder-Flow-Sheet {
    param($Worksheet, [string[]]$Order)

    $rowCount = $Worksheet.UsedRange.Rows.Count
    $colCount = $Worksheet.UsedRange.Columns.Count
    if ($colCount -lt 14) {
        $colCount = 14
    }

    $rowsById = @{}
    $allIds = New-Object System.Collections.Generic.List[string]
    for ($row = 2; $row -le $rowCount; $row++) {
        $caseId = ([string]$Worksheet.Cells.Item($row, 1).Text).Trim()
        if (-not $caseId) {
            continue
        }
        $values = New-Object System.Collections.Generic.List[string]
        for ($col = 1; $col -le $colCount; $col++) {
            $values.Add([string]$Worksheet.Cells.Item($row, $col).Value2)
        }
        $rowsById[$caseId] = $values
        $allIds.Add($caseId)
    }

    $finalIds = New-Object System.Collections.Generic.List[string]
    foreach ($caseId in $Order) {
        if ($rowsById.ContainsKey($caseId)) {
            $finalIds.Add($caseId)
        }
    }
    foreach ($caseId in $allIds) {
        if (-not $finalIds.Contains($caseId)) {
            $finalIds.Add($caseId)
        }
    }

    $targetRow = 2
    foreach ($caseId in $finalIds) {
        $values = $rowsById[$caseId]
        for ($col = 1; $col -le $colCount; $col++) {
            $Worksheet.Cells.Item($targetRow, $col).Value2 = [string]$values[$col - 1]
        }
        $targetRow += 1
    }
}

$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)

    Sync-Status $caseWs $automatedIds $doneStatus $todoStatus
    Sync-Status $flowWs $automatedIds $doneStatus $todoStatus
    Reorder-Flow-Sheet $flowWs $flowOrder

    $wb.Save()
    Write-Output ("synced_automated_ids=" + $automatedIds.Count)
    Write-Output ("workbook=" + $item.FullName)
}
finally {
    if ($wb) {
        $wb.Close($true)
    }
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}
