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

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

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

try {
    $wb = $excel.Workbooks.Open($item.FullName)
    Write-Output "excel_open_ok=True"

    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        $ws.Activate()
        $rowCount = $ws.UsedRange.Rows.Count
        $colCount = $ws.UsedRange.Columns.Count

        $doneRows = 0
        $coloredDoneRows = 0
        for ($row = 2; $row -le $rowCount; $row++) {
            $status = ([string]$ws.Cells.Item($row, 13).Text).Trim()
            if ($status -eq $statusDone) {
                $doneRows += 1
                $themeColor = $ws.Cells.Item($row, 1).Interior.ThemeColor
                $tint = $ws.Cells.Item($row, 1).Interior.TintAndShade
                if ($themeColor -eq 10 -and [math]::Abs($tint - 0.799981688894314) -lt 0.001) {
                    $coloredDoneRows += 1
                }
            }
        }

        $borderSample = $ws.Cells.Item(1, 1).Borders.Item(7).LineStyle
        Write-Output ($ws.Name + "_rows=" + $rowCount)
        Write-Output ($ws.Name + "_freezePanes=" + $excel.ActiveWindow.FreezePanes)
        Write-Output ($ws.Name + "_splitRow=" + $excel.ActiveWindow.SplitRow)
        Write-Output ($ws.Name + "_doneRows=" + $doneRows)
        Write-Output ($ws.Name + "_coloredDoneRows=" + $coloredDoneRows)
        Write-Output ($ws.Name + "_borderSampleLineStyle=" + $borderSample)
    }

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