#!/usr/bin/env python3
"""Roles that mention React, with every US dollar pay range they print.

A role (roles.json, see roles.py) mentions React if the title or text of any of
its postings matches REACT: "React", "React.js", "ReactJS", "React JS", but not
"React Native" alone. The sentences that mention it are kept for labeling
(labeling-instructions.md decides whether React is part of the job).

Pay ranges, in US dollars, from two places:
  field  the board's own pay field (pay-fields.json): Greenhouse pay_input_ranges,
         Ashby compensation (Salary components only), Lever salaryRange
  text   ranges of two annual amounts in the posting text, found with the
         US dollar detector of ../salary-questions/analyze.py
Every range of every posting of the role is kept, with its label (a location
tier, as a rule), so the counting rule can be stated and checked.

Writes react-roles.json here and OUT_DIR/react-sentences.jsonl.
Usage: python3 react-roles.py OUT_DIR
"""
import json
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
OUT = Path(sys.argv[1])
sys.path.insert(0, str(HERE.parent / 'salary-questions'))
sys.path.insert(1, str(HERE.parent / 'engineering-by-country'))
_argv, sys.argv = sys.argv, [sys.argv[0], str(OUT)]
import importlib.util  # noqa: E402
_spec = importlib.util.spec_from_file_location('sq_analyze', HERE.parent / 'salary-questions' / 'analyze.py')
sq = importlib.util.module_from_spec(_spec)   # only its regexes and helpers; main() is not run
_spec.loader.exec_module(sq)
from states import states  # noqa: E402
sys.argv = _argv

REACT = re.compile(r'\bReact(?:\.?\s?js|JS)?\b(?![\s-]?Native)', re.I)
CASED = re.compile(r'\bReact')            # "react to incidents" is a verb, not the library
SENT = re.compile(r'(?<=[.!?;])\s+|\n+|\s•\s|\s\*\s')


def mentions(text):
    return [m for m in REACT.finditer(text) if CASED.match(text, m.start())]


def sentences(text):
    out = []
    for s in SENT.split(text):
        s = re.sub(r'\s+', ' ', s).strip()
        if s and mentions(s):
            out.append(s[:600])
    return out


def text_ranges(text):
    text = sq.clean(text)
    found = []
    for m in sq.ANNUAL.finditer(text):
        lo, hi = sq.money(m.group('lo')), sq.money(m.group('hi'))
        if not 20000 <= lo <= hi <= 5000000:
            continue
        near = text[max(0, m.start() - 120):m.end() + 12]
        if sq.FOREIGN.search(text[max(0, m.start() - 80):m.end() + 8]):
            continue
        if not ('$' in m.group(0) or 'USD' in m.group(0)) and not sq.PAYWORD.search(near):
            continue
        if re.search(r'(?i)raised|valuation|funding|invest|revenue|customers|billion|million', near[:120]):
            continue
        found.append({'low': lo, 'high': hi, 'words': re.sub(r'\s+', ' ', m.group(0)).strip(),
                      'context': re.sub(r'\s+', ' ', text[max(0, m.start() - 160):m.start()]).strip()[-160:]})
    return found


def main():
    roles = json.load(open(HERE / 'roles.json'))
    comp = json.load(open(HERE / 'companies.json'))
    fields = json.load(open(HERE / 'pay-fields.json'))
    eng = {r['id']: r for r in map(json.loads, open(OUT / 'eng.jsonl'))}
    rows, sent_out = [], open(OUT / 'react-sentences.jsonl', 'w')
    for r in roles:
        ps = r['posting_ids']
        sents, title_hit = [], False
        for p in ps:
            e = eng[p]
            title_hit |= bool(mentions(e['title']))
            for s in sentences(e['text']):
                if s not in sents:
                    sents.append(s)
        if not sents and not title_hit:
            continue
        field_r, text_r = [], []
        for p in ps:
            for x in fields[p]['ranges']:
                if sq.usd_field(x) and x.get('low') and x.get('high'):
                    field_r.append({'posting': p, 'low': float(x['low']), 'high': float(x['high']),
                                    'period': x.get('period'), 'label': x.get('label') or ''})
            for x in text_ranges(eng[p]['text']):
                text_r.append({'posting': p, **x})
        st = set()
        for p in ps:
            st |= states(eng[p]['location'])
            for s in eng[p]['more_locations']:
                st |= states(s)
        row = {'id': r['id'], 'company': r['company'], 'company_name': comp[r['company']].get('company', r['company']),
               'hq': comp[r['company']]['hq'], 'title': r['title'], 'url': r['url'], 'published': r['published'],
               'api': eng[ps[0]]['api'], 'postings': len(ps), 'seniority': r['seniority'], 'mode': r['mode'],
               'countries': r['countries'], 'places': r['places'], 'us_states': sorted(st),
               'react_in_title': title_hit, 'react_sentences': len(sents),
               'field_ranges': field_r, 'text_ranges': text_r}
        rows.append(row)
        sent_out.write(json.dumps({'id': r['id'], 'title': r['title'], 'sentences': sents}, ensure_ascii=False) + '\n')
    json.dump(rows, open(HERE / 'react-roles.json', 'w'), ensure_ascii=False, indent=0)
    us = [x for x in rows if 'United States' in x['countries'] and x['hq'] == 'United States']
    print({'roles_mentioning_react': len(rows), 'us_roles_us_companies': len(us),
           'with_field_usd': sum(bool(x['field_ranges']) for x in us),
           'with_text_usd': sum(bool(x['text_ranges']) for x in us),
           'with_any_usd': sum(bool(x['field_ranges'] or x['text_ranges']) for x in us),
           'companies_us': len({x['company'] for x in us})})


if __name__ == '__main__':
    main()
