"""Selected PINT-AE totals relationships on fictional tax-exclusive AED inputs."""
from datetime import datetime, timezone
from decimal import Decimal
import hashlib
import json
from pathlib import Path
import re
import sys


def amount(value):
    if not isinstance(value, str) or not re.fullmatch(r"-?\d+(\.\d{1,2})?", value):
        raise ValueError("explicit decimal string with at most two places required")
    return Decimal(value)


def findings(fixture):
    if fixture["currency"] != "AED" or fixture["tax_included_pricing"] is not False:
        raise ValueError("only the declared tax-exclusive AED fixture is supported")
    rows = []
    for case in fixture["cases"]:
        if not case["lines"]:
            raise ValueError("nonempty fictional line amounts required")
        expected = {
            "IBR-CO-13": sum(map(amount, case["lines"])) - amount(case["allowance"]) + amount(case["charge"]),
            "IBR-CO-15": amount(case["without_tax"]) + amount(case["tax"]),
            "IBR-CO-16": amount(case["with_tax"]) - amount(case["paid"]) + amount(case["rounding"]),
        }
        observed = dict(zip(expected, map(amount, [case["without_tax"], case["with_tax"], case["due"]])))
        differences = {rule: observed[rule] - total for rule, total in expected.items()}
        failed = [rule for rule, gap in differences.items() if gap != 0]
        assert failed == case["expected_failed"], case["id"]
        rows.append(dict(id=case["id"], failed=failed, checks=[
            dict(rule=rule, expected=format(total, ".2f"), observed=format(observed[rule], ".2f"),
                 observed_minus_expected=format(differences[rule], ".2f"))
            for rule, total in expected.items()]))
    return rows


def generate():
    root = Path(__file__).parent
    fixture = json.loads((root / "fixture.json").read_text())
    results = findings(fixture)
    # Exercise boundaries that otherwise could be mistaken for supported inputs.
    changed = dict(fixture, tax_included_pricing=True)
    try:
        findings(changed)
    except ValueError:
        pass
    else:
        raise AssertionError("tax-inclusive pricing must remain outside scope")
    for invalid in ["1.001", "NaN", "1e2", 1.25]:
        try:
            amount(invalid)
        except ValueError:
            continue
        raise AssertionError("unsupported decimal input accepted")
    return dict(author="Anant Mishra", executed_at_utc=datetime.now(timezone.utc).isoformat(),
                python_version=sys.version, command="python3 reproduce.py",
                status="executed_synthetic_selected_totals_only",
                reviewed_specification=fixture["reviewed_specification"],
                hashes={name: hashlib.sha256((root / name).read_bytes()).hexdigest()
                        for name in ["fixture.json", "reproduce.py"]}, results=results,
                limitations="Five invented AED records, two-decimal amounts and tax-exclusive pricing only. Tax supplied as input. No XML, full Schematron validation, tax determination, live ERP or provider transaction was executed.")


if __name__ == "__main__":
    print(json.dumps(generate(), indent=2))
