$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"
}

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

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false

try {
    $wb = $excel.Workbooks.Open($item.FullName)
    $formattedRows = 0

    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        $ws.Activate()

        $excel.ActiveWindow.FreezePanes = $false
        $excel.ActiveWindow.SplitColumn = 0
        $excel.ActiveWindow.SplitRow = 1
        $excel.ActiveWindow.FreezePanes = $true

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

        $borderRange = $ws.Range($ws.Cells.Item(1, 1), $ws.Cells.Item($rowCount, $colCount))
        $borderRange.Borders.LineStyle = 1
        $borderRange.Borders.Weight = 2
        $borderRange.Borders.ColorIndex = -4105

        for ($row = 2; $row -le $rowCount; $row++) {
            $status = ([string]$ws.Cells.Item($row, 13).Text).Trim()
            $rowRange = $ws.Range($ws.Cells.Item($row, 1), $ws.Cells.Item($row, $colCount))
            if ($status -eq $statusDone) {
                $rowRange.Interior.ThemeColor = 10
                $rowRange.Interior.TintAndShade = 0.799981688894314
                $formattedRows += 1
            }
            else {
                $rowRange.Interior.Pattern = -4142
            }
        }
    }

    $wb.Worksheets.Item(1).Activate()
    $wb.Save()
    Write-Output ("formatted_done_rows=" + $formattedRows)
    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()
}
