#!/usr/bin/env python3
"""Check your own data platform logs for two HIPAA Security Rule items, in DuckDB:
audit controls (164.312(b)) and log-in monitoring (164.308(a)(5)(ii)(C)).

    python3 hipaa_log_check.py --demo                  # clean generated records
    python3 hipaa_log_check.py --demo --plant-error    # generated records with days that have no records and a run of failed sign-ins
    python3 hipaa_log_check.py --demo --plant-input    # generated records with planted input faults
    python3 hipaa_log_check.py --demo --plant-header   # generated records with one column renamed in daily_records.csv
    python3 hipaa_log_check.py                         # your exports: set DATA_DIR and the settings below first
    python3 hipaa_log_check.py --data <folder>         # your exports in <folder> (instead of editing DATA_DIR)
    python3 hipaa_log_check.py --strict                # exit 1 if any day has no records or is NOT COVERED
    add  --out <folder>  to write every file under that folder (default: ./hipaa-log-out)

It reads two CSV files from each platform's own logs, plus an optional list of logins (see COLUMN_MAP):
  daily_records.csv   how many sign-in records and query records each platform kept on each day
  failed_sign_ins.csv every failed sign-in: when, which login, and the reason the platform gave
  logins.csv          (optional) the logins that exist, so attempts on any other name can be listed
and prints:
  1. Audit controls: for each platform and log, the days of the period with records, the days with none, and the
     days the exports cannot show (before the platform's records start, or after the exports were taken).
  2. Log-in monitoring: failed sign-ins in the period by login, the logins over FAILED_PER_DAY_LIMIT on a day, and
     failed attempts on names that are not a login in logins.csv.
Each list is printed with its period, row count and a SHA-256 of its rows, and written as CSV under --out.

This is evidence for a person to look at, not a finding that anyone complies. The two items, the limit and the
days you call quiet are your decisions; your compliance team and your auditor decide what is enough.
Needs Python 3 and the duckdb module (tested on DuckDB 1.5.6 and 2.0.0). Reads only the files you give it.
Exits 2, and computes nothing, if an input check fails.
"""
import argparse
import csv
import datetime as dt
import hashlib
import os
import pathlib
import random
import sys

import duckdb

# ---------------------------------------------------------------- settings: change these, and nothing else
PERIOD_START = "2026-07-01"   # first day of the period you are checking (YYYY-MM-DD)
PERIOD_END = "2026-09-30"     # last day of the period (YYYY-MM-DD)
AS_OF = "2026-10-05"          # the day you took the exports (YYYY-MM-DD)
DATA_DIR = None               # the folder that holds your CSV files, for example "exports"
PLATFORMS = ["snowflake", "databricks", "redshift"]   # the platforms you exported; any other is NOT CHECKED
# how many days back each platform's own views keep each log, counted back from AS_OF (see the page for the sources)
HISTORY_DAYS = {"snowflake": {"sign_ins": 365, "queries": 365},
                "databricks": {"sign_ins": 395, "queries": 365},
                "redshift": {"sign_ins": 7, "queries": 7}}
# if you keep your own daily copies of the exports, the first day those copies cover, per platform; {} if none.
# (--demo uses 2026-06-01 for Redshift, the first day of its generated daily copies.)
KEPT_SINCE = {}
# days you know a platform had no activity at all (a shutdown, a holiday), per platform, as YYYY-MM-DD; they are
# listed as quiet days instead of as days with no records
QUIET_DAYS = {}
FAILED_PER_DAY_LIMIT = 5      # a login with more failed sign-ins than this on one day is listed
FILE_NAMES = {"daily": "daily_records.csv", "failed": "failed_sign_ins.csv", "logins": "logins.csv"}
# the column names in your files: change the name on the right of each line, never the one on the left
COLUMN_MAP = {
    "daily": {"platform": "platform", "day": "day", "log": "log", "records": "records"},
    "failed": {"platform": "platform", "event_time": "event_time", "login": "login", "reason": "reason"},
    "logins": {"platform": "platform", "login": "login", "email": "email"},
}
# ---------------------------------------------------------------- end of settings

KNOWN_PLATFORMS = ["snowflake", "databricks", "redshift"]
OPTIONAL_COLUMNS = {("logins", "email")}   # logins.csv may leave out email
LOGS = ["sign_ins", "queries"]
DATE_RE = r"\d{4}-\d{2}-\d{2}"
TIME_RE = r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]00:?00)?"


def days(a, b):
    d, out = dt.date.fromisoformat(a), []
    while d <= dt.date.fromisoformat(b):
        out.append(d.isoformat())
        d += dt.timedelta(days=1)
    return out


def generate(folder, plant_error=False, plant_input=False, plant_header=False):
    """Generated records in the shape the page's export queries write. Not anyone's real logs."""
    rnd = random.Random(164312)
    folder.mkdir(parents=True, exist_ok=True)
    period = days(PERIOD_START, AS_OF)
    daily, failed = [], []
    logins = {"snowflake": ["ADA", "BEN", "CHLOE", "ETL_SVC"],
              "databricks": ["ada.novak@example.com", "ben.reyes@example.com", "chloe.novak@example.com"],
              "redshift": ["ada", "ben", "etl_loader"]}
    for p in KNOWN_PLATFORMS:
        start = "2026-06-01" if p == "redshift" else "2025-10-06"
        for d in days(start, AS_OF):
            weekend = dt.date.fromisoformat(d).weekday() >= 5
            s = rnd.randint(8, 20) if weekend else rnd.randint(40, 90)
            q = rnd.randint(200, 400) if weekend else rnd.randint(1500, 4000)
            if plant_error and p == "databricks" and "2026-08-12" <= d <= "2026-08-14":
                continue          # planted: three days with no sign-in records and no query records
            if plant_error and p == "redshift" and d == "2026-09-02":
                daily.append([p, d, "queries", q])
                continue          # planted: one day with query records but no sign-in records
            daily += [[p, d, "sign_ins", s], [p, d, "queries", q]]
    has_signins = {(r[0], r[1]) for r in daily if r[2] == "sign_ins"}
    for d in period:
        for p in KNOWN_PLATFORMS:
            if rnd.random() < 0.25:
                who = rnd.choice(logins[p])
                row = [p, f"{d} {rnd.randint(7, 19):02d}:{rnd.randint(0, 59):02d}:{rnd.randint(0, 59):02d}", who,
                       {"snowflake": "INCORRECT_USERNAME_PASSWORD", "databricks": "401", "redshift": "authentication failure"}[p]]
                if (p, d) in has_signins:   # a failed sign-in is a sign-in record, so only on a day that has some
                    failed.append(row)
    if plant_error:
        # planted: twelve failed sign-ins for BEN within one hour, and three attempts on a name that is not a login
        failed += [["snowflake", f"2026-08-19 02:{m:02d}:07", "BEN", "INCORRECT_USERNAME_PASSWORD"] for m in range(0, 60, 5)]
        failed += [["snowflake", f"2026-09-09 03:1{m}:44", "ADMIN", "USER_DOES_NOT_EXIST"] for m in range(3)]
    if plant_input:
        daily.append(["snowflake", "8/5/26", "sign_ins", 40])            # not YYYY-MM-DD
        daily.append(["databricks", "2026-08-05", "sign_ins", -3])       # not a whole number of records
        daily.append(list(daily[0]))                                      # the same platform, day and log twice
        failed.append(["redshift", "2026/08/05 10:00", "ben", "authentication failure"])   # not a timestamp
    dh = ["platform", "day", "log", "count" if plant_header else "records"]
    for name, head, rows in (("daily_records.csv", dh, daily),
                             ("failed_sign_ins.csv", ["platform", "event_time", "login", "reason"], failed),
                             ("logins.csv", ["platform", "login", "email"],
                              [[p, l, l if "@" in l else f"{l.lower()}@example.com"] for p in KNOWN_PLATFORMS for l in logins[p]])):
        with open(folder / name, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(head)
            w.writerows(rows)


def sha(rows):
    h = hashlib.sha256()
    for r in rows:
        h.update(("\t".join("" if v is None else str(v) for v in r) + "\n").encode())
    return h.hexdigest()


def ranges(ds):
    """Consecutive YYYY-MM-DD days as 'a to b (n day(s))' strings."""
    out, run = [], []
    for d in sorted(ds):
        if run and dt.date.fromisoformat(d) - dt.date.fromisoformat(run[-1]) != dt.timedelta(days=1):
            out.append(run)
            run = []
        run.append(d)
    if run:
        out.append(run)
    return [f"{r[0]} to {r[-1]} ({len(r)} day(s))" for r in out]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--demo", action="store_true")
    ap.add_argument("--plant-error", action="store_true")
    ap.add_argument("--plant-input", action="store_true")
    ap.add_argument("--plant-header", action="store_true")
    ap.add_argument("--data")
    ap.add_argument("--out", default="hipaa-log-out")
    ap.add_argument("--strict", action="store_true")
    a = ap.parse_args()
    out = pathlib.Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    if a.demo:
        data = out / "generated"     # written after the settings check, which the generated records depend on
    else:
        data = pathlib.Path(a.data or DATA_DIR or ".")
    print(f"hipaa_log_check  duckdb {duckdb.__version__}  python {sys.version.split()[0]}")
    print(f"period {PERIOD_START} to {PERIOD_END}, exports taken {AS_OF}, data {'generated (--demo)' if a.demo else data}")

    con = duckdb.connect()
    problems = []

    def check(label, bad, detail=""):
        if bad:
            problems.append(label)
            print(f"  [FAIL] {label}: {detail}")
        else:
            print(f"  [ok] {label}")

    print("\nInput checks (nothing is computed unless all pass)")
    # settings
    bad = [x for x in (PERIOD_START, PERIOD_END, AS_OF) if not (isinstance(x, str) and len(x) == 10 and x[4] == "-")]
    try:
        dt.date.fromisoformat(AS_OF)
        ok_order = not bad and dt.date.fromisoformat(PERIOD_START) <= dt.date.fromisoformat(PERIOD_END)
    except (TypeError, ValueError):
        ok_order = False
    check("PERIOD_START, PERIOD_END and AS_OF are real dates written YYYY-MM-DD and the period starts before it ends", not ok_order,
          "set the three dates at the top of the script")
    check("PLATFORMS lists the platforms you exported, from " + ", ".join(KNOWN_PLATFORMS),
          not PLATFORMS or any(p not in KNOWN_PLATFORMS for p in PLATFORMS), f"PLATFORMS is {PLATFORMS}")
    hd_bad = [f"{p}/{lg}" for p in PLATFORMS for lg in LOGS
              if not isinstance(HISTORY_DAYS.get(p, {}).get(lg), int) or HISTORY_DAYS[p][lg] < 1]
    check("HISTORY_DAYS gives a whole number of days for each platform and log", hd_bad, ", ".join(hd_bad))
    kept = dict(KEPT_SINCE)
    if a.demo:
        kept.setdefault("redshift", "2026-06-01")
    sd_bad = [f"{p}: {v}" for p, v in kept.items() if not isinstance(v, str) or len(v) != 10]
    sd_bad += [f"{p}: {v}" for p, vs in QUIET_DAYS.items() for v in vs if not isinstance(v, str) or len(v) != 10]
    for p, v in list(kept.items()) + [(p, v) for p, vs in QUIET_DAYS.items() for v in vs]:
        try:
            dt.date.fromisoformat(v)
        except (TypeError, ValueError):
            sd_bad.append(f"{p}: {v}")
    check("every day in KEPT_SINCE and QUIET_DAYS is YYYY-MM-DD", sd_bad, ", ".join(sorted(set(sd_bad))))
    if problems:
        print(f"\nINCOMPLETE: {len(problems)} input check(s) failed, so nothing is computed. Fix the settings.")
        return 2
    if a.demo:
        generate(data, a.plant_error, a.plant_input, a.plant_header)

    # files and headers
    def load(kind, required):
        path = data / FILE_NAMES[kind]
        if not path.exists():
            if required:
                check(f"{FILE_NAMES[kind]} exists in {data}", True, "file not found")
            else:
                print(f"  [--] {FILE_NAMES[kind]} not found: failed attempts on unknown names are NOT CHECKED")
            return False
        con.execute(f"CREATE TEMP TABLE raw_{kind} AS SELECT * FROM read_csv(?, header = true, all_varchar = true)", [str(path)])
        cols = {c.lower(): c for c in [r[0] for r in con.execute(f"DESCRIBE raw_{kind}").fetchall()]}
        need = {std: mine for std, mine in COLUMN_MAP[kind].items() if (kind, std) not in OPTIONAL_COLUMNS}
        missing = [mine for mine in need.values() if mine.lower() not in cols]
        for std, mine in COLUMN_MAP[kind].items():
            if (kind, std) in OPTIONAL_COLUMNS and mine.lower() not in cols:
                print(f"  [--] {FILE_NAMES[kind]} has no {mine} column: names are matched on {COLUMN_MAP[kind]['login']} only")
        check(f"{FILE_NAMES[kind]} has the columns {', '.join(need.values())}", missing,
              f"missing {', '.join(missing)}: rename it in the file or change COLUMN_MAP")
        if missing:
            return False
        sel = ", ".join((f'trim(coalesce("{cols[mine.lower()]}", \'\'))' if mine.lower() in cols else "''") + f" AS {std}"
                        for std, mine in COLUMN_MAP[kind].items())
        con.execute(f"CREATE TEMP TABLE t_{kind} AS SELECT {sel} FROM raw_{kind}")
        return True

    have_d = load("daily", True)
    have_f = load("failed", True)
    have_l = load("logins", False)
    if problems:
        print(f"\nINCOMPLETE: {len(problems)} input check(s) failed, so nothing is computed. Fix the input.")
        return 2

    q = lambda sql, p=None: con.execute(sql, p or []).fetchone()[0]
    plats = ", ".join(f"'{p}'" for p in KNOWN_PLATFORMS)
    n = q(f"SELECT count(*) FROM t_daily WHERE lower(platform) NOT IN ({plats})")
    check("every platform in daily_records.csv is snowflake, databricks or redshift", n, f"{n} row(s) with another platform")
    n = q(f"SELECT count(*) FROM t_daily WHERE NOT regexp_full_match(day, '{DATE_RE}') OR try_strptime(day, '%Y-%m-%d') IS NULL")
    check("every day in daily_records.csv is written YYYY-MM-DD", n, f"{n} row(s) not written as YYYY-MM-DD")
    n = q("SELECT count(*) FROM t_daily WHERE lower(log) NOT IN ('sign_ins', 'queries')")
    check("every log in daily_records.csv is sign_ins or queries", n, f"{n} row(s) with another log")
    n = q(r"SELECT count(*) FROM t_daily WHERE NOT regexp_full_match(records, '\d+')")
    check("every records value is a whole number of 0 or more", n, f"{n} row(s) with another value")
    n = q("SELECT count(*) FROM (SELECT lower(platform), day, lower(log) FROM t_daily GROUP BY ALL HAVING count(*) > 1)")
    check("no platform, day and log appears twice in daily_records.csv", n, f"{n} platform-day-log(s) twice: export each day once")
    n = q(f"SELECT count(*) FROM t_failed WHERE lower(platform) NOT IN ({plats})")
    check("every platform in failed_sign_ins.csv is snowflake, databricks or redshift", n, f"{n} row(s) with another platform")
    n = q(f"SELECT count(*) FROM t_failed WHERE NOT regexp_full_match(event_time, '{TIME_RE}') "
          "OR try_cast(left(replace(event_time, 'T', ' '), 19) AS TIMESTAMP) IS NULL")
    check("every event_time is a real time written YYYY-MM-DD HH:MM:SS (UTC)", n, f"{n} row(s) that are not")
    n = q("SELECT count(*) FROM t_failed WHERE login = ''")
    check("every failed sign-in names a login", n, f"{n} row(s) with no login: export the name the platform recorded")
    if problems:
        print(f"\nINCOMPLETE: {len(problems)} input check(s) failed, so nothing is computed. Fix the input.")
        return 2
    con.execute("""CREATE TEMP TABLE dr AS SELECT lower(platform) AS platform, strptime(day, '%Y-%m-%d')::DATE AS day,
                   lower(log) AS log, records::BIGINT AS records FROM t_daily""")
    con.execute("""CREATE TEMP TABLE fs AS SELECT lower(platform) AS platform, left(replace(event_time, 'T', ' '), 19) AS ts,
                   left(event_time, 10)::DATE AS day, login AS login_shown, lower(login) AS login, reason FROM t_failed""")
    # a failed sign-in is itself a sign-in record, so a day cannot hold more failures than sign-in records
    n = q("""SELECT count(*) FROM (SELECT platform, day, count(*) AS f FROM fs GROUP BY ALL) x
             LEFT JOIN dr ON dr.platform = x.platform AND dr.day = x.day AND dr.log = 'sign_ins'
             WHERE x.f > coalesce(dr.records, 0)""")
    check("no day has more failed sign-ins than sign-in records (the two files come from the same log)", n,
          f"{n} platform-day(s) with more failures than records: export both files from the same view, after the same day")
    if problems:
        print(f"\nINCOMPLETE: {len(problems)} input check(s) failed, so nothing is computed. Fix the input.")
        return 2

    # ---------------------------------------------------------------- 1. audit controls
    ps, pe, asof = dt.date.fromisoformat(PERIOD_START), dt.date.fromisoformat(PERIOD_END), dt.date.fromisoformat(AS_OF)
    rows, gaps, not_cov, quiet = [], {}, {}, {}
    exported = {r[0] for r in con.execute("SELECT DISTINCT platform FROM dr").fetchall()}
    counts = {(r[0], r[1].isoformat(), r[2]): r[3] for r in con.execute("SELECT platform, day, log, records FROM dr").fetchall()}
    has_log = {(r[0], r[1]) for r in con.execute("SELECT DISTINCT platform, log FROM dr").fetchall()}
    print("\n1. AUDIT CONTROLS: did each platform keep sign-in and query records on every day of the period?")
    for p in KNOWN_PLATFORMS:
        if p not in PLATFORMS or p not in exported:
            print(f"  {p:<11} NOT CHECKED: {'not in PLATFORMS' if p not in PLATFORMS else 'no rows in ' + FILE_NAMES['daily']}")
            if p in PLATFORMS:
                not_cov.setdefault((p, "all logs"), {})["no rows exported for this platform"] = days(PERIOD_START, PERIOD_END)
            continue
        for lg in LOGS:
            floor = asof - dt.timedelta(days=HISTORY_DAYS[p][lg] - 1)
            if p in kept:
                floor = min(floor, dt.date.fromisoformat(kept[p]))
            with_rec = 0
            for d in days(PERIOD_START, PERIOD_END):
                dd = dt.date.fromisoformat(d)
                if dd > asof:
                    state = "after the day the exports were taken"
                elif dd < floor:
                    state = f"before the platform's records start ({floor.isoformat()})"
                elif (p, lg) not in has_log:
                    state = f"no {lg} rows exported for this platform"
                else:
                    r = counts.get((p, d, lg), 0)
                    if r > 0:
                        state = "records"
                        with_rec += 1
                    elif d in QUIET_DAYS.get(p, []):
                        state = "quiet day (QUIET_DAYS)"
                        quiet.setdefault((p, lg), []).append(d)
                    else:
                        state = "NO RECORDS"
                        gaps.setdefault((p, lg), []).append(d)
                if state not in ("records", "NO RECORDS", "quiet day (QUIET_DAYS)"):
                    not_cov.setdefault((p, lg), {}).setdefault(state, []).append(d)
                rows.append((p, lg, d, counts.get((p, d, lg), 0), state))
            total = (pe - ps).days + 1
            nq = len(quiet.get((p, lg), []))
            print(f"  {p:<11} {lg:<9} {with_rec} of {total} days with records, {len(gaps.get((p, lg), []))} with none, "
                  + (f"{nq} quiet, " if nq else "")
                  + f"{sum(len(v) for v in not_cov.get((p, lg), {}).values())} NOT COVERED")
    rows.sort()
    print(f"  Population: {len(rows)} platform-log-days, period {PERIOD_START} to {PERIOD_END}, exports taken {AS_OF}, SHA-256 {sha(rows)[:16]}...")
    print("\n  Days with no records (a platform in use writes sign-in and query records every day; each day needs a reason):")
    if not gaps:
        print("    none")
    for (p, lg), ds in sorted(gaps.items()):
        for r in ranges(ds):
            print(f"    {p:<11} {lg:<9} {r}")
    if quiet:
        print("  Quiet days you listed in QUIET_DAYS (not counted as gaps, still listed):")
        for (p, lg), ds in sorted(quiet.items()):
            for r in ranges(ds):
                print(f"    {p:<11} {lg:<9} {r}")

    # ---------------------------------------------------------------- 2. log-in monitoring
    print(f"\n2. LOG-IN MONITORING: failed sign-ins from {PERIOD_START} to {PERIOD_END}")
    covered = {(p, d) for (p, lg, d, _, st) in rows if lg == "sign_ins" and st in ("records", "NO RECORDS", "quiet day (QUIET_DAYS)")}
    frows = [r for r in con.execute(f"""SELECT platform, ts, login_shown, login, reason FROM fs
             WHERE day BETWEEN DATE '{PERIOD_START}' AND DATE '{PERIOD_END}' ORDER BY platform, ts, login, reason""").fetchall()
             if r[0] in PLATFORMS]
    pop = [(r[0], r[1], r[2], r[4]) for r in frows]
    print(f"  Population: {len(pop)} failed sign-in(s), SHA-256 {sha(pop)[:16]}...")
    by = {}
    for p, ts, shown, key, reason in frows:
        b = by.setdefault((p, key), {"shown": shown, "n": 0, "days": {}, "first": ts, "last": ts, "reasons": set()})
        b["n"] += 1
        b["days"][ts[:10]] = b["days"].get(ts[:10], 0) + 1
        b["last"] = ts
        b["reasons"].add(reason)
    print("  By login:")
    if not by:
        print("    none")
    for (p, key), b in sorted(by.items(), key=lambda kv: (-kv[1]["n"], kv[0])):
        print(f"    {p:<11} {b['shown']:<26} {b['n']:>4} failed on {len(b['days'])} day(s), most in one day "
              f"{max(b['days'].values())}, first {b['first']}, last {b['last']}  ({', '.join(sorted(b['reasons']))})")
    over = sorted((p, b["shown"], d, c) for (p, key), b in by.items() for d, c in b["days"].items() if c > FAILED_PER_DAY_LIMIT)
    print(f"  Logins with more than FAILED_PER_DAY_LIMIT = {FAILED_PER_DAY_LIMIT} failed sign-ins on one day:")
    print("    none" if not over else "\n".join(f"    {p:<11} {who:<26} {d}  {c} failed" for p, who, d, c in over))
    unknown = []
    if have_l:
        # a name counts as a login if it is the login in logins.csv, or on Databricks, whose export records the user's
        # email, the email; on Snowflake and Redshift an email tried as a user name stays an unknown name
        known = {(r[0], r[1]) for r in con.execute("""SELECT lower(platform), lower(login) FROM t_logins UNION
                 SELECT lower(platform), lower(email) FROM t_logins WHERE email <> '' AND lower(platform) = 'databricks'""").fetchall()}
        lplats = {k[0] for k in known}
        unknown = sorted({(p, b["shown"], b["n"]) for (p, key), b in by.items() if p in lplats and (p, key) not in known})
        print(f"  Failed attempts on names that are not a login in {FILE_NAMES['logins']}:")
        print("    none" if not unknown else "\n".join(f"    {p:<11} {who:<26} {c} failed" for p, who, c in unknown))
        for p in PLATFORMS:
            if p in exported and p not in lplats:
                print(f"    {p}: NOT CHECKED (no rows for this platform in {FILE_NAMES['logins']})")
    blind = sorted((p, d) for p in PLATFORMS for d in days(PERIOD_START, PERIOD_END) if (p, d) not in covered)
    if blind:
        print("  Failed sign-ins cannot be seen on the NOT COVERED sign_ins days below.")

    # ---------------------------------------------------------------- 3. NOT COVERED
    print("\n3. NOT COVERED (days these exports cannot show; never read as nothing happened)")
    if not not_cov:
        print("  none")
    for (p, lg), reasons in sorted(not_cov.items()):
        for reason, ds in reasons.items():
            for r in ranges(ds):
                print(f"  {p:<11} {lg:<9} {r}: {reason}")

    # ---------------------------------------------------------------- files
    def write(name, head, data_rows):
        with open(out / name, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(head)
            w.writerows(data_rows)
    write("audit_days.csv", ["platform", "log", "day", "records", "state"], rows)
    write("failed_sign_ins_in_period.csv", ["platform", "event_time", "login", "reason"], pop)
    write("logins_over_limit.csv", ["platform", "login", "day", "failed"], over)
    write("unknown_login_names.csv", ["platform", "login", "failed"], unknown)
    ngap = sum(len(v) for v in gaps.values())
    nnc = sum(len(ds) for v in not_cov.values() for ds in v.values())
    print(f"\n{ngap} platform-log-day(s) with no records, {nnc} NOT COVERED, {len(pop)} failed sign-in(s), "
          f"{len(over)} login-day(s) over the limit, {len(unknown)} unknown name(s).")
    print(f"Evidence written to {out}/ (audit_days.csv, failed_sign_ins_in_period.csv, logins_over_limit.csv, unknown_login_names.csv)")
    if a.strict and (ngap or nnc):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
