"""Named range helpers — standalone functions operating on a raw COM Workbook."""

from __future__ import annotations


def get_named_range_info(wb, max_count: int = 50) -> str:
    """Get named ranges from the workbook.

    wb: raw COM Workbook object
    max_count: maximum number to return
    Returns: formatted string matching SpreadJS output format
    """
    try:
        names = wb.Names
        total = names.Count
    except Exception:
        return 'No named ranges found.'

    if total == 0:
        return 'No named ranges found.'

    limit = min(total, max_count)
    lines: list[str] = []

    for i in range(1, limit + 1):
        try:
            n = names.Item(i)
            full_name = n.Name
            refers_to = n.RefersTo
            comment = n.Comment

            # Determine scope: sheet-scoped names contain '!'
            if '!' in full_name:
                scope = full_name.split('!')[0]
            else:
                scope = 'workbook'

            entry = f'  Name: {full_name} | Ref: {refers_to} | Scope: {scope}'
            if comment:
                entry += f' | Comment: {comment}'
            lines.append(entry)
        except Exception:
            # Some Name objects may be broken/hidden — skip them
            continue

    if not lines:
        return 'No named ranges found.'

    header = f'Named Ranges ({len(lines)}):'
    return '\n'.join([header] + lines)
