#!/usr/bin/env python3
"""Offline standard straight-trade examples, reviewed December 2, 2026.

Companion: alphascope.app/blog/polymarket-us-fees
Source: https://docs.polymarket.us/fees
No account access, eligibility determination, live quotes, combo fees, maker
rebates, funding costs or promise of a rebate. API promotion referenced in the
article is dated through December 31, 2026. Check current provider terms.
"""

import csv
from decimal import Decimal, InvalidOperation, ROUND_HALF_EVEN
from pathlib import Path
import sys

CENT = Decimal("0.01")
ONE = Decimal(1)


def number(value):
    if isinstance(value, bool):
        raise ValueError("Use a finite decimal number")
    try:
        result = Decimal(str(value))
    except InvalidOperation as exc:
        raise ValueError("Use a finite decimal number") from exc
    if not result.is_finite():
        raise ValueError("Use a finite decimal number")
    return result


def cents(value):
    return number(value).quantize(CENT, rounding=ROUND_HALF_EVEN)


def exact_fee(contracts, price, coefficient):
    quantity, p, theta = map(number, (contracts, price, coefficient))
    if quantity <= 0 or quantity != quantity.to_integral_value():
        raise ValueError("This worksheet uses positive integer contract quantities")
    if not Decimal("0.01") <= p <= Decimal("0.99") or theta < 0:
        raise ValueError("Use a price from $0.01 to $0.99 and nonnegative taker coefficient")
    return theta * quantity * p * (ONE - p)


def modeled_credit(gross_fee, qualifying_fraction):
    """Conditional arithmetic only. No eligibility, basis or payout inference."""
    gross, share = number(gross_fee), number(qualifying_fraction)
    if gross < 0 or not 0 <= share <= 1:
        raise ValueError("Use a nonnegative charge and a fraction from 0 to 1")
    return cents(gross * share)


def illustrative_order_charges(fills):
    """One cap-respecting allocation for ONE aggressive order.

    Provider rule: independently half-even round each fill, adjusting down so
    cumulative charges never exceed rounded cumulative exact fees. This greedy
    illustration is not a claim about the venue's precise allocation algorithm.
    Start a fresh invocation for each order; do not pool unrelated orders.
    fills: iterable of (contracts, decimal dollar price, coefficient).
    """
    exact_total = Decimal(0)
    charged_total = Decimal(0)
    charges = []
    for quantity, price, coefficient in fills:
        raw = exact_fee(quantity, price, coefficient)
        exact_total += raw
        charge = min(cents(raw), cents(exact_total) - charged_total)
        charges.append(charge)
        charged_total += charge
    return charges


def main():
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_suffix(".csv")
    with path.open(newline="", encoding="utf-8") as source:
        rows = list(csv.DictReader(source))
    print("Fictional single-fill scenarios; USD; standard straight taker trades")
    for row in rows:
        raw = exact_fee(row["contracts"], row["price"], row["coefficient"])
        if raw != number(row["exact_fee"]) or cents(raw) != number(row["rounded_single_fill_fee"]):
            raise ValueError(f"CSV calculation mismatch: {row['scenario']}")
        print(f"{row['scenario']}: exact={raw}; cent-rounded={cents(raw)}")
    gross = cents(exact_fee(80, "0.50", "0.0695"))
    credit = modeled_credit(gross, "0.70")
    print(f"Conditional credit model: gross={gross}; modeled credit={credit}; residual fee={gross-credit}")
    print("Initial purchase plus gross fee:", Decimal(40) + gross)
    print("Purchase plus residual fee AFTER modeled credit:", Decimal(40) + gross - credit)
    fills = [(1, "0.50", "0.0695")] * 3
    charges = illustrative_order_charges(fills)
    print("Illustrative ONE-order fill charges:", charges, "; total:", sum(charges))
    exit_fee = cents(exact_fee(80, "0.60", "0.0695"))
    print("Entry/exit scenario gain before any rebates or other costs:", Decimal(8) - gross - exit_fee)


if __name__ == "__main__":
    main()
