"""Bounded, single-currency accounting fixture. Python 3.9+, standard library.
Amounts are synthetic USD estimates, not a provider billing contract.
No network, model calls or file writes. --test runs the regression suite.
"""
import re
import sys
import unittest
from decimal import Decimal, localcontext, ROUND_HALF_EVEN

SCALE = 1_000_000
PATTERN = re.compile(r"(?:0|[1-9][0-9]{0,8})(?:\.[0-9]{1,6})?")


def micros(text):
    """Require a nonnegative decimal string with at most six fractional places."""
    if not isinstance(text, str) or PATTERN.fullmatch(text) is None:
        raise ValueError("amount must be a bounded decimal string")
    whole, _, fraction = text.partition(".")
    return int(whole) * SCALE + int(fraction.ljust(6, "0"))


def display_cents(units):
    # Context belongs to this presentation operation, not the caller.
    with localcontext() as ctx:
        ctx.prec = 40
        return (Decimal(units) / SCALE).quantize(
            Decimal("0.01"), rounding=ROUND_HALF_EVEN)


def report(amounts, budget):
    if not isinstance(amounts, (list, tuple)) or not 1 <= len(amounts) <= 100_000:
        raise ValueError("provide between 1 and 100000 amounts")
    limit = micros(budget)
    total = sum(micros(value) for value in amounts)
    return {"total_microusd": total, "display_usd": str(display_cents(total)),
            "over_budget": total > limit}


def weak_total(amounts):
    # Deliberately broken: display rounding destroys accounting information.
    return sum((display_cents(micros(x)) for x in amounts), Decimal("0.00"))


class Tests(unittest.TestCase):
    def test_counterexample(self):
        rows = ["0.0004"] * 1000
        self.assertEqual(weak_total(rows), Decimal("0.00"))
        self.assertEqual(report(rows, "0.25"), {
            "total_microusd": 400000, "display_usd": "0.40", "over_budget": True})

    def test_partition_invariance(self):
        split = report(["0.0004"] * 1000, "0.25")
        self.assertEqual(split, report(["0.4"], "0.25"))
        self.assertNotEqual(weak_total(["0.0004"] * 1000), weak_total(["0.4"]))

    def test_order_invariance(self):
        rows = ["0.000001", "1.234567", "0"]
        self.assertEqual(report(rows, "1"), report(list(reversed(rows)), "1"))

    def test_exact_boundary(self):
        self.assertFalse(report(["0.25"], "0.25")["over_budget"])
        self.assertTrue(report(["0.250001"], "0.25")["over_budget"])

    def test_display_does_not_decide(self):
        r = report(["0.254"], "0.25")
        self.assertEqual(r["display_usd"], "0.25")
        self.assertTrue(r["over_budget"])

    def test_half_even_display(self):
        self.assertEqual(str(display_cents(micros("0.005"))), "0.00")
        self.assertEqual(str(display_cents(micros("0.015"))), "0.02")

    def test_invalid_amounts_and_budget(self):
        for value in [None, True, 0.1, "NaN", "Infinity", "-1", "1e-4",
                      " 1", "1\n", "01", "1.0000001", "1000000000", "١"]:
            with self.subTest(value=value):
                with self.assertRaises(ValueError): report([value], "1")
                with self.assertRaises(ValueError): report(["1"], value)

    def test_batch_bounds(self):
        for rows in [[], iter(["1"]), ["0"] * 100001]:
            with self.assertRaises(ValueError): report(rows, "1")

    def test_caller_precision(self):
        with localcontext() as ctx:
            ctx.prec = 2
            self.assertEqual(report(["12345678.123456"], "1")["display_usd"], "12345678.12")

    def test_zero(self):
        self.assertEqual(report(["0"], "0"), {
            "total_microusd": 0, "display_usd": "0.00", "over_budget": False})


if __name__ == "__main__":
    if "--test" in sys.argv:
        unittest.main(argv=[sys.argv[0]])
    else:
        rows = ["0.0004"] * 1000
        print("rounded-per-call USD:", weak_total(rows))
        print("retained-precision report:", report(rows, "0.25"))
