#!/usr/bin/env python3
"""Join request rows to evidence rows by request_id.

The printed rows are in predicted-join.txt.
The owned requests.csv and evidence.csv are the inputs for those rows.
A later run that disagrees with that card should correct the card.

Later use, only on the owned files in this folder:
  python3 join-evidence.py requests.csv evidence.csv

Standard library only. No network. No password field.
Duplicate ids are reported. The first row is kept. Later copies do not overwrite.
A request with no evidence row is unmatched. It is not printed as a denial.
""",

import csv
import sys


def load(path, required):
    with open(path, newline="", encoding="utf-8") as handle:
        reader = csv.DictReader(handle)
        if reader.fieldnames is None:
            raise SystemExit(f"{path}: missing header")
        missing = [name for name in required if name not in reader.fieldnames]
        if missing:
            raise SystemExit(path + ": missing columns " + ", ".join(missing))
        rows = []
        seen = {}
        duplicates = []
        for row in reader:
            key = row["request_id"]
            if key in seen:
                duplicates.append(key)
                continue
            seen[key] = row
            rows.append(row)
        return rows, seen, duplicates


def main(argv):
    if len(argv) != 3:
        raise SystemExit("usage: join-evidence.py requests.csv evidence.csv")
    requests, request_map, request_dups = load(
        argv[1], ["request_id", "account", "action"]
    )
    _evidence_rows, evidence_map, evidence_dups = load(
        argv[2], ["request_id", "result", "note"]
    )
    print("joined")
    print("request_id,account,action,result,note")
    unmatched = []
    for row in requests:
        key = row["request_id"]
        evidence = evidence_map.get(key)
        if evidence is None:
            unmatched.append(key)
            continue
        print(
            ",".join(
                [
                    key,
                    row["account"],
                    row["action"],
                    evidence["result"],
                    evidence["note"],
                ]
            )
        )
    print("unmatched_requests")
    for key in unmatched:
        print(key)
    print("evidence_without_request")
    for key in evidence_map:
        if key not in request_map:
            print(key)
    print("duplicate_request_ids")
    for key in request_dups:
        print("requests:" + key)
    for key in evidence_dups:
        print("evidence:" + key)


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