"""Utility functions for interacting with L402 servers"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_claudette.ipynb.

# %% auto 0
__all__ = ['Offer', 'PaymentOffers', 'PaymentInfo', 'get_payment_details']

# %% ../nbs/02_claudette.ipynb 2
from fastcore.utils import L, first, last, groupby, mul, add, sub, truediv, patch, store_attr, BasicRepr
import fastcore.all as fc
import os
from collections.abc import Iterable
import httpx

# %% ../nbs/02_claudette.ipynb 22
class Offer(fc.BasicRepr):
    def __init__(self, offer_id, title, description, type, balance, amount, currency, payment_methods):
        store_attr()

# %% ../nbs/02_claudette.ipynb 26
@patch
def starstarmap(self:L, f): return L(f(**o) for o in self)

# %% ../nbs/02_claudette.ipynb 30
@patch
def supports(self: Offer, payment): return payment in self.payment_methods

# %% ../nbs/02_claudette.ipynb 35
class PaymentOffers(fc.BasicRepr):
    def __init__(self, *, version, offers, payment_request_url, payment_context_token, terms_url, metadata=None, expiry=None):
        self.version, self.payment_request_url, self.payment_context_token, self.terms_url, self.metadata, self.offers = (
            version, payment_request_url, payment_context_token, terms_url, metadata, L(offers).starstarmap(Offer))

# %% ../nbs/02_claudette.ipynb 37
@patch
def __str__(self: PaymentOffers):
    return (f"L402 Payment Offers (v{self.version})\n" + 
            '\n'.join(f"- {o.offer_id} '{o.title}' ${o.amount}, {o.balance}, {o.payment_methods}" 
                     for o in self.offers))

# %% ../nbs/02_claudette.ipynb 43
@patch
def by_payment(self:PaymentOffers, payment_type, reverse=False):
    'Returns offers matching the `payment_type` sortedy by `amount`'
    return self.offers.filter(lambda o: o.supports(payment_type)).sorted(lambda o: o.amount, reverse=reverse)

# %% ../nbs/02_claudette.ipynb 58
class PaymentInfo(fc.BasicRepr):
    def __init__(self, *, offer_id, expires_at, payment_request, version):
        store_attr()


# %% ../nbs/02_claudette.ipynb 60
def get_payment_details(url, oid, pm, t):
    "Get payment details for an offer using offer id `oid` and payment method `pm`"
    return PaymentInfo(**httpx.post(url, json={'offer_id': oid, 'payment_method': pm, 'payment_context_token': t}).json())
