"""Download the Open University Learning Analytics Dataset (CC BY 4.0) and build one row per enrolment.

The zip is checked against the sha256 in protocol-r1.json. Activity is read from studentVle as a stream (10.6 million
rows), keeping only what a rule could know on day 14: active days and clicks on days 0 to 13, the last active day before
day 14, and active days before the start. Demographic fields are never written out.

Usage: python3 -I -B tools/get_data.py [--cache DIR] [--out data/enrolments.csv.gz]
Default cache: ~/.cache/trial-to-paid-retention/
"""
import argparse
import csv
import gzip
import hashlib
import io
import json
import os
import urllib.request
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PROTOCOL = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
FIELDS = ["code_module", "code_presentation", "id_student", "date_registration", "date_unregistration",
          "final_result", "studied_credits", "prev_attempts", "days_active_14", "clicks_14", "last_active_14",
          "days_active_pre", "clicks_pre", "module_length", "first_due_day"]


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def fetch(cache):
    cache.mkdir(parents=True, exist_ok=True)
    path = cache / "oulad.zip"
    if not path.exists():
        tmp = cache / "oulad.zip.part"
        with urllib.request.urlopen(PROTOCOL["data"]["zip_url"], timeout=300) as r, open(tmp, "wb") as f:
            while True:
                block = r.read(1 << 20)
                if not block:
                    break
                f.write(block)
        os.replace(tmp, path)
    got = sha256(path)
    assert got == PROTOCOL["data"]["zip_sha256"], f"zip sha256 {got} does not match the protocol"
    return path


def table(z, name):
    with z.open(f"{name}.csv") as raw:
        yield from csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8", newline=""))


def num(v):
    v = (v or "").strip()
    return None if v in ("", PROTOCOL["data"]["missing_value_token"]) else int(float(v))


def build(zip_path, out):
    z = zipfile.ZipFile(zip_path)
    length = {(r["code_module"], r["code_presentation"]): int(r["module_presentation_length"]) for r in table(z, "courses")}
    first_due = {}
    for r in table(z, "assessments"):
        if r["assessment_type"] == "Exam" or num(r["date"]) is None:
            continue
        k = (r["code_module"], r["code_presentation"])
        first_due[k] = min(first_due.get(k, 10 ** 6), num(r["date"]))
    info = {}
    for r in table(z, "studentInfo"):
        info[(r["code_module"], r["code_presentation"], r["id_student"])] = (
            r["final_result"], num(r["studied_credits"]), num(r["num_of_prev_attempts"]))
    act = {}
    rows = 0
    for r in table(z, "studentVle"):
        rows += 1
        d = int(r["date"])
        if d > 13:
            continue
        k = (r["code_module"], r["code_presentation"], r["id_student"])
        a = act.get(k)
        if a is None:
            a = act[k] = [set(), 0, -10 ** 6, set(), 0]
        c = int(r["sum_click"])
        if d >= 0:
            a[0].add(d)
            a[1] += c
            a[2] = max(a[2], d)
        else:
            a[3].add(d)
            a[4] += c
    out.parent.mkdir(parents=True, exist_ok=True)
    tmp = out.with_suffix(".part")
    n = 0
    with open(tmp, "wb") as raw, gzip.GzipFile(filename="", fileobj=raw, mode="wb", mtime=0) as gz, \
            io.TextIOWrapper(gz, encoding="utf-8", newline="") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(FIELDS)
        for r in table(z, "studentRegistration"):
            k = (r["code_module"], r["code_presentation"], r["id_student"])
            final, credits, prev = info[k]
            a = act.get(k, [set(), 0, None, set(), 0])
            last = a[2] if a[2] is not None and a[2] >= 0 else ""
            mp = k[:2]
            w.writerow([k[0], k[1], k[2], "" if num(r["date_registration"]) is None else num(r["date_registration"]),
                        "" if num(r["date_unregistration"]) is None else num(r["date_unregistration"]),
                        final, credits, prev, len(a[0]), a[1], last, len(a[3]), a[4], length[mp], first_due[mp]])
            n += 1
    os.replace(tmp, out)
    return {"enrolments": n, "activity_rows_read": rows, "enrolments_with_activity_by_day_13": len(act)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--cache", default=str(Path.home() / ".cache" / "trial-to-paid-retention"))
    ap.add_argument("--out", default=str(ROOT / "data" / "enrolments.csv.gz"))
    a = ap.parse_args()
    stats = build(fetch(Path(a.cache)), Path(a.out))
    print(json.dumps(stats))


if __name__ == "__main__":
    main()
