param(
    [string]$WorkbookPath = ""
)

$ErrorActionPreference = "Stop"

if (-not $WorkbookPath) {
    $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 ($item) {
        $WorkbookPath = $item.FullName
    }
}

if (-not (Test-Path -LiteralPath $WorkbookPath)) {
    throw "Workbook not found: $WorkbookPath"
}

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

$missingRefs = New-Object System.Collections.Generic.List[string]
$wanted = @(
    "F-MAIN-001",
    "F-MAIN-002",
    "A-DELIVERY-002",
    "A-DELIVERY-003"
)

try {
    $wb = $excel.Workbooks.Open((Resolve-Path -LiteralPath $WorkbookPath).Path)
    Write-Output ("excel_open_ok=True")
    Write-Output ("sheets=" + $wb.Worksheets.Count)

    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        Write-Output ($ws.Name + "_rows=" + $ws.UsedRange.Rows.Count)
        Write-Output ($ws.Name + "_cols=" + $ws.UsedRange.Columns.Count)
    }

    foreach ($caseId in $wanted) {
        $found = $false
        for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
            $ws = $wb.Worksheets.Item($sheetIndex)
            for ($row = 2; $row -le $ws.UsedRange.Rows.Count; $row++) {
                if ([string]$ws.Cells.Item($row, 1).Text -eq $caseId) {
                    Write-Output ($caseId + "=" + $ws.Name + "|" + $ws.Cells.Item($row, 5).Text)
                    $found = $true
                    break
                }
            }
            if ($found) { break }
        }
        if (-not $found) {
            Write-Output ($caseId + "=MISSING")
        }
    }

    $openParen = [string][char]0xFF08
    $pattern = "(?<![A-Z0-9-])([A-Z]+-[A-Z0-9]+-\d+[A-Z]?)(?![A-Z0-9-])"
    $regex = New-Object System.Text.RegularExpressions.Regex($pattern)
    for ($sheetIndex = 1; $sheetIndex -le $wb.Worksheets.Count; $sheetIndex++) {
        $ws = $wb.Worksheets.Item($sheetIndex)
        for ($row = 2; $row -le $ws.UsedRange.Rows.Count; $row++) {
            $text = [string]$ws.Cells.Item($row, 9).Text
            if (-not $text) {
                continue
            }
            $matches = $regex.Matches($text)
            foreach ($match in $matches) {
                $afterIndex = $match.Index + $match.Length
                if ($afterIndex -ge $text.Length -or $text.Substring($afterIndex, 1) -ne $openParen) {
                    $missingRefs.Add($ws.Name + "!" + $row + ":" + $match.Value)
                }
            }
        }
    }
    Write-Output ("unannotated_step_refs=" + $missingRefs.Count)
    foreach ($item in $missingRefs) {
        Write-Output $item
    }

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