"""Stream GH Archive hourly files and keep only the events of one day's new accounts.

GH Archive (https://www.gharchive.org/) publishes every public GitHub event as one gzipped
JSON file per hour. This script downloads one hour at a time, reads it with DuckDB, writes a
census row for the hour (events, distinct event ids, bot-login events, largest account id),
keeps the events of accounts whose id falls in the new-account band, and deletes the download.

GitHub account ids are issued in order, so the band (T1, T2] is: above the largest id seen on
the day before the cohort day, and at most the largest id seen on the cohort day.

Usage:
  python3 -B tools/extract.py <work dir> [--workers 2]

Each hour leaves <work dir>/hours/<hour>.census.json and, after the cohort day, an
<hour>.parquet; a finished hour is skipped on a re-run.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor

import duckdb

HERE = os.path.dirname(os.path.abspath(__file__))
PROTOCOL = json.load(open(os.path.join(HERE, "..", "protocol-r1.json"), encoding="utf-8"))
URL = "https://data.gharchive.org/{h}.json.gz"

COLUMNS = ("{'id':'VARCHAR','type':'VARCHAR','actor':'STRUCT(id BIGINT, login VARCHAR)',"
           "'repo':'STRUCT(id BIGINT, name VARCHAR)','payload':'JSON','created_at':'TIMESTAMP'}")


def hours_for(day: str) -> list[str]:
    d = dt.date.fromisoformat(day)
    return [f"{d.isoformat()}-{h}" for h in range(24)]


def days(cohort_day: str | None = None) -> dict[str, list[str]]:
    p = PROTOCOL["data"]
    d0 = dt.date.fromisoformat(cohort_day or p["cohort_day"])
    span = lambda a, b: [(d0 + dt.timedelta(days=i)).isoformat() for i in range(a, b + 1)]
    return {"threshold": span(-1, -1), "cohort": span(0, 0),
            "week1": span(1, p["first_window_days"] - 1),
            "later": span(p["retention_window"][0], p["retention_window"][1])}


def process_hour(h: str, work: str, band: tuple[int, int] | None) -> dict:
    hd = os.path.join(work, "hours")
    census_p = os.path.join(hd, f"{h}.census.json")
    if os.path.exists(census_p) and os.path.getsize(census_p) > 0:
        return json.load(open(census_p))
    gz = os.path.join(work, "dl", f"{h}.json.gz")
    r = subprocess.run(["curl", "-fsSL", "--retry", "3", "-o", gz, URL.format(h=h)],
                       capture_output=True, text=True)
    if r.returncode != 0:
        census = {"hour": h, "missing": True, "curl_exit": r.returncode}
    else:
        con = duckdb.connect()
        con.execute("set threads=1; set memory_limit='500MB'; set preserve_insertion_order=false")
        src = (f"read_json('{gz}', format='newline_delimited', compression='gzip', "
               f"columns={COLUMNS})")
        row = con.execute(
            f"select count(*), count(distinct id), count(*) filter (where actor.login like '%[bot]'),"
            f" max(actor.id), min(created_at)::varchar, max(created_at)::varchar from {src}").fetchone()
        census = {"hour": h, "missing": False, "events": row[0], "distinct_ids": row[1],
                  "bot_login_events": row[2], "max_actor_id": row[3], "min_ts": row[4],
                  "max_ts": row[5], "bytes": os.path.getsize(gz)}
        if band is not None:
            out = os.path.join(hd, f"{h}.parquet")
            con.execute(
                f"copy (select id as event_id, type as event_type, actor.id as actor_id,"
                f" actor.login as actor_login, repo.id as repo_id, repo.name as repo_name,"
                f" created_at, payload->>'action' as action,"
                f" (payload->'pull_request'->>'merged')::boolean as pr_merged,"
                f" payload->>'ref_type' as ref_type, '{h}' as source_hour"
                f" from {src} where actor.id > {band[0]} and actor.id <= {band[1]})"
                f" to '{out}.tmp' (format parquet)")
            os.replace(out + ".tmp", out)
            census["band_events"] = con.execute(
                f"select count(*) from read_parquet('{out}')").fetchone()[0]
        con.close()
    if os.path.exists(gz):
        os.remove(gz)
    tmp = census_p + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(census, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, census_p)
    return census


def run(work: str, workers: int, cohort_day: str | None = None) -> None:
    os.makedirs(os.path.join(work, "hours"), exist_ok=True)
    os.makedirs(os.path.join(work, "dl"), exist_ok=True)
    plan = days(cohort_day)
    band_p = os.path.join(work, "band.json")

    def stage(day_list, band):
        hs = [h for d in day_list for h in hours_for(d)]
        with ThreadPoolExecutor(workers) as ex:
            res = list(ex.map(lambda h: process_hour(h, work, band), hs))
        done = sum(1 for c in res if not c.get("missing"))
        print(f"stage {day_list[0]}..{day_list[-1]}: {done}/{len(hs)} hours read", flush=True)
        return res

    thr = stage(plan["threshold"], None)
    t1 = max(c["max_actor_id"] for c in thr if not c.get("missing"))
    # cohort day: keep everything above t1 (the upper bound is set by this day itself)
    coh = stage(plan["cohort"], (t1, 2**62))
    t2 = max(c["max_actor_id"] for c in coh if not c.get("missing"))
    json.dump({"t1": t1, "t2": t2}, open(band_p, "w"))
    stage(plan["week1"] + plan["later"], (t1, t2))
    print("VERDICT extract: done", json.dumps({"t1": t1, "t2": t2}))


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("work")
    ap.add_argument("--workers", type=int, default=2)
    ap.add_argument("--cohort-day", default=None, help="the declared follow-up day")
    a = ap.parse_args()
    run(os.path.abspath(a.work), a.workers, a.cohort_day)
