#!/usr/bin/env python3
"""Blueprint token benchmark: the same small UI written three ways.

  A. Brilliant Blueprint rows, as an agent writes them (fixtures/<name>.bl).
  B. A Figma-style JSON node tree, minified, holding only the fields the
     design needs (fixtures/<name>.figma.json).
  C. Figma plugin-API JavaScript that builds the same tree, one statement per
     property (fixtures/<name>.plugin.js).

The .bl files are written by hand. B and C are GENERATED from them by the
mapping in this file, so the three forms always describe the same design. A
token of a .bl row the mapping does not carry fails the run, so the larger
forms never describe less than the Blueprint does.

Run:    python3 bench.py            (counts tokens, rewrites results.json)
        python3 bench.py --check    (also fails if a generated fixture on disk
                                     differs from what the mapping emits)
Needs:  pip install tiktoken        (o200k_base; cl100k_base as a cross-check)

With no tiktoken the script prints NOT MEASURED and exits 2: it never prints
a number from a guess.
"""
import datetime, json, os, re, statistics, sys

HERE = os.path.dirname(os.path.abspath(__file__))
FIX = os.path.join(HERE, 'fixtures')
NAMES = ('pricing_card', 'nav_bar', 'sign_in_form', 'dashboard_tile', 'task_list', 'confirm_modal')

try:
    import tiktoken
    ENC = {n: tiktoken.get_encoding(n) for n in ('o200k_base', 'cl100k_base')}
    TOKENIZER = 'tiktoken ' + tiktoken.__version__
except Exception:
    ENC = None


# ---------------------------------------------------------------- Blueprint parsing
def split_top(s, sep=' '):
    out, cur, depth, q = [], '', 0, False
    i = 0
    while i < len(s):
        ch = s[i]
        if q:
            cur += ch
            if ch == '\\' and i + 1 < len(s):
                cur += s[i + 1]; i += 1
            elif ch == '"':
                q = False
        elif ch == '"':
            q = True; cur += ch
        elif ch in '([':
            depth += 1; cur += ch
        elif ch in ')]':
            depth -= 1; cur += ch
        elif ch == sep and depth == 0:
            if cur != '' or sep != ' ':
                out.append(cur)
            cur = ''
        else:
            cur += ch
        i += 1
    if cur != '' or (sep != ' ' and out):
        out.append(cur)
    return out


TYPES = ('fr', 'r', 'c', 'gr')

TYPES = ('fr', 'r', 'c', 'gr')


def head(tok):
    m = re.match(r'^([a-zA-Z]+)[\(\[]', tok)
    return m.group(1) if m else tok


def inner(tok):
    return tok[tok.index('(') + 1:-1] if '(' in tok and tok.endswith(')') else tok[tok.index('[') + 1:-1]


class Node:
    def __init__(s, depth, toks):
        s.depth, s.toks, s.kids, s.parent = depth, toks, [], None

    def get(s, h):
        for t in s.toks:
            if head(t) == h and t != h:
                return t
        return None

    @property
    def kind(s):
        for t in s.toks:
            if t in TYPES or head(t) in ('al', 't', 'v', 'inst', 'svg', 'line', 'mask', 'comp'):
                return head(t)
        return '?'


def parse(text):
    lines = [l.rstrip() for l in text.split('\n') if l.strip() and not l.strip().startswith(('--', '//'))]
    base = min(len(l) - len(l.lstrip(' ')) for l in lines)
    roots, stack = [], []
    for l in lines:
        d = (len(l) - len(l.lstrip(' ')) - base) // 2
        n = Node(d, split_top(l.strip()))
        while stack and stack[-1].depth >= d:
            stack.pop()
        if stack:
            n.parent = stack[-1]; stack[-1].kids.append(n)
        else:
            roots.append(n)
        stack.append(n)
    return roots


def walk(roots):
    for r in roots:
        yield r
        yield from walk(r.kids)



# ---------------------------------------------------------------- the mapping
WEIGHT = {'r': 400, 'm': 500, 'sb': 600, 'b': 700, 'eb': 800, 'bl': 900}
FIGMA_STYLE = {'r': 'Regular', 'm': 'Medium', 'sb': 'Semi Bold', 'b': 'Bold', 'eb': 'Extra Bold', 'bl': 'Black'}
FALIGN = {'s': 'MIN', 'c': 'CENTER', 'e': 'MAX', 'sb': 'SPACE_BETWEEN'}
MAPPED = {'al', 't', 'p', 's', 'f', 'st', 'rd', 'o', 'shadow', 'fr', 'r', 'c', 'gr', 'clip', 'abs', 'svg'}


def model(n, dropped):
    """One row as a neutral dict every emitter reads. Unmapped tokens are counted."""
    m = {'kind': n.kind, 'kids': [], 'name': None}
    k = n.kind
    if k not in ('al', 't', 'fr', 'r', 'c', 'gr', 'svg'):
        raise KeyError('type ' + k)
    for t in n.toks:
        h = head(t)
        if t.startswith('"'):
            m['name'] = json.loads(t)
        elif t.startswith('#'):
            m['ref'] = t
        elif h not in MAPPED:
            dropped.append(t)
        elif h == 'al':
            a = split_top(inner(t), ',')
            m['dir'] = a[0]
            for x in a[1:]:
                hx = head(x)
                if hx in ('x', 'y'):
                    m[hx] = inner(x)
                elif hx == 'g':
                    m['gap'] = inner(x)
                elif hx == 'pad':
                    m['pad'] = split_top(inner(x), ',')
                else:
                    dropped.append('al:' + x)
        elif h == 't' and t != 't':
            a = split_top(inner(t), ',')
            m['text'] = json.loads(a[0])
            m['font'] = a[1] if len(a) > 1 else 'Inter'
            m['size'] = a[2] if len(a) > 2 else '14'
            for x in a[3:]:
                if x in WEIGHT:
                    m['weight'] = x
                elif x.startswith('align('):
                    m['align'] = inner(x)
                elif x.startswith('lh(') and not x.startswith('lh(auto'):
                    m['lh'] = inner(x)
                else:
                    dropped.append('t:' + x)
        elif h == 'svg' and t != 'svg':
            m['icon'] = inner(t).replace('icon:', '')
        elif h == 'p' and t != 'p':
            m['p'] = split_top(inner(t), ',')
        elif h == 's' and t != 's':
            m['s'] = split_top(inner(t), ',')
        elif h == 'f' and '[' in t:
            m['fills'] = [split_top(e[1:-1], ',')[0] for e in split_top(inner(t), ',')] if inner(t) else []
            if len(m['fills']) > 1:
                dropped.append('f:extra-layers')
        elif h == 'st' and '[' in t:
            e = split_top(split_top(inner(t), ',')[0][1:-1], ',')
            w = [x for x in e[1:] if x.startswith('w(')]
            m['stroke'] = (e[0], inner(w[0]) if w else '1')
        elif h == 'rd' and t != 'rd':
            m['rd'] = split_top(inner(t), ',')
        elif h == 'o' and t != 'o':
            m['o'] = inner(t)
        elif h == 'shadow':
            a = split_top(inner(t), ',')
            sh = {'color': '#000000', 'o': '1', 'x': '0', 'y': '0', 'blur': '0'}
            if a and head(a[0]) not in sh:
                sh['color'] = a.pop(0)
            for x in a:
                if head(x) in sh:
                    sh[head(x)] = inner(x)
                else:
                    dropped.append('shadow:' + x)
            m['shadow'] = sh
        elif t in ('clip', 'abs'):
            m[t] = True
    for kid in n.kids:
        c = model(kid, dropped)
        c['parent'] = m
        m['kids'].append(c)
    return m



# ---------------------------------------------------------------- C: Figma-style JSON node tree
def rgb(spec):
    """-> ({r,g,b} to 3 decimals, opacity or None, variable name or None)."""
    spec = spec.strip()
    if spec.startswith('$'):
        return None, None, spec[1:].replace('.', '/')
    m = re.match(r'^solid\((\$[\w.\-]+|#[0-9A-Fa-f]{6}),o\((\$[\w.\-]+|[\d.]+)\)\)$', spec)
    if m and '$' in spec:
        col, _, var = rgb(m.group(1))
        return col, fnum(m.group(2)), var
    m = re.match(r'^solid\((#[0-9A-Fa-f]{6}),o\(([\d.]+)\)\)$', spec)
    op = None
    if m:
        spec, op = m.group(1), float(m.group(2))
    h = spec
    return {c: fnum(str(round(int(h[i:i + 2], 16) / 255, 3))) for c, i in (('r', 1), ('g', 3), ('b', 5))}, op, None


def paint(spec):
    col, op, var = rgb(spec)
    p = {'type': 'SOLID', 'boundVariables': {'color': {'type': 'VARIABLE_ALIAS', 'id': var}}} if var else {'type': 'SOLID', 'color': col}
    if op is not None:
        p['opacity'] = op
    return p


def fnum(v):
    if v.startswith('$'):
        return {'type': 'VARIABLE_ALIAS', 'id': v[1:].replace('.', '/')}
    f = float(v)
    return int(f) if f == int(f) else f


class Counter:
    n = 0


def figma(m, ctr=None):
    """A minimal node: only the fields that carry this design. A real REST or plugin
    dump carries many more per node (see the unpaired Figma context in results)."""
    ctr = ctr or Counter()
    ctr.n += 1
    k = m['kind']
    par = m.get('parent')
    flow = par is not None and par['kind'] == 'al' and not m.get('abs')
    n = {'id': '1:%d' % ctr.n,
         'name': m['name'] or (m.get('text') if k == 't' else {'al': 'Frame', 'fr': 'Frame', 'gr': 'Group', 'r': 'Rectangle', 'c': 'Ellipse', 'svg': 'Icon'}[k]),
         'type': {'al': 'FRAME', 'fr': 'FRAME', 'gr': 'GROUP', 'r': 'RECTANGLE', 'c': 'ELLIPSE', 't': 'TEXT', 'svg': 'INSTANCE'}[k]}
    if k == 'svg':
        n['componentId'] = 'icon/' + m['icon']
    if k == 'al':
        n['layoutMode'] = 'VERTICAL' if m['dir'] == 'v' else 'HORIZONTAL'
        main, cross = ('y', 'x') if m['dir'] == 'v' else ('x', 'y')
        if m.get(main) and m[main] != 's':
            n['primaryAxisAlignItems'] = FALIGN.get(m[main], 'SPACE_BETWEEN')
        if m.get(cross) and m[cross] != 's':
            n['counterAxisAlignItems'] = FALIGN[m[cross]]
        if m.get('gap') and m['gap'] not in ('0', '$spacing.none'):
            n['itemSpacing'] = fnum(m['gap'])
        pad = m.get('pad') or []
        if any(p not in ('0', '$spacing.none') for p in pad):
            t, r, b, l = {1: pad * 4, 2: [pad[0], pad[1]] * 2 if len(pad) == 2 else None, 4: pad}.get(len(pad)) or (pad + pad)[:4]
            n.update(paddingTop=fnum(t), paddingRight=fnum(r), paddingBottom=fnum(b), paddingLeft=fnum(l))
    if m.get('p') and not flow:
        n['x'], n['y'] = fnum(m['p'][0]), fnum(m['p'][1])
    if m.get('abs'):
        n['layoutPositioning'] = 'ABSOLUTE'
    for ax, dim, sizing in ((0, 'width', 'layoutSizingHorizontal'), (1, 'height', 'layoutSizingVertical')):
        v = (m.get('s') or ['hug', 'hug'])[ax]
        if v in ('hug', ''):
            if k in ('al', 't'):
                n[sizing] = 'HUG'
        elif v.startswith('fill'):
            n[sizing] = 'FILL'
        else:
            n[dim] = fnum(v)
    if k == 't':
        n['characters'] = m['text']
        st = {'fontFamily': m['font'], 'fontSize': fnum(m['size']), 'fontWeight': WEIGHT[m.get('weight', 'r')]}
        if m.get('align', 'l') != 'l':
            st['textAlignHorizontal'] = {'c': 'CENTER', 'r': 'RIGHT', 'j': 'JUSTIFIED'}[m['align']]
        if m.get('lh'):
            st['lineHeightPercentFontSize'] = fnum(m['lh']) if m['lh'].startswith('$') else round(float(m['lh']) * 100, 2)
        n['style'] = st
    if 'fills' in m:
        n['fills'] = [paint(f) for f in m['fills'][:1]]
    if m.get('stroke'):
        n['strokes'] = [paint(m['stroke'][0])]
        n['strokeWeight'] = fnum(m['stroke'][1])
    if m.get('rd'):
        if len(m['rd']) == 1:
            n['cornerRadius'] = fnum(m['rd'][0])
        else:
            n['rectangleCornerRadii'] = [fnum(r) for r in m['rd']]
    if m.get('shadow'):
        sh = m['shadow']
        col, _, var = rgb(sh['color'])
        e = {'type': 'DROP_SHADOW', 'offset': {'x': fnum(sh['x']), 'y': fnum(sh['y'])}, 'radius': fnum(sh['blur'])}
        if var:
            e['boundVariables'] = {'color': {'type': 'VARIABLE_ALIAS', 'id': var}}
            e['opacity'] = fnum(sh['o'])
        else:
            e['color'] = dict(col, a=fnum(sh['o']))
        n['effects'] = [e]
    if m.get('o'):
        n['opacity'] = float(m['o'])
    if m.get('clip'):
        n['clipsContent'] = True
    if m['kids']:
        n['children'] = [figma(c, ctr) for c in m['kids']]
    return n


# ---------------------------------------------------------------- D: Figma plugin-API JavaScript
def js(v):
    return json.dumps(v, separators=(',', ':'), ensure_ascii=False)


def plugin_js(tree):
    """Straight-line script derived from C: one statement per property, no helper
    functions, no loops, no error handling. A lower bound for that style."""
    out, fonts = [], []

    def font_of(n):
        st = n['style']
        style = {v: FIGMA_STYLE[k] for k, v in WEIGHT.items()}[st['fontWeight']]
        return {'family': st['fontFamily'], 'style': style}

    def collect(n):
        if n['type'] == 'TEXT' and font_of(n) not in fonts:
            fonts.append(font_of(n))
        for c in n.get('children', []):
            collect(c)

    collect(tree)
    for f in fonts:
        out.append('await figma.loadFontAsync(%s);' % js(f))

    def emit(n, parent, i=[0]):
        i[0] += 1
        v = 'n%d' % i[0]
        make = {'FRAME': 'createFrame', 'GROUP': 'createFrame', 'RECTANGLE': 'createRectangle', 'ELLIPSE': 'createEllipse', 'TEXT': 'createText'}.get(n['type'])
        if n['type'] == 'INSTANCE':
            out.append('const %s=(await figma.importComponentByKeyAsync(%s)).createInstance();' % (v, js(n['componentId'])))
        else:
            out.append('const %s=figma.%s();' % (v, make))
        out.append('%s.name=%s;' % (v, js(n['name'])))
        if parent:
            out.append('%s.appendChild(%s);' % (parent, v))
        if n['type'] == 'TEXT':
            out.append('%s.fontName=%s;' % (v, js(font_of(n))))
            out.append('%s.fontSize=%s;' % (v, js(n['style']['fontSize'])))
            out.append('%s.characters=%s;' % (v, js(n['characters'])))
            if 'textAlignHorizontal' in n['style']:
                out.append('%s.textAlignHorizontal=%s;' % (v, js(n['style']['textAlignHorizontal'])))
            if 'lineHeightPercentFontSize' in n['style']:
                out.append('%s.lineHeight={unit:"PERCENT",value:%s};' % (v, js(n['style']['lineHeightPercentFontSize'])))
        for key in ('layoutMode', 'primaryAxisAlignItems', 'counterAxisAlignItems', 'itemSpacing', 'paddingTop', 'paddingRight',
                    'paddingBottom', 'paddingLeft', 'layoutPositioning', 'x', 'y', 'fills', 'strokes', 'strokeWeight', 'cornerRadius',
                    'effects', 'opacity', 'clipsContent'):
            if key in n:
                val = n[key]
                if key == 'effects':
                    val = [dict(e, visible=True, blendMode='NORMAL') for e in val]
                out.append('%s.%s=%s;' % (v, key, js(val)))
        if 'rectangleCornerRadii' in n:
            for kname, val in zip(('topLeftRadius', 'topRightRadius', 'bottomRightRadius', 'bottomLeftRadius'), n['rectangleCornerRadii']):
                out.append('%s.%s=%s;' % (v, kname, js(val)))
        if 'width' in n or 'height' in n:
            out.append('%s.resize(%s,%s);' % (v, js(n.get('width', 100)), js(n.get('height', 100))))
        for key in ('layoutSizingHorizontal', 'layoutSizingVertical'):
            if key in n and (parent or n[key] == 'HUG'):
                out.append('%s.%s=%s;' % (v, key, js(n[key])))
        for c in n.get('children', []):
            emit(c, v)

    emit(tree, None)
    return '\n'.join(out) + '\n'



# ---------------------------------------------------------------- measuring
def forms(name):
    """(blueprint, figma json, plugin js) for one fixture. Fails on any token
    of a row the mapping does not carry, so the larger forms never describe
    less than the Blueprint does."""
    with open(os.path.join(FIX, name + '.bl')) as f:
        bl = f.read()
    roots = parse(bl)
    dropped = []
    models = [model(r, dropped) for r in roots]
    if dropped:
        sys.exit('%s: tokens the mapping does not carry: %s' % (name, dropped))
    if len(models) != 1:
        sys.exit('%s: one root row per fixture' % name)
    tree = figma(models[0], Counter())
    return bl, json.dumps(tree, separators=(',', ':'), ensure_ascii=False) + '\n', plugin_js(tree), sum(1 for _ in walk(roots))


def main():
    check = '--check' in sys.argv
    if ENC is None:
        print('NOT MEASURED: tiktoken is not installed (pip install tiktoken). No numbers printed.')
        sys.exit(2)
    rows, stale = [], []
    for name in NAMES:
        bl, fj, pj, n = forms(name)
        for ext, text in (('.figma.json', fj), ('.plugin.js', pj)):
            path = os.path.join(FIX, name + ext)
            old = open(path).read() if os.path.exists(path) else None
            if old != text:
                if check:
                    stale.append(name + ext)
                else:
                    with open(path, 'w') as f:
                        f.write(text)
        r = {'fixture': name, 'elements': n}
        for enc in ENC:
            t = [len(ENC[enc].encode(x)) for x in (bl, fj, pj)]
            r[enc] = {'blueprint': t[0], 'figma_json': t[1], 'plugin_js': t[2],
                      'figma_json_x': round(t[1] / t[0], 2), 'plugin_js_x': round(t[2] / t[0], 2)}
        r['bytes'] = {'blueprint': len(bl.encode()), 'figma_json': len(fj.encode()), 'plugin_js': len(pj.encode())}
        rows.append(r)
    if stale:
        sys.exit('generated fixtures differ from the mapping (run python3 bench.py): ' + ', '.join(stale))

    def summary(enc):
        out = {}
        for form in ('figma_json', 'plugin_js'):
            xs = [r[enc][form + '_x'] for r in rows]
            out[form] = {'median_x': round(statistics.median(xs), 2), 'min_x': min(xs), 'max_x': max(xs),
                         'total_x': round(sum(r[enc][form] for r in rows) / sum(r[enc]['blueprint'] for r in rows), 2)}
        return out

    result = {'n': len(rows), 'tokenizer': TOKENIZER, 'encodings': list(ENC), 'fixtures': rows,
              'summary': {enc: summary(enc) for enc in ENC}}
    path = os.path.join(HERE, 'results.json')
    prior = json.load(open(path)) if os.path.exists(path) else {}
    body = {k: v for k, v in prior.items() if k != 'measured'}
    if check and body != result:
        sys.exit('results.json differs from this run (run python3 bench.py)')
    if body != result:
        result['measured'] = datetime.date.today().isoformat()
        with open(path, 'w') as f:
            json.dump(result, f, indent=2)
            f.write('\n')
    else:
        result['measured'] = prior.get('measured')

    print('%s, o200k_base tokens, n = %d, results.json measured %s' % (TOKENIZER, len(rows), result['measured']))
    print('%-16s %8s %10s %11s %10s %12s %10s' % ('fixture', 'elements', 'blueprint', 'figma json', 'ratio', 'plugin js', 'ratio'))
    for r in rows:
        o = r['o200k_base']
        print('%-16s %8d %10d %11d %9.2fx %12d %9.2fx' % (r['fixture'], r['elements'], o['blueprint'], o['figma_json'], o['figma_json_x'], o['plugin_js'], o['plugin_js_x']))
    for enc in ENC:
        sm = result['summary'][enc]
        print('%s: figma json median %.2fx (range %.2f to %.2f), plugin js median %.2fx (range %.2f to %.2f)' % (
            enc, sm['figma_json']['median_x'], sm['figma_json']['min_x'], sm['figma_json']['max_x'],
            sm['plugin_js']['median_x'], sm['plugin_js']['min_x'], sm['plugin_js']['max_x']))


if __name__ == '__main__':
    main()
