"""Reproduce the fictional account mapping replay with Python 3."""
import json
from collections import Counter
from pathlib import Path


def destination(row, rules, release):
    matches = [
        rule["line"]
        for rule in rules
        if rule["release"] == release
        and (rule["ledger"], rule["account"]) == (row["ledger"], row["account"])
        and rule["from_month"] <= row["month"] <= rule["to_month"]
    ]
    if len(matches) == 1:
        return matches[0]
    return "ambiguous" if matches else "missing"


def totals(rows, rules, release):
    amounts = Counter()
    for row in rows:
        line = destination(row, rules, release)
        if line in {"ambiguous", "missing"}:
            raise ValueError(f"{row['id']}: {line}")
        amounts[line] += row["pence"]
    return amounts


def main():
    fixture = json.loads(Path(__file__).with_name("mapping-replay-fixture.json").read_text())
    rules = fixture["rules"]
    original = totals(fixture["rows"], rules, "v1")
    candidate = totals(fixture["rows"], rules, "v2")
    movements = {line: candidate[line] - original[line] for line in sorted(original.keys() | candidate.keys())}
    probes = {row["id"]: destination(row, rules, "v2") for row in fixture["probes"]}
    assert original == {"GENERAL_MAINT": 1200000, "SERVICE_REVENUE": 250000}
    assert candidate == {"PRODUCTION_MAINT": 1200000, "SERVICE_REVENUE": 250000}
    assert movements == {"GENERAL_MAINT": -1200000, "PRODUCTION_MAINT": 1200000, "SERVICE_REVENUE": 0}
    assert sum(original.values()) == sum(candidate.values()) == sum(row["pence"] for row in fixture["rows"])
    assert probes == {"missing": "missing", "overlap": "ambiguous"}
    print(json.dumps({"v1": original, "v2": candidate, "movements_pence": movements, "probes": probes}, indent=2))


if __name__ == "__main__":
    main()
