"""Reproduce a fictional example with Python 3; no packages or network needed.

Save this file beside terms.json, then run: python enumerate_allocations.py
This tiny exhaustive arithmetic oracle is not BidResolve's product solver.
Amounts are exact integer cents in the currency of terms.json. The example does not measure client savings.
"""

import json
from pathlib import Path


def enumerate_allocations(terms):
    offers = {(o["supplier"], o["sku"]): o for o in terms["offers"]}
    rows = []
    step = terms["multiple"]
    for ax in range(0, offers["A", "X"]["capacity"] + 1, step):
        for by in range(0, terms["demand"]["Y"] + 1, step):
            cx, cy = terms["demand"]["X"] - ax, terms["demand"]["Y"] - by
            quantities = {
                ("A", "X"): ax,
                ("B", "Y"): by,
                ("C", "X"): cx,
                ("C", "Y"): cy,
            }
            if any(
                q < 0 or q > offers[key]["capacity"] or q % step
                for key, q in quantities.items()
            ):
                continue
            goods = {
                s: sum(
                    q * offers[key]["unit_price"] * 100
                    for key, q in quantities.items()
                    if key[0] == s
                )
                for s in "ABC"
            }
            discount = (
                goods["C"] * terms["discount"]["basis_points"] // 10000
                if cx + cy >= terms["discount"]["combined_quantity_threshold"]
                else 0
            )
            fees = sum(
                terms["fixed_fees"][s] * 100
                for s in "ABC"
                if any(q and key[0] == s for key, q in quantities.items())
            )
            rows.append(
                {
                    "A_X": ax,
                    "B_Y": by,
                    "C_X": cx,
                    "C_Y": cy,
                    "C_discount_cents": discount,
                    "fees_cents": fees,
                    "total_cents": sum(goods.values()) - discount + fees,
                }
            )
    return sorted(rows, key=lambda row: (row["total_cents"], row["A_X"], row["B_Y"]))


if __name__ == "__main__":
    terms = json.loads(
        Path(__file__).with_name("terms.json").read_text(encoding="utf-8")
    )
    rows = enumerate_allocations(terms)
    print(
        json.dumps(
            {
                "fictional": True,
                "currency": terms["currency"],
                "combination_count": len(rows),
                "minimum": rows[0],
                "all_allocations": rows,
            },
            indent=2,
        )
    )
