"""COM cell style reader — reads Excel COM styles into compact dicts.

Default values are omitted to save tokens.  Keys are literal COM
property paths (e.g. "Font.Bold", "Interior.Color") so the agent
can assign them back without any translation.
"""

from shortcut_xl._log import xl_log

# Border edge indices (used by clear_formatting)
_BORDER_EDGES = {
    'borderLeft': 7,  # xlEdgeLeft
    'borderTop': 8,  # xlEdgeTop
    'borderBottom': 9,  # xlEdgeBottom
    'borderRight': 10,  # xlEdgeRight
}


def read_style(cell) -> dict:
    """Read COM cell style into a compact dict.

    Keys are COM property paths. Default values are omitted.
    Colors are raw BGR integers — the native COM format.
    """
    s: dict = {}

    try:
        font = cell.Font

        if font.Bold:
            s['Font.Bold'] = True
        if font.Italic:
            s['Font.Italic'] = True
        if font.Name:
            s['Font.Name'] = font.Name
        if font.Size:
            s['Font.Size'] = font.Size

        fc = font.Color
        if fc is not None and int(fc) != 0:
            s['Font.Color'] = int(fc)

        ul = font.Underline
        if ul is not None and ul != -4142:  # xlUnderlineStyleNone
            s['Font.Underline'] = ul

        if font.Strikethrough:
            s['Font.Strikethrough'] = True

        ic = cell.Interior.Color
        if ic is not None and int(ic) != 0xFFFFFF:
            s['Interior.Color'] = int(ic)

        ha = cell.HorizontalAlignment
        if ha is not None and ha != 1:  # xlGeneral
            s['HorizontalAlignment'] = ha

        va = cell.VerticalAlignment
        if va is not None and va != -4107:  # xlBottom
            s['VerticalAlignment'] = va

        if cell.WrapText:
            s['WrapText'] = True

        indent = cell.IndentLevel
        if indent and indent > 0:
            s['IndentLevel'] = indent

        nf = cell.NumberFormat
        if nf and nf != 'General':
            s['NumberFormat'] = nf

        # Borders — only non-default edges
        for edge_idx in _BORDER_EDGES.values():
            try:
                border = cell.Borders(edge_idx)
                ls = border.LineStyle
                if ls is None or ls == -4142:  # xlLineStyleNone
                    continue
                s[f'Borders({edge_idx}).LineStyle'] = ls
                wt = border.Weight
                if wt is not None:
                    s[f'Borders({edge_idx}).Weight'] = wt
                bc = border.Color
                if bc is not None and int(bc) != 0:
                    s[f'Borders({edge_idx}).Color'] = int(bc)
            except Exception:
                pass

    except Exception as e:
        xl_log(f'read_style failed: {e}')

    return s
