"""Refresh the AI adoption tracker's data files from their public sources.

Usage: python3 -I refresh_adoption.py <out_dir> [--cache DIR]
  <out_dir> is this folder (src/data/adoption). With --cache, downloads are kept in DIR and reused if present.
Needs pandas and openpyxl (the Census files are Excel workbooks).

Sources
  Census Business Trends and Outlook Survey (BTOS), every two weeks:
    https://www.census.gov/hfp/btos/downloads/National.xlsx and Sector.xlsx
    Question 7: "In the last two weeks, did this business use [AI] in any of its business functions?"
    Question 28: the same, for the next six months.
  BLS Job Openings and Labor Turnover Survey (JOLTS), monthly, seasonally adjusted rates by industry.
  Microsoft AI Economy Institute, AI Diffusion Report: share of working-age people using AI, by economy.

Files written
  btos-ai-use-national.csv          every survey: share of businesses using AI, expecting to, and unsure
  btos-ai-use-by-sector.csv         every survey and sector, as published (blank where Census suppressed it)
  ai-use-national-plot.csv          chart file
  ai-use-by-sector-plot.csv         chart file: three-survey average for eight sectors
  jolts-by-sector.csv               monthly job openings and hires rates for the matched industries
  adoption-vs-jobs-by-sector.csv    one row per sector: AI use now and at the start, openings and hires now and a year ago
  microsoft-ai-diffusion-by-country.csv
"""
import io, json, pathlib, sys, urllib.request
import pandas as pd

OUT = pathlib.Path(sys.argv[1])
CACHE = pathlib.Path(sys.argv[sys.argv.index("--cache") + 1]) if "--cache" in sys.argv else None
BTOS = "https://www.census.gov/hfp/btos/downloads/"
BLS = "https://api.bls.gov/publicAPI/v2/timeseries/data/"
MSFT = "https://raw.githubusercontent.com/microsoft/ai-diffusion-report/main/data/AI_Diffusion_Q22026_Update.csv"
UA = {"User-Agent": "adoption-tracker-refresh"}

# BTOS sector code -> (name, JOLTS industry code or None, note on the JOLTS match)
SECTORS = {
    "23": ("Construction", "230000", ""),
    "31": ("Manufacturing", "300000", ""),
    "42": ("Wholesale trade", "420000", ""),
    "44": ("Retail trade", "440000", ""),
    "48": ("Transportation and warehousing", "480099", "JOLTS adds utilities"),
    "51": ("Information", "510000", ""),
    "52": ("Finance and insurance", "520000", ""),
    "53": ("Real estate and rental", "530000", ""),
    "54": ("Professional and technical services", "540099", "JOLTS adds management and administrative services"),
    "56": ("Administrative and support services", None, ""),
    "61": ("Educational services", "610000", "Private education only"),
    "62": ("Health care and social assistance", "620000", ""),
    "71": ("Arts, entertainment and recreation", "710000", ""),
    "72": ("Accommodation and food services", "720000", ""),
    "81": ("Other services", "810000", ""),
    "21": ("Mining", None, ""),
    "22": ("Utilities", None, ""),
}
PLOT = ["51", "54", "52", "62", "44", "23", "72"]          # sectors drawn on the chart
ALL = "All businesses"


def fetch(name, url, data=None):
    if CACHE and (CACHE / name).exists():
        return (CACHE / name).read_bytes()
    headers = dict(UA, **({"Content-Type": "application/json"} if data else {}))
    with urllib.request.urlopen(urllib.request.Request(url, data=data, headers=headers), timeout=120) as r:
        body = r.read()
    if CACHE:
        CACHE.mkdir(parents=True, exist_ok=True)
        (CACHE / name).write_bytes(body)
    return body


def pct(v):
    return float(v.strip().rstrip("%")) if isinstance(v, str) and v.strip().endswith("%") else None


def write(name, frame):
    frame.to_csv(OUT / name, index=False)
    print(f"{name}: {len(frame)} rows")


# ---- Census BTOS ----
nat_x = pd.ExcelFile(io.BytesIO(fetch("National.xlsx", BTOS + "National.xlsx")))
nat = pd.read_excel(nat_x, "Response Estimates")
dates = pd.read_excel(nat_x, "Collection and Reference Dates")
dates = dates[dates["Smpdt"].notna()]
dates["cycle"] = dates["Smpdt"].astype(int).astype(str)
start = dict(zip(dates["cycle"], pd.to_datetime(dates["Collection Start"]).dt.strftime("%Y-%m-%d")))
end = dict(zip(dates["cycle"], pd.to_datetime(dates["Col End"]).dt.strftime("%Y-%m-%d")))
cycles = sorted(c for c in nat.columns if str(c).isdigit())


def answer(frame, qid, ans):
    hit = frame[(frame["Question ID"] == qid) & (frame["Answer"] == ans)]
    return hit.iloc[0] if len(hit) else None


use, unsure, expect = answer(nat, 7, "Yes"), answer(nat, 7, "Do not know"), answer(nat, 28, "Yes")
national = pd.DataFrame([{
    "cycle": c, "collection_start": start.get(c, ""), "collection_end": end.get(c, ""),
    "ai_use_pct": pct(use[c]), "do_not_know_pct": pct(unsure[c]), "expect_ai_use_in_six_months_pct": pct(expect[c]),
} for c in cycles])
national = national[national["ai_use_pct"].notna()]
write("btos-ai-use-national.csv", national)
write("ai-use-national-plot.csv", national.rename(columns={"collection_end": "date", "ai_use_pct": ALL})[["date", ALL]])

sec = pd.read_excel(io.BytesIO(fetch("Sector.xlsx", BTOS + "Sector.xlsx")), "Response Estimates")
sec = sec[(sec["Question ID"] == 7) & (sec["Answer"] == "Yes")]
rows = []
for _, r in sec.iterrows():
    code = str(r["Sector"])
    if code not in SECTORS:
        continue
    for c in national["cycle"]:
        rows.append({"cycle": c, "collection_end": end.get(c, ""), "naics": code, "sector": SECTORS[code][0], "ai_use_pct": pct(r[c])})
by_sector = pd.DataFrame(rows)
write("btos-ai-use-by-sector.csv", by_sector)

wide = by_sector.pivot(index="collection_end", columns="naics", values="ai_use_pct").sort_index()
smooth = wide.rolling(3, min_periods=3).mean()
plot = smooth[PLOT].rename(columns={c: SECTORS[c][0] for c in PLOT})
plot.insert(0, ALL, national.set_index("collection_end")["ai_use_pct"].rolling(3, min_periods=3).mean())
plot = plot.dropna(how="all").round(1)
plot.insert(0, "date", plot.index)
write("ai-use-by-sector-plot.csv", plot)

# ---- BLS JOLTS ----
codes = {SECTORS[c][1]: c for c in SECTORS if SECTORS[c][1]}
ids = [f"JTS{j}000000000{m}" for j in list(codes) + ["000000"] for m in ("JOR", "HIR")]
this_year = int(national["collection_end"].iloc[-1][:4])
series = []
for i in range(0, len(ids), 25):
    body = json.dumps({"seriesid": ids[i:i + 25], "startyear": str(this_year - 2), "endyear": str(this_year)}).encode()
    series += json.loads(fetch(f"jolts{i // 25 + 1}.json", BLS, body))["Results"]["series"]
jrows = {}
for s in series:
    j, m = s["seriesID"][3:9], s["seriesID"][-3:]
    for d in s["data"]:
        if d["period"].startswith("M") and d["period"] != "M13":
            key = (f"{d['year']}-{d['period'][1:]}", j)
            jrows.setdefault(key, {})["openings_rate" if m == "JOR" else "hires_rate"] = float(d["value"])
jolts = pd.DataFrame([{"month": k[0], "naics": codes.get(k[1], ""), "sector": SECTORS[codes[k[1]]][0] if k[1] in codes else "Total nonfarm",
                       **v} for k, v in sorted(jrows.items())])
write("jolts-by-sector.csv", jolts)

# ---- AI use against job openings and hires, by sector ----
months = sorted(jolts["month"].unique())
now_m = months[-3:]
ago_m = [f"{int(m[:4]) - 1}{m[4:]}" for m in now_m]
first3, last3 = national["cycle"].tolist()[:3], national["cycle"].tolist()[-3:]
table = []
for code, (name, j, note) in SECTORS.items():
    if not j:
        continue
    s = by_sector[by_sector["naics"] == code].set_index("cycle")["ai_use_pct"]
    jj = jolts[jolts["naics"] == code].set_index("month")
    a0, a1 = s.reindex(first3).mean(), s.reindex(last3).mean()
    table.append({
        "naics": code, "sector": name,
        "ai_use_start_pct": round(a0, 1), "ai_use_now_pct": round(a1, 1), "ai_use_change_pts": round(a1 - a0, 1),
        "openings_rate_year_ago": round(jj["openings_rate"].reindex(ago_m).mean(), 2),
        "openings_rate_now": round(jj["openings_rate"].reindex(now_m).mean(), 2),
        "hires_rate_year_ago": round(jj["hires_rate"].reindex(ago_m).mean(), 2),
        "hires_rate_now": round(jj["hires_rate"].reindex(now_m).mean(), 2),
        "ai_use_start_period": f"{start[first3[0]]} to {end[first3[-1]]}", "ai_use_now_period": f"{start[last3[0]]} to {end[last3[-1]]}",
        "jolts_now_months": f"{now_m[0]} to {now_m[-1]}", "jolts_match_note": note,
    })
table = pd.DataFrame(table).sort_values("ai_use_now_pct", ascending=False)
table["openings_rate_change"] = (table["openings_rate_now"] - table["openings_rate_year_ago"]).round(2)
table["hires_rate_change"] = (table["hires_rate_now"] - table["hires_rate_year_ago"]).round(2)
write("adoption-vs-jobs-by-sector.csv", table)
for col in ("openings_rate_change", "hires_rate_change"):
    print(f"  correlation of AI use now with {col}: {table['ai_use_now_pct'].corr(table[col]):+.2f}"
          f"; of AI use change with {col}: {table['ai_use_change_pts'].corr(table[col]):+.2f}  (n = {len(table)})")

# ---- Microsoft AI diffusion by economy ----
raw = fetch("AI_Diffusion.csv", MSFT)
try:
    ms = pd.read_csv(io.BytesIO(raw))
except UnicodeDecodeError:                      # the file has shipped in Mac Roman
    ms = pd.read_csv(io.BytesIO(raw), encoding="mac_roman")
ms.columns = ["economy"] + [c.replace(" AI Diffusion", "").replace(" ", "_").lower() + "_pct" for c in ms.columns[1:]]
for c in ms.columns[1:]:
    ms[c] = ms[c].map(pct)
ms["change_pts"] = (ms.iloc[:, -1] - ms.iloc[:, 1]).round(1)
write("microsoft-ai-diffusion-by-country.csv", ms.sort_values(ms.columns[-2], ascending=False))
