"""Per enrolment, the first marked assignment of its course run and whether it was handed in by its due day.

The first assignment is the non-exam assessment with the earliest due day (no course run has two on that day).
A result carried over from an earlier attempt (is_banked = 1) counts as a submission. Reads the same checked zip as
tools/get_data.py.

Usage: python3 -I -B tools/get_first_assessment.py [--cache DIR] [--out data/first-assessment.csv.gz]
"""
import argparse
import csv
import gzip
import io
import json
import os
import sys
import zipfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from get_data import fetch, num, table  # noqa: E402

ROOT = Path(__file__).resolve().parent.parent


def build(zip_path, out):
    z = zipfile.ZipFile(zip_path)
    first = {}
    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"])
        cand = (num(r["date"]), int(r["id_assessment"]), r["assessment_type"])
        if k not in first or cand[0] < first[k][0]:
            first[k] = cand
    by_id = {v[1]: k for k, v in first.items()}
    sub = {}
    for r in table(z, "studentAssessment"):
        aid = int(r["id_assessment"])
        if aid not in by_id:
            continue
        key = by_id[aid] + (r["id_student"],)
        sub[key] = (num(r["date_submitted"]), int(r["is_banked"]))
    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(["code_module", "code_presentation", "id_student", "first_assessment_id", "first_assessment_type",
                    "first_due_day", "submitted_day", "is_banked"])
        for r in table(z, "studentRegistration"):
            k = (r["code_module"], r["code_presentation"])
            d, aid, typ = first[k]
            s = sub.get(k + (r["id_student"],))
            w.writerow([k[0], k[1], r["id_student"], aid, typ, d, "" if s is None or s[0] is None else s[0],
                        "" if s is None else s[1]])
            n += 1
    os.replace(tmp, out)
    return {"enrolments": n, "course_runs": len(first)}


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" / "first-assessment.csv.gz"))
    a = ap.parse_args()
    print(json.dumps(build(fetch(Path(a.cache)), Path(a.out))))


if __name__ == "__main__":
    main()
