"""Compare two recoveries for one fictional invoice worksheet."""
from pathlib import Path
import csv
from tempfile import TemporaryDirectory

BASELINE = {"INV-100": ["B2", 100], "INV-101": ["B3", 200]}
EXPECTED = {"INV-100": ["B2", 125], "INV-101": ["B3", 200]}
REQUEST = {"invoice": "INV-100", "amount": 125}
ORIGINAL_PROPOSAL = "B3"


def save_export(path, rows):
    with path.open("w", newline="") as output:
        csv.writer(output).writerows(
            (invoice_id, cell, amount) for invoice_id, (cell, amount) in rows.items()
        )


def read_export(path):
    with path.open(newline="") as source:
        return {invoice_id: [cell, int(value)] for invoice_id, cell, value in csv.reader(source)}


def write_cell(path, rows, cell, amount):
    for record in rows.values():
        if record[0] == cell:
            record[1] = amount
            save_export(path, rows)
            return
    raise ValueError("Unknown cell")


def run_trial(path, check_invoice, label):
    try:
        write_cell(path, read_export(path.parents[1] / "baseline.csv"), ORIGINAL_PROPOSAL, REQUEST["amount"])
    except FileNotFoundError:
        print(f"{label} first attempt: FileNotFoundError; no export written")
    else:
        raise AssertionError("Expected a real failure before the recovery")
    assert not path.exists()
    path.parent.mkdir()
    rows = read_export(path.parents[1] / "baseline.csv")
    target = rows[REQUEST["invoice"]][0] if check_invoice else ORIGINAL_PROPOSAL
    write_cell(path, rows, target, REQUEST["amount"])
    observed = read_export(path)
    print(
        f"{label} retry: write succeeded; B2={observed['INV-100'][1]}, "
        f"B3={observed['INV-101'][1]}; expected state matched: {observed == EXPECTED}"
    )
    return observed


with TemporaryDirectory() as directory:
    root = Path(directory)
    save_export(root / "baseline.csv", BASELINE)
    assert run_trial(root / "unchecked" / "worksheet.csv", False, "Unchecked") == {
        "INV-100": ["B2", 100], "INV-101": ["B3", 125]
    }
    assert run_trial(root / "checked" / "worksheet.csv", True, "Checked") == EXPECTED
    assert read_export(root / "baseline.csv") == BASELINE
