$ErrorActionPreference = 'Stop'

$Path = (Get-ChildItem -File -Filter '*.xlsx' | Where-Object { $_.Name -like '*Sheet*.xlsx' } | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName
if (-not $Path) {
    throw 'No testcase xlsx found.'
}
$Patterns = @('source_order_no', 'order_title', 'strategy_name', 'assignment_method')

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
try {
    $wb = $excel.Workbooks.Open($Path)
    Write-Output ('sheets=' + $wb.Worksheets.Count)
    for ($i = 1; $i -le $wb.Worksheets.Count; $i++) {
        $sheet = $wb.Worksheets.Item($i)
        Write-Output ($sheet.Name + ': rows=' + $sheet.UsedRange.Rows.Count + ', cols=' + $sheet.UsedRange.Columns.Count)
    }

    $ws = $wb.Worksheets.Item(1)
    $stateCount = 0
    for ($r = 2; $r -le $ws.UsedRange.Rows.Count; $r++) {
        $caseId = $ws.Cells.Item($r, 1).Text
        if ($caseId -like 'S-*') {
            $stateCount++
        }
    }
    Write-Output ('state_branch_rows=' + $stateCount)

    $hits = @()
    foreach ($pattern in $Patterns) {
        $found = $ws.UsedRange.Find($pattern)
        if ($null -ne $found) {
            $hits += ($pattern + '@' + $found.Address($false, $false))
        }
    }
    Write-Output ('english_var_hits=' + ($hits -join ','))
    $wb.Close($false)
}
finally {
    $excel.Quit()
}
