#!/usr/bin/env python3
"""One base-pay picture per role: every distinct US dollar annual base range it prints.

Reads react-roles.json. Rules, in order:
- Ranges come from the board's pay field and from the posting text; the two
  often repeat each other, so a role keeps each distinct (low, high) pair once.
- Left out: field ranges paid by the hour or month (interns, contractors);
  text ranges introduced as on-target earnings, total cash or total
  compensation, or with commission (Braze prints base and then OTE; only base
  is kept). Grafana Labs writes "OTE (On-Target Earnings)/Base compensation
  range" for engineers, one range that is both; that one is kept. A single
  amount written as a range ("$320,000 — $320,000", Anthropic) is kept with
  width 0. Left out also: anything with a low end under $20,000 or a high end over $5,000,000.
- A role with several ranges prints them for location zones ("Zone A", "SF Bay
  Area", "Colorado range") or, at SpaceX, for levels. The study uses two of
  them: top, the range with the highest midpoint (the most expensive zone the
  role names), and bottom, the lowest. One range means top = bottom.
- Midpoint = (low + high) / 2. Width = high / low - 1.
Writes role-pay.json here.
Usage: python3 pay.py
"""
import json
import re
from pathlib import Path

HERE = Path(__file__).resolve().parent
NOT_BASE = re.compile(r'(?i)\bOTE\b|on[- ]target|total (?:target )?(?:cash|comp\w*)|commission')
BOTH = re.compile(r'OTE \(On-Target Earnings\)/Base compensation range')
ANNUAL_FIELD = {None, '1 YEAR', 'per-year-salary', 'YEAR', 'year', 'yearly', 'annual'}


def ranges(role):
    out, seen = [], set()
    for x in role['field_ranges']:
        if x['period'] not in ANNUAL_FIELD:
            continue
        out.append(('field', x['low'], x['high'], x['label'][:120]))
    for x in role['text_ranges']:
        if NOT_BASE.search(x['context'][-100:]) and not BOTH.search(x['context'][-100:]):
            continue
        out.append(('text', x['low'], x['high'], x['context'][-120:]))
    keep = []
    for src, lo, hi, lab in out:
        if not (20000 <= lo <= hi <= 5000000):
            continue
        k = (round(lo), round(hi))
        if k in seen:
            continue
        seen.add(k)
        keep.append({'source': src, 'low': lo, 'high': hi, 'label': lab})
    return keep


def main():
    rows = json.load(open(HERE / 'react-roles.json'))
    out = []
    for r in rows:
        rs = ranges(r)
        mid = lambda x: (x['low'] + x['high']) / 2  # noqa: E731
        top = max(rs, key=mid) if rs else None
        bottom = min(rs, key=mid) if rs else None
        out.append({'id': r['id'], 'ranges': rs, 'top': top, 'bottom': bottom})
    json.dump(out, open(HERE / 'role-pay.json', 'w'), ensure_ascii=False, indent=0)
    print(len(out), 'roles;', sum(1 for x in out if x['top']), 'with a base range')


if __name__ == '__main__':
    main()
