#!/usr/bin/env python3
"""
ashe/extract.py

Builds src/data/ashePay.ts from the raw ONS ASHE Table 14 workbooks, so every
pay figure on the site is checkable rather than taken on trust. Published at
https://thecareery.com/ashe-extract.py.

Source
    ONS, "Earnings and hours worked, occupation by four-digit SOC: ASHE
    Table 14", 2026 provisional edition, released 22 October 2026.
    https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/occupation4digitsoc2010ashetable14

    Files read, both from the Full-Time sheet:
      Table 14.7a  Annual pay - Gross 2026        (the figures)
      Table 14.7b  Annual pay - Gross 2026 CV     (ONS's precision measure)

What this does and does not do
    Selects the thirteen SOC 2020 occupations Careery tracks in the labour
    demand data and copies the published median, mean and percentiles. It does
    not adjust, round, interpolate or recompute any figure. Where ONS publishes
    "x" (suppressed) or ".." the value is written as null, never filled in.

Usage
    python3 -I extract.py --figures "...14.7a...xlsx" --cv "...14.7b...xlsx" --out src/data/ashePay.ts
"""

import argparse
import json
import sys

import openpyxl

# The thirteen occupations in the labour demand data, then occupations the
# "courses for <degree> graduates" guides compare (src/pages/guides/majors).
SOCS = ["2134", "3544", "2122", "2121", "2421", "3571", "2422", "3556", "3554", "2431", "3543", "2142", "2133",
        "2112", "2113", "2152", "3111", "3115",
        "6135", "1136", "2434", "2226", "2225", "3224", "4159", "2432", "2483", "1254", "7111", "2141", "3421"]
# Column positions in the Full-Time sheet of ASHE Table 14 (0 based).
COLS = {"jobsThousands": 2, "median": 3, "mean": 5, "p10": 7, "p25": 9, "p75": 14}
EXPECTED_HEADER = {3: "Median", 5: "Mean", 7: "10", 9: "25", 14: "75"}


def num(v):
    if isinstance(v, (int, float)):
        return float(v)
    return None


def read(path):
    wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
    ws = wb["Full-Time"]
    rows = list(ws.iter_rows(values_only=True))
    header = next(r for r in rows if r and r[0] == "Description")
    for i, want in EXPECTED_HEADER.items():
        if str(header[i]).strip() != want:
            sys.exit(f"ASHE layout changed: column {i} is {header[i]!r}, expected {want!r}")
    out = {}
    for r in rows:
        code = str(r[1]).strip().lstrip("'") if r and r[1] is not None else ""
        if code in SOCS:
            out[code] = {"label": str(r[0]).strip(), **{k: num(r[c]) for k, c in COLS.items()}}
    missing = [s for s in SOCS if s not in out]
    if missing:
        sys.exit(f"ASHE rows missing for SOC {missing}")
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--figures", required=True)
    ap.add_argument("--cv", required=True)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    figs, cv = read(a.figures), read(a.cv)
    rows = []
    for s in SOCS:
        f, c = figs[s], cv[s]
        rows.append({
            "soc": s, "label": f["label"],
            "jobsThousands": f["jobsThousands"],
            "median": f["median"], "mean": f["mean"], "p10": f["p10"], "p25": f["p25"], "p75": f["p75"],
            "cv": {"median": c["median"], "p10": c["p10"], "p25": c["p25"], "p75": c["p75"]},
        })
    body = json.dumps(rows, indent=2)
    ts = f'''/**
 * GENERATED by scripts/ashe/extract.py. Do not edit by hand.
 *
 * Annual gross pay for full-time employees, by SOC 2020 occupation, from ONS
 * ASHE Table 14 (2026 provisional). All ages and experience levels together:
 * this is NOT a graduate or starting salary. Licence: Open Government Licence
 * v3.0. Any page showing a figure from this file must name the dataset and link
 * ASHE_DATASET_URL.
 */

export type AshePay = {{
  soc: string;
  /** ONS's own ASHE label. Do not paraphrase it on the page. */
  label: string;
  /** Number of jobs in the ASHE sample frame, thousands. */
  jobsThousands: number | null;
  median: number | null;
  mean: number | null;
  /** 10th percentile: one in ten full-time employees in the occupation earn less. */
  p10: number | null;
  /** 25th percentile, the lower quartile. */
  p25: number | null;
  /** 75th percentile, the upper quartile. */
  p75: number | null;
  /** ONS coefficient of variation for each estimate, in percent. */
  cv: {{ median: number | null; p10: number | null; p25: number | null; p75: number | null }};
}};

export const ASHE_DATASET = "Earnings and hours worked, occupation by four-digit SOC: ASHE Table 14";
export const ASHE_DATASET_URL = "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/datasets/occupation4digitsoc2010ashetable14";
export const ASHE_EDITION = "2026 provisional";
export const ASHE_RELEASED = "22 October 2026";
export const ASHE_TABLE = "Table 14.7a, Annual pay, gross, full-time";

export const ASHE_PAY: AshePay[] = {body};
'''
    with open(a.out, "w") as fh:
        fh.write(ts)
    print(f"wrote {len(rows)} occupations to {a.out}")


if __name__ == "__main__":
    main()
