"""Build occupation-group AI exposure for the 43 LFS PUMF `noc_43` groups.

Usage: python3 -P build_exposure.py <root>

Chain (all inputs public, under data/raw/):
  SOC 2018 (6-digit) score
    -> NOC 2016 V1.3 unit group   (StatCan definitional correspondence NOC 2016 V1.3 - SOC 2018)
    -> NOC 2021 V1.0 unit group   (StatCan correspondence NOC 2016 V1.3 - NOC 2021 V1.0)
    -> noc_43 group               (NOC 2021 V1.0 labour force variant; title match of the 43 PUMF labels, then parents)

Weights (primary, "emp"):
  SOC inside NOC 2016: BLS OEWS May 2024 national employment, each SOC's employment split equally across the
    NOC 2016 codes it maps to (a SOC that maps to 3 NOC codes gives a third of its employment to each).
  NOC 2016 inside NOC 2021: simple mean over the NOC 2016 source codes (no public split shares).
  NOC 2021 inside noc_43: 2021 Census employed persons by NOC 2021 unit group (table 98-10-0449-01).
Equal-weight variant ("eq"): simple means at every step.
Anchor replication ("anchor"): the feasibility probe's union-of-SOC equal mean, kept only as a code check.

Scores pushed through the same chain:
  observed      Anthropic observed_exposure (labor_market_impacts/job_exposure.csv)
  observed_can  observed_exposure x r_s, r_s = Canada / global share of Claude.ai usage for SOC s
                (Economic Index release 2026-06-26, April and May 2026 averaged), r_s capped to [0.5, 2],
                r_s = 1 where the Canada cell is not published
  beta_human    Eloundou et al. occupation beta, human ratings (mean over O*NET-SOC sub-codes of a SOC)
  beta_gpt4     Eloundou et al. occupation beta, GPT-4 ratings

Outputs: data/derived/exposure_noc21_unit.csv, data/derived/exposure_noc43.csv,
results/phase1/exposure_build.json. Prints counts and the group ranking only.
"""
import csv
import io
import json
import os
import re
import sys
import zipfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lfs_io  # noqa: E402

R_CAP = (0.5, 2.0)


def norm(s):
    return " ".join(s.lower().replace(",", " ").split())


def read_soc_scores(root):
    jx = os.path.join(lfs_io.raw_dir(root, "hf-aei-lmi"), "job_exposure.csv")
    observed = {r["occ_code"].strip(): float(r["observed_exposure"]) for r in csv.DictReader(open(jx, encoding="utf-8"))}
    el = os.path.join(lfs_io.raw_dir(root, "gpts-are-gpts"), "occ_level.csv")
    acc = {}
    for r in csv.DictReader(open(el, encoding="utf-8")):
        s = r["O*NET-SOC Code"].strip()[:7]
        a = acc.setdefault(s, [[], []])
        a[0].append(float(r["human_rating_beta"]))
        a[1].append(float(r["dv_rating_beta"]))
    beta_human = {s: sum(v[0]) / len(v[0]) for s, v in acc.items()}
    beta_gpt4 = {s: sum(v[1]) / len(v[1]) for s, v in acc.items()}
    # Canada usage tilt from the Economic Index June 2026 release (filtered extract copied from the anchor)
    ce = os.path.join(lfs_io.raw_dir(root, "hf-aei-canada"), "aei_claude_ai_2026-06-26_canada_and_global_soc.csv")
    monthly = {}
    for r in csv.DictReader(open(ce, newline="", encoding="utf-8")):
        if r["category_name"] == "soc_occupation" and r["hierarchy_level"] == "0" and r["metric_id"] == "pct" \
                and r["geo_id"] in ("CAN", "GLOBAL"):
            # node ids are 8-digit O*NET-SOC codes (13-1041.00): sum sub-codes to the 6-digit SOC within a month
            key = (r["geo_id"], r["node_external_id"].strip()[:7], r["date_start"])
            monthly[key] = monthly.get(key, 0.0) + float(r["value"])
    shares = {}
    for (geo, soc, _month), v in monthly.items():
        shares.setdefault((geo, soc), []).append(v)
    ratio, n_pub = {}, 0
    for s in observed:
        c, g = shares.get(("CAN", s)), shares.get(("GLOBAL", s))
        if c and g and sum(g) > 0:
            # average over the months published for each geography
            rr = (sum(c) / len(c)) / (sum(g) / len(g))
            ratio[s] = min(max(rr, R_CAP[0]), R_CAP[1])
            n_pub += 1
        else:
            ratio[s] = 1.0
    observed_can = {s: observed[s] * ratio[s] for s in observed}
    scores = {"observed": observed, "observed_can": observed_can, "beta_human": beta_human, "beta_gpt4": beta_gpt4}
    info = {"n_soc_observed": len(observed), "n_soc_zero": sum(1 for v in observed.values() if v == 0),
            "n_onet_rows_beta": sum(len(v[0]) for v in acc.values()),
            "n_soc_can_ratio_published": n_pub,
            "n_soc_ratio_capped": sum(1 for s in observed if ratio[s] in R_CAP and n_pub),
            "n_soc_beta": len(beta_human), "observed_soc_in_beta": len(set(observed) & set(beta_human))}
    return scores, info


def read_oews(root):
    import openpyxl  # user site; run with python3 -P
    zp = os.path.join(lfs_io.raw_dir(root, "bls-oews-2024"), "oesm24nat.zip")
    z = zipfile.ZipFile(zp)
    name = [n for n in z.namelist() if n.endswith(".xlsx")][0]
    wb = openpyxl.load_workbook(io.BytesIO(z.read(name)), read_only=True)
    ws = wb[wb.sheetnames[0]]
    rows = ws.iter_rows(values_only=True)
    hdr = [str(h) for h in next(rows)]
    ix = {h: i for i, h in enumerate(hdr)}
    detailed, broad = {}, {}
    for r in rows:
        g, code, emp = r[ix["O_GROUP"]], str(r[ix["OCC_CODE"]]).strip(), r[ix["TOT_EMP"]]
        if not isinstance(emp, (int, float)):
            continue
        if g == "detailed":
            detailed[code] = float(emp)
        elif g == "broad":
            broad[code] = float(emp)
    return detailed, broad


def soc_employment(observed, detailed, broad):
    """OEWS employment for each scored SOC; SOCs missing at detailed level share their broad group's residual."""
    emp, how = {}, {}
    for s in observed:
        if s in detailed:
            emp[s], how[s] = detailed[s], "detailed"
    missing = [s for s in observed if s not in emp]
    by_broad = {}
    for s in missing:
        by_broad.setdefault(s[:6] + "0", []).append(s)
    for b, ss in by_broad.items():
        if b in broad:
            listed = sum(v for k, v in detailed.items() if k[:6] == b[:6])
            resid = broad[b] - listed
            total = resid if resid > 0 else broad[b]
            for s in ss:
                emp[s], how[s] = total / len(ss), "broad_residual" if resid > 0 else "broad_split"
        else:
            for s in ss:
                emp[s], how[s] = None, "none"
    return emp, how


def read_crosswalks(root):
    cw = lfs_io.raw_dir(root, "statcan-noc-crosswalks")
    n16_soc = {}
    with open(os.path.join(cw, "noc2016v1_3-soc2018us-eng.csv"), encoding="latin-1") as f:
        rd = csv.reader(f)
        next(rd)
        for r in rd:
            if len(r) >= 4 and r[0].strip() and r[3].strip():
                n16_soc.setdefault(r[0].strip(), set()).add(r[3].strip())
    n16_n21 = {}
    with open(os.path.join(cw, "noc2016v1_3-noc2021v1_0-eng.csv"), encoding="utf-8-sig") as f:
        rd = csv.reader(f)
        next(rd)
        for r in rd:
            if len(r) >= 4 and r[0].strip() and r[3].strip():
                n16_n21.setdefault(r[0].strip(), set()).add(r[3].strip())
    var = list(csv.DictReader(open(os.path.join(cw, "noc-2021-v1.0-variant-aggregates-analysis-labour-force.csv"),
                                   encoding="utf-8-sig")))
    return n16_soc, n16_n21, var


def unit_to_group(root, var):
    cb_path = os.path.join(lfs_io.raw_dir(root, "statcan-lfs-2026-09"), "extracted", "LFS_PUMF_EPA_FGMD_codebook.csv")
    labels = lfs_io.parse_codebook(open(cb_path, "rb").read())["noc_43"]["codes"]
    labels = {k: v for k, v in labels.items() if k.isdigit()}
    parent = {r["Code"].strip(): r["Parent "].strip() for r in var}
    level = {r["Code"].strip(): r["Level/Niveau"].strip() for r in var}
    by_title = {}
    for r in var:
        by_title.setdefault(norm(r["Class title"]), []).append(r["Code"].strip())
    node_to_g, unmatched = {}, []
    for g, lab in labels.items():
        hits = [c for c in by_title.get(norm(lab), []) if level[c] in ("2", "3", "4")]
        if hits:
            node_to_g[hits[0]] = g
        else:
            unmatched.append(g)
    u2g = {}
    for c, lv in level.items():
        if lv != "6":
            continue
        x = c
        while x and x not in node_to_g:
            x = parent.get(x)
        if x:
            u2g[c] = node_to_g[x]
    return labels, u2g, unmatched


def wmean(pairs):
    num = sum(w * x for x, w in pairs)
    den = sum(w for _, w in pairs)
    return num / den if den > 0 else None


def main():
    root = sys.argv[1]
    scores, info = read_soc_scores(root)
    observed = scores["observed"]
    detailed, broad = read_oews(root)
    emp, how = soc_employment(observed, detailed, broad)
    n16_soc, n16_n21, var = read_crosswalks(root)
    labels, u2g, unmatched = unit_to_group(root, var)
    census = {}
    cpath = os.path.join(lfs_io.raw_dir(root, "statcan-census2021-98100449"), "noc2021_unit_employed_2021.csv")
    for r in csv.DictReader(open(cpath, encoding="utf-8")):
        census[r["noc21"]] = float(r["employed_2021"])
    # The 2021 Census table publishes senior managers 00011 to 00015 only as one combined code, 00018
    # ("Senior managers - public and private sector"). Spread 00018 equally over the five variant units.
    census_note = None
    combined = [u for u in ("00011", "00012", "00013", "00014", "00015") if u in u2g and u not in census]
    if "00018" in census and combined:
        share = census.pop("00018") / len(combined)
        for u in combined:
            census[u] = share
        census_note = f"00018 spread equally over {combined}"

    k_links = {}
    for n, ss in n16_soc.items():
        for s in ss:
            k_links[s] = k_links.get(s, 0) + 1

    def n16_score(score, n, mode):
        pairs = []
        for s in n16_soc.get(n, ()):
            if s in score and s in observed:  # restrict to the 756 scored SOCs for every measure
                w = 1.0 if mode == "eq" else (emp.get(s) or 0.0) / k_links[s]
                pairs.append((score[s], w))
        if not pairs:
            return None
        v = wmean(pairs)
        return v if v is not None else sum(x for x, _ in pairs) / len(pairs)

    n21_sources = {}
    for n, us in n16_n21.items():
        for u in us:
            n21_sources.setdefault(u, set()).add(n)

    units = sorted(u2g)
    unit_rows, unit_vals = [], {}
    for u in units:
        row = {"noc21": u, "noc43": u2g[u], "census_employed_2021": census.get(u, ""),
               "n_noc16_sources": len(n21_sources.get(u, ()))}
        for name, score in scores.items():
            for mode in ("emp", "eq"):
                vals = [n16_score(score, n, mode) for n in sorted(n21_sources.get(u, ()))]
                vals = [v for v in vals if v is not None]
                val = sum(vals) / len(vals) if vals else None
                row[f"{name}_{mode}"] = "" if val is None else round(val, 6)
                unit_vals[(u, name, mode)] = val
        # anchor replication: union of SOCs over all NOC 2016 sources, equal weights, observed only
        socs = set()
        for n in n21_sources.get(u, ()):
            socs |= n16_soc.get(n, set())
        vs = [observed[s] for s in socs if s in observed]
        unit_vals[(u, "observed", "anchor")] = sum(vs) / len(vs) if vs else None
        row["observed_anchor"] = "" if not vs else round(sum(vs) / len(vs), 6)
        unit_rows.append(row)

    groups = sorted(labels, key=int)
    grp_rows = []
    for g in groups:
        us = [u for u in units if u2g[u] == g]
        row = {"noc43": g, "label": labels[g], "n_units": len(us),
               "n_units_scored": sum(1 for u in us if unit_vals[(u, "observed", "emp")] is not None),
               "census_employed_2021": sum(census.get(u, 0.0) for u in us)}
        cov = sum(census.get(u, 0.0) for u in us if unit_vals[(u, "observed", "emp")] is not None)
        row["census_share_scored"] = round(cov / row["census_employed_2021"], 4) if row["census_employed_2021"] else ""
        for name in scores:
            for mode in ("emp", "eq"):
                if mode == "emp":
                    pairs = [(unit_vals[(u, name, mode)], census.get(u, 0.0)) for u in us
                             if unit_vals[(u, name, mode)] is not None]
                    v = wmean(pairs)
                else:
                    vs = [unit_vals[(u, name, mode)] for u in us if unit_vals[(u, name, mode)] is not None]
                    v = sum(vs) / len(vs) if vs else None
                row[f"{name}_{mode}"] = "" if v is None else round(v, 6)
        vs = [unit_vals[(u, "observed", "anchor")] for u in us if unit_vals[(u, "observed", "anchor")] is not None]
        row["observed_anchor"] = "" if not vs else round(sum(vs) / len(vs), 6)
        grp_rows.append(row)

    ddir = os.path.join(root, "data", "derived")
    os.makedirs(ddir, exist_ok=True)
    for path, rows in ((os.path.join(ddir, "exposure_noc21_unit.csv"), unit_rows),
                       (os.path.join(ddir, "exposure_noc43.csv"), grp_rows)):
        with open(path + ".part", "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=list(rows[0]))
            w.writeheader()
            w.writerows(rows)
        os.replace(path + ".part", path)

    how_counts = {}
    for s in observed:
        how_counts[how[s]] = how_counts.get(how[s], 0) + 1
    census_units_not_in_variant = sorted(set(census) - set(units))
    variant_units_not_in_census = sorted(set(units) - set(census))
    report = {
        "soc_scores": info,
        "oews": {"n_detailed": len(detailed), "n_broad": len(broad), "scored_soc_employment_source": how_counts,
                 "scored_soc_oews_employment_total": sum(v for v in emp.values() if v)},
        "crosswalk": {"n_noc16_in_soc_table": len(n16_soc), "n_noc16_in_noc21_table": len(n16_n21),
                      "n_soc_in_soc_table": len(k_links),
                      "scored_soc_in_soc_table": len(set(observed) & set(k_links)),
                      "soc_links_per_soc_max": max(k_links.values()),
                      "n_noc21_units_in_variant": len(units), "n_noc21_units_scored": sum(
                          1 for u in units if unit_vals[(u, "observed", "emp")] is not None),
                      "unscored_units": [u for u in units if unit_vals[(u, "observed", "emp")] is None],
                      "noc43_labels": len(labels), "noc43_unmatched_titles": unmatched,
                      "census_units": len(census), "census_units_not_in_variant": census_units_not_in_variant,
                      "variant_units_not_in_census": variant_units_not_in_census,
                      "census_special_case": census_note},
    }
    rdir = os.path.join(root, "results", "phase1")
    os.makedirs(rdir, exist_ok=True)
    with open(os.path.join(rdir, "exposure_build.json"), "w", encoding="utf-8") as f:
        json.dump(report, f, indent=1)
    print(json.dumps(report, indent=1)[:3000])
    print("group ranking (observed_emp | observed_eq | anchor | observed_can_emp | beta_human_emp):")
    for r in sorted(grp_rows, key=lambda r: -(r["observed_emp"] or 0)):
        print(f"  {r['noc43']:>2} {r['observed_emp']:.3f} {r['observed_eq']:.3f} {r['observed_anchor']:.3f} "
              f"{r['observed_can_emp']:.3f} {r['beta_human_emp']:.3f} units={r['n_units_scored']}/{r['n_units']} "
              f"{r['label'][:48]}")


if __name__ == "__main__":
    main()
