"""Per enrolment, the days with any activity on the course site from day 0 to its course run's first due day (both
included), for change 2's same-day use rule (CHANGES-r2.md, check C-C). Reads the same checked zip as
tools/get_data.py; the first due day is the one tools/get_first_assessment.py uses (earliest non-exam assessment).

Usage: python3 -I -B tools/get_due_usage.py [--cache DIR] [--out data/due-usage.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"])
        first[k] = min(first.get(k, 10 ** 6), num(r["date"]))
    days = {}
    rows = 0
    for r in table(z, "studentVle"):
        rows += 1
        d = int(r["date"])
        mp = (r["code_module"], r["code_presentation"])
        if d < 0 or d > first[mp]:
            continue
        days.setdefault(mp + (r["id_student"],), set()).add(d)
    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_due_day", "days_active_to_due"])
        for r in table(z, "studentRegistration"):
            k = (r["code_module"], r["code_presentation"])
            w.writerow([k[0], k[1], r["id_student"], first[k], len(days.get(k + (r["id_student"],), ()))])
            n += 1
    os.replace(tmp, out)
    return {"enrolments": n, "activity_rows_read": rows, "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" / "due-usage.csv.gz"))
    a = ap.parse_args()
    print(json.dumps(build(fetch(Path(a.cache)), Path(a.out))))


if __name__ == "__main__":
    main()
