"""Reproduce Datamsah's five fictional invoice checks with Python 3.

Keep invoice-checks.csv beside this file and run python3 check_invoices.py.
"""

import csv
from decimal import Decimal
from pathlib import Path


def evaluate(row, passed_keys):
    key = (row["supplier_code"], row["invoice_ref"])
    reasons = []
    difference = ""
    if row["printed_currency"] != row["draft_currency"]:
        reasons.append("CURRENCY")
    else:
        printed_total = Decimal(row["printed_net"]) + Decimal(row["printed_tax"])
        delta = Decimal(row["draft_total"]) - printed_total
        difference = format(delta, ".2f")
        if delta != 0:
            reasons.append("TOTAL")
    if key in passed_keys:
        reasons.append("DUPLICATE")
    if row["bank_change_flag"] not in {"yes", "no"}:
        raise ValueError("bank_change_flag must be yes or no")
    if row["bank_change_flag"] == "yes":
        reasons.append("BANK_CHANGE")

    if reasons:
        return "HOLD", "+".join(reasons), difference
    passed_keys.add(key)
    return "PASS", "CLEAR", difference


def main():
    passed_keys = set()
    mismatches = []
    path = Path(__file__).with_name("invoice-checks.csv")
    with path.open(newline="", encoding="utf-8") as source:
        for row in csv.DictReader(source):
            actual = evaluate(row, passed_keys)
            expected = (row["expected_decision"], row["expected_reason"],
                        row["expected_difference"])
            print(row["case_id"], actual[0], actual[1], actual[2] or "n/a")
            if actual != expected:
                mismatches.append(row["case_id"])
    if mismatches:
        raise SystemExit("Unexpected result in " + ", ".join(mismatches))


if __name__ == "__main__":
    main()
