#!/usr/bin/env python3
"""What US tech companies publish as base pay for roles that work in React.

Reads react-roles.json, role-pay.json, labels.json, companies.json. Prints every
figure the article uses (results.txt) and writes react-pay.json, one row per
labeled role, for the appendix.

Sample rules:
- Main sample: roles open in the United States, at companies based in the
  United States (companies.json), not internships, labeled react_role
  (labeling-instructions.md), that print a US dollar annual base range
  (pay.py). Comparison: the same for roles labeled optional.
- Level is read from the title (../ai-tools-postings/extract.py, seniority()):
  "Senior", "Sr", "Lead", "III" are senior; "Staff", "Principal", "Architect"
  are staff; no marker is "no level in title" (mostly "Software Engineer",
  "Software Engineer II", "Frontend Engineer").
- Pay of a role: top = the range with the highest midpoint among the zones it
  names, bottom = the lowest (pay.py). Midpoint = (low + high) / 2.
- A role whose title names another country ("| Canada | Remote", "Japan")
  is not a US role, even when the board's location field says US. Seven
  labeled roles were dropped by this rule after labeling (ELSEWHERE); they stay
  in react-pay.json with "excluded" set.
- Company-weighted median: the median of each company's own median, so a
  company with 40 roles counts once.

Employer cost (ECEC, BLS, June 2026, private industry, professional and
related, $ per hour worked): wages 50.98, paid leave 6.78, supplemental pay 2.90,
insurance 5.47, retirement and savings 2.75, legally required 4.81. A salary
already includes paid leave, so salary = wages + paid leave = 57.76; costs on
top of salary are the other four, 15.93, or 27.6% of salary. The calculator
replaces the ECEC average for legally required benefits with the federal
payroll taxes at the role's own salary: Social Security 6.2% up to $184,500
(2026), Medicare 1.45%, FUTA 0.6% of the first $7,000; state unemployment
insurance and workers' compensation are left out.
Usage: python3 analyze.py
"""
import collections
import json
import re
import statistics as st
from pathlib import Path

HERE = Path(__file__).resolve().parent
US = 'United States'
LEVELS = [('mid', 'No level in title'), ('senior', 'Senior'), ('staff', 'Staff and principal')]
ECEC = {'wages': 50.98, 'paid_leave': 6.78, 'supplemental': 2.90, 'insurance': 5.47,
        'retirement': 2.75, 'legally_required': 4.81}
ELSEWHERE = re.compile(r'\b(?:Canada|Japan|Mexico|Brazil|United Kingdom|India|Germany|Poland|Ireland|Spain|Portugal|'
                       r'Argentina|Colombia|Singapore|Australia|Israel)\b')
AI_LABS = ('Anthropic PBC', 'OpenAI', 'Harvey', 'Perplexity AI, Inc.')
SS_BASE, SS, MEDICARE, FUTA = 184500, 0.062, 0.0145, 0.006 * 7000


def mid(r):
    return (r['low'] + r['high']) / 2


def q(xs, p):
    xs = sorted(xs)
    return st.quantiles(xs, n=4, method='inclusive')[p] if len(xs) > 1 else xs[0]


def money(x):
    return f'${x:,.0f}'


def employer_cost(salary):
    salary_hour = ECEC['wages'] + ECEC['paid_leave']
    other = (ECEC['supplemental'] + ECEC['insurance'] + ECEC['retirement']) / salary_hour
    taxes = SS * min(salary, SS_BASE) + MEDICARE * salary + FUTA
    return {'salary': salary, 'benefits': other * salary, 'payroll_taxes': taxes,
            'total': salary * (1 + other) + taxes, 'other_share': other}


def main():
    roles = {r['id']: r for r in json.load(open(HERE / 'react-roles.json'))}
    pay = {p['id']: p for p in json.load(open(HERE / 'role-pay.json'))}
    labels = json.load(open(HERE / 'labels.json'))
    rows = []
    for k, lab in labels.items():
        r, p = roles[k], pay[k]
        assert US in r['countries'] and r['hq'] == US and r['seniority'] != 'intern'
        rows.append({'id': k, 'company': r['company'], 'company_name': r['company_name'], 'title': r['title'],
                     'url': r['url'], 'api': r['api'], 'published': r['published'], 'seniority': r['seniority'],
                     'mode': r['mode'], 'us_states': r['us_states'], 'label': lab['label'],
                     'ranges': p['ranges'], 'top': p['top'], 'bottom': p['bottom'],
                     'excluded': 'title names another country' if ELSEWHERE.search(r['title']) else ''})
    json.dump(rows, open(HERE / 'react-pay.json', 'w'), ensure_ascii=False, indent=0)
    labeled = rows
    rows = [r for r in rows if not r['excluded']]

    P = print
    allr = list(roles.values())
    P('# React cost: base pay in US tech job postings, read 24 November 2026')
    P()
    P('## Funnel')
    P('roles mentioning React (any country, any company):', len(allr))
    us = [r for r in allr if US in r['countries'] and r['hq'] == US]
    P('  open in the US at US-based companies:', len(us), 'at', len({r['company'] for r in us}), 'companies')
    P('  of them not internships (labeled):', len(labeled))
    P('  dropped after labeling, title names another country:', [(r['company'], r['title'], r['label']) for r in labeled if r['excluded']])
    P('  analyzed:', len(rows))
    c = collections.Counter(r['label'] for r in rows)
    P('  labels:', dict(c))
    main_ = [r for r in rows if r['label'] == 'react_role']
    paid = [r for r in main_ if r['top']]
    P('react_role roles:', len(main_), 'at', len({r['company'] for r in main_}), 'companies')
    P('  with a US dollar base range:', len(paid), f'({100 * len(paid) / len(main_):.1f}%)', 'at',
      len({r['company'] for r in paid}), 'companies')
    P('  without:', [(r['company'], r['title']) for r in main_ if not r['top']])
    P()
    P('## Main sample: react_role with a base range, by level in title (top zone)')
    P('level | roles | companies | median low | median high | median midpoint | p25 midpoint | p75 midpoint | company-weighted median midpoint')
    for lev, name in LEVELS + [('junior', 'Junior')]:
        g = [r for r in paid if r['seniority'] == lev]
        if not g:
            continue
        mids = [mid(r['top']) for r in g]
        byc = collections.defaultdict(list)
        for r in g:
            byc[r['company']].append(mid(r['top']))
        cw = st.median([st.median(v) for v in byc.values()])
        P(f"{name} | {len(g)} | {len(byc)} | {money(st.median([r['top']['low'] for r in g]))} | "
          f"{money(st.median([r['top']['high'] for r in g]))} | {money(st.median(mids))} | {money(q(mids, 0))} | "
          f"{money(q(mids, 2))} | {money(cw)}")
    mids = [mid(r['top']) for r in paid]
    P(f'all levels | {len(paid)} | median midpoint {money(st.median(mids))} | p25 {money(q(mids, 0))} | p75 {money(q(mids, 2))}')
    P(f'  lowest low printed: {money(min(r["top"]["low"] for r in paid))}; highest high: {money(max(r["top"]["high"] for r in paid))}')
    P()
    P('## Same, bottom zone (cheapest zone the role names)')
    for lev, name in LEVELS:
        g = [r for r in paid if r['seniority'] == lev]
        b = [mid(r['bottom']) for r in g]
        P(f"{name} | {len(g)} | median low {money(st.median([r['bottom']['low'] for r in g]))} | "
          f"median high {money(st.median([r['bottom']['high'] for r in g]))} | median midpoint {money(st.median(b))}")
    multi = [r for r in paid if len(r['ranges']) > 1]
    P('roles printing more than one range (zones or levels):', len(multi), f'({100 * len(multi) / len(paid):.1f}%)')
    ratio = [mid(r['bottom']) / mid(r['top']) for r in multi]
    P(f'  bottom zone midpoint as share of top zone, median: {100 * st.median(ratio):.1f}%; min {100 * min(ratio):.1f}%')
    P()
    P('## Width of the top range (high / low - 1)')
    w = [r['top']['high'] / r['top']['low'] - 1 for r in paid]
    P(f'median {100 * st.median(w):.1f}%; p25 {100 * q(w, 0):.1f}%; p75 {100 * q(w, 2):.1f}%; '
      f'width 50% or more: {sum(x >= 0.5 for x in w)} of {len(w)}; zero width: {sum(x == 0 for x in w)}')
    dollars = [r['top']['high'] - r['top']['low'] for r in paid]
    P(f'median spread in dollars {money(st.median(dollars))}; $100,000 or more: {sum(d >= 100000 for d in dollars)}')
    P()
    P('## Concentration')
    cc = collections.Counter(r['company_name'] for r in paid)
    P('roles per company, top 10:', cc.most_common(10))
    big = cc.most_common(1)[0][0]
    rest = [mid(r['top']) for r in paid if r['company_name'] != big]
    P(f'median midpoint without {big}: {money(st.median(rest))} ({len(rest)} roles)')
    for lev, name in LEVELS:
        g = [mid(r['top']) for r in paid if r['seniority'] == lev and r['company_name'] not in AI_LABS]
        P(f'{name} without {", ".join(AI_LABS)}: {len(g)} roles, median midpoint {money(st.median(g))}')
    for cn in ('Palantir Technologies Inc.', 'OpenAI'):
        g = [r for r in paid if r['company_name'] == cn and r['seniority'] == 'mid']
        P(f'{cn}, no level in title: {len(g)} roles, median midpoint {money(st.median([mid(r["top"]) for r in g]))}; '
          f'titles {sorted(r["title"] for r in g)}')
    P()
    P('## Against the first page (serp-audit.md)')
    sen = [r for r in paid if r['seniority'] == 'senior']
    P(f"senior roles: {len(sen)}; top range ends at or below $185,000 (top of KORE1 senior): "
      f"{sum(r['top']['high'] <= 185000 for r in sen)}; starts at or above $185,000: {sum(r['top']['low'] >= 185000 for r in sen)}; "
      f"midpoint above $185,000: {sum(mid(r['top']) > 185000 for r in sen)}")
    P(f"senior roles whose cheapest zone starts at or above $145,000 (bottom of KORE1 senior): "
      f"{sum(r['bottom']['low'] >= 145000 for r in sen)}")
    P(f"senior roles, cheapest zone: ends at or below $185,000: {sum(r['bottom']['high'] <= 185000 for r in sen)} "
      f"{[(r['company'], r['title'], r['bottom']['low'], r['bottom']['high']) for r in sen if r['bottom']['high'] <= 185000]}; "
      f"starts at or above $185,000: {sum(r['bottom']['low'] >= 185000 for r in sen)}")
    P(f"all roles whose cheapest zone midpoint is below the BLS median $135,980: "
      f"{sum(mid(r['bottom']) < 135980 for r in paid)} of {len(paid)}")
    P()
    P('## Table: the 12 companies with the most React roles in the main sample')
    byc = collections.defaultdict(list)
    for r in paid:
        byc[r['company_name']].append(r)
    for name, rs in sorted(byc.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:12]:
        lv = collections.Counter(r['seniority'] for r in rs)
        P(f"{name} | {len(rs)} | {dict(lv)} | {money(min(r['top']['low'] for r in rs))} to "
          f"{money(max(r['top']['high'] for r in rs))} | median midpoint {money(st.median([mid(r['top']) for r in rs]))}")
    P()
    P('## Comparison: optional (React a plus or one of several)')
    opt = [r for r in rows if r['label'] == 'optional' and r['top']]
    for lev, name in LEVELS:
        g = [mid(r['top']) for r in opt if r['seniority'] == lev]
        if g:
            P(f'{name} | {len(g)} | median midpoint {money(st.median(g))}')
    P()
    P('## Work mode of main sample')
    P(dict(collections.Counter(r['mode'] for r in paid)))
    for m in ('remote', 'hybrid', 'office'):
        g = [mid(r['top']) for r in paid if r['seniority'] == 'senior' and r['mode'] == m]
        P(f'senior {m}: {len(g)} roles, median midpoint {money(st.median(g))}')
    P()
    P('## Employer cost on top of base (ECEC June 2026, professional and related, private industry)')
    sh = ECEC['wages'] + ECEC['paid_leave']
    oth = ECEC['supplemental'] + ECEC['insurance'] + ECEC['retirement'] + ECEC['legally_required']
    P(f'salary per hour worked (wages + paid leave) {sh:.2f}; other costs {oth:.2f}; share of salary {100 * oth / sh:.1f}%')
    P(f'other costs without legally required {oth - ECEC["legally_required"]:.2f} = {100 * (oth - ECEC["legally_required"]) / sh:.1f}% of salary')
    P(f'benefits as share of total compensation {100 * 22.71 / 73.69:.1f}% (the share ECEC prints is 30.8%)')
    P(f'all private industry workers: benefits $14.07 of $46.89 = {100 * 14.07 / 46.89:.1f}% of total compensation (ECEC prints 30.0%)')
    for lev, name in LEVELS:
        g = [mid(r['top']) for r in paid if r['seniority'] == lev]
        s = st.median(g)
        e = employer_cost(s)
        P(f"{name}: salary {money(s)} -> benefits {money(e['benefits'])} + federal payroll taxes {money(e['payroll_taxes'])}"
          f" = {money(e['total'])} ({e['total'] / s:.3f}x); per 2,080 paid hours {money(e['total'] / 2080)}; salary alone {money(s / 2080)}/h")
    for s in (135980,):
        e = employer_cost(s)
        P(f"BLS median software developer {money(s)} -> {money(e['total'])} ({e['total'] / s:.3f}x), {money(e['total'] / 2080)}/h")


if __name__ == '__main__':
    main()
