"""
Tabulates employed health workers in the United States by country of birth
from the 2024 American Community Survey (ACS) 1-year Public Use Microdata
Sample (PUMS), national person file.

Input : csv_pus.zip from
        https://www2.census.gov/programs-surveys/acs/data/pums/2024/1-Year/csv_pus.zip
Usage : python3 acs_pums_tabulation.py csv_pus.zip > acs_pums_2024_results.json

Definitions (2024 PUMS data dictionary):
  Universe   ESR in {1,2,4,5}  -> employed (civilian at work / with a job but
                                  not at work; armed forces at work / with a
                                  job but not at work)
  POBP       place of birth: 324 Barbados, 329 Dominican Republic, 332 Haiti,
             333 Jamaica, 341 Trinidad and Tobago, 368 Guyana
  OCCP       3255 Registered nurses, 3256 Nurse anesthetists,
             3258 Nurse practitioners and nurse midwives  -> "rn"
             3500 Licensed practical / vocational nurses   -> "lpn"
             3090 Physicians, 3100 Surgeons                -> "phys"
  Weights    PWGTP (person weight); standard errors from the 80 successive
             difference replicate weights PWGTP1-PWGTP80:
             SE = sqrt(4/80 * sum((rep_i - est)^2)); MOE90 = 1.645 * SE

Country of birth is not the same as country of training: a person born in
Jamaica may have trained in the United States, and vice versa.
"""
import csv, io, json, math, sys, zipfile

POB = {324: "Barbados", 329: "Dominican Republic", 332: "Haiti",
       333: "Jamaica", 341: "Trinidad and Tobago", 368: "Guyana"}
OCC = {"rn": {3255, 3256, 3258}, "lpn": {3500}, "phys": {3090, 3100}}
EMPLOYED = {"1", "2", "4", "5"}
GROUPS = list(POB.values()) + ["SIX_COUNTRIES", "ALL_FOREIGN_BORN", "ALL_US"]


def main(path):
    acc = {g: {m: [0.0] * 81 for m in ("emp", "rn", "lpn", "phys")} for g in GROUPS}
    with zipfile.ZipFile(path) as zf:
        for name in ("psam_pusa.csv", "psam_pusb.csv"):
            with zf.open(name) as fh:
                rows = csv.reader(io.TextIOWrapper(fh, encoding="latin-1"))
                header = next(rows)
                ix = {c: i for i, c in enumerate(header)}
                w_cols = [ix["PWGTP"]] + [ix[f"PWGTP{i}"] for i in range(1, 81)]
                for row in rows:
                    if row[ix["ESR"]] not in EMPLOYED:
                        continue
                    groups = ["ALL_US"]
                    if row[ix["NATIVITY"]] == "2":
                        groups.append("ALL_FOREIGN_BORN")
                    pob = int(row[ix["POBP"]]) if row[ix["POBP"]].strip() else -1
                    if pob in POB:
                        groups += [POB[pob], "SIX_COUNTRIES"]
                    occ = int(row[ix["OCCP"]]) if row[ix["OCCP"]].strip() else -1
                    measures = ["emp"] + [m for m, codes in OCC.items() if occ in codes]
                    w = [float(row[i]) for i in w_cols]
                    for g in groups:
                        for m in measures:
                            a = acc[g][m]
                            for i in range(81):
                                a[i] += w[i]
    out = {}
    for g in GROUPS:
        out[g] = {}
        for m, a in acc[g].items():
            est = a[0]
            se = math.sqrt(4 / 80 * sum((a[i] - est) ** 2 for i in range(1, 81)))
            out[g][m] = {"est": round(est), "moe90": round(1.645 * se)}
    json.dump(out, sys.stdout, indent=1)


if __name__ == "__main__":
    main(sys.argv[1])
