"""
Compare the height of the default Button with its Outline style.

Usage (from the repo root):
    python3 .claude/skills/theme-review/scripts/button-heights.py <theme-slug>

Checks theme.json and each style variation (merged over theme.json). The
height that matters is top + bottom padding + top + bottom border width.

Output, one line per file that differs:
    BUTTON HEIGHT <file>: outline is <n>px taller|shorter
    UNITS <file>: ...    different units (rem vs em); not raised, the
                         reviewer's visual check covers it

Model checked against the browser on WordPress 7.1 (Repose, Memoriam, Denton,
Formwork, Ellusive, Purple): the outline takes core's is-style-outline rule
(2px border, 0.667em padding) for anything its own variation doesn't set, and
that rule beats elements.button and core/button.
"""
import json, os, re, sys

def get(d, *ks):
    for k in ks:
        if not isinstance(d, dict) or k not in d:
            return None
        d = d[k]
    return d

def merge(a, b):
    out = dict(a or {})
    for k, v in (b or {}).items():
        out[k] = merge(out.get(k), v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
    return out

CUSTOM = {}

def resolve(v):
    """Replace var(--wp--custom--a--b) with settings.custom.a.b when it's a plain value."""
    def sub(m):
        val = get(CUSTOM, *[re.sub(r'-([a-z])', lambda x: x.group(1).upper(), k) for k in m.group(1).split('--')])
        if val is None:
            val = get(CUSTOM, *m.group(1).split('--'))
        return str(val) if isinstance(val, (str, int, float)) else m.group(0)
    return re.sub(r'var\(--wp--custom--([a-z0-9-]+)\)', sub, v)

def term(v):
    """Split a length into (base, px): 'calc(X - 1px)' -> ('X', -1), '2px' -> ('', 2)."""
    v = resolve(re.sub(r'\s+', ' ', str(v or '0')).strip())
    m = re.fullmatch(r'calc\((.+) ([+-]) ([\d.]+)px\)', v)
    if m:
        return m.group(1), float(m.group(3)) * (1 if m.group(2) == '+' else -1)
    m = re.fullmatch(r'([\d.]+)px|0', v)
    if m:
        return '', float(m.group(1) or 0)
    return v, 0.0

def height(style):
    pad, b = get(style, 'spacing', 'padding') or {}, get(style, 'border') or {}
    if isinstance(pad, str):
        pad = {'top': pad, 'bottom': pad}
    bases, px = [], 0.0
    for v in (pad.get('top'), pad.get('bottom'), get(b, 'top', 'width') or b.get('width'), get(b, 'bottom', 'width') or b.get('width')):
        base, n = term(v)
        px += n
        if base:
            bases.append(base)
    return sorted(bases), px

CORE_BUTTON = {'spacing': {'padding': {'top': 'calc(0.667em + 2px)', 'bottom': 'calc(0.667em + 2px)'}}, 'border': {'width': '0'}}

def buttons(s):
    """Default and outline button boxes, as WordPress 7.1 renders them.

    The default button takes core's element styles, then the theme's
    elements.button, then core/button. The outline button takes core's
    is-style-outline rule (2px border, 0.667em padding) for whatever its own
    variation doesn't set: that rule beats elements.button and core/button
    (measured on Repose, Memoriam and Denton).
    """
    block = {k: v for k, v in (get(s, 'blocks', 'core/button') or {}).items() if k != 'variations'}
    default = merge(merge(CORE_BUTTON, get(s, 'elements', 'button')), block)
    own = get(s, 'blocks', 'core/button', 'variations', 'outline') or {}
    outline = {'spacing': {'padding': {'top': '0.667em', 'bottom': '0.667em'}}, 'border': {'width': '2px'}}
    if get(own, 'spacing', 'padding') is not None:
        outline['spacing'] = {'padding': get(own, 'spacing', 'padding')}
    if any(get(own, 'border', k) is not None for k in ('width', 'top', 'bottom')):
        outline['border'] = get(own, 'border')
    return default, outline

theme = sys.argv[1]
tj = json.load(open(os.path.join(theme, 'theme.json')))
base = tj.get('styles', {})
files = ['theme.json'] + sorted('styles/' + f for f in os.listdir(os.path.join(theme, 'styles')) if f.endswith('.json')) if os.path.isdir(os.path.join(theme, 'styles')) else ['theme.json']
for f in files:
    var = {} if f == 'theme.json' else json.load(open(os.path.join(theme, f)))
    s = merge(base, var.get('styles', {}))
    if f != 'theme.json' and s == base:
        continue
    CUSTOM = merge(get(tj, 'settings', 'custom'), get(var, 'settings', 'custom'))
    d, o = buttons(s)
    hd, ho = height(d), height(o)
    if hd != ho:
        if hd[0] == ho[0]:
            what = 'outline is %gpx %s' % (abs(ho[1] - hd[1]), 'taller' if ho[1] > hd[1] else 'shorter')
        else:
            print('UNITS %s/%s: default %s, outline %s' % (theme, f, ' + '.join(hd[0] + ['%gpx' % hd[1]]), ' + '.join(ho[0] + ['%gpx' % ho[1]])))
            continue
        print('BUTTON HEIGHT %s/%s: %s' % (theme, f, what))
