Metadata-Version: 2.4
Name: settlesettle
Version: 0.1.0
Summary: The official Python SDK for SettleSettle — Revenue OS for African developers
Project-URL: Homepage, https://settlesettle.uno
Project-URL: Documentation, https://docs.settlesettle.uno
Project-URL: Repository, https://github.com/settlesettle/settlesettle-python
Project-URL: Issues, https://github.com/settlesettle/settlesettle-python/issues
Author-email: Pathy Technology Limited <dev@settlesettle.uno>
License: MIT
Keywords: africa,billing,nigeria,payments,sdk,settlesettle,wallet
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx>=0.27.0
Requires-Dist: typing-extensions>=4.0.0; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.30.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Description-Content-Type: text/markdown

# SettleSettle Python SDK

The official Python SDK for **SettleSettle** — the Revenue OS for African developers. Securely monetize your apps via local fiat rails (Paystack, Flutterwave) or stablecoin payments (Solana USDC) with built-in credit wallets, subscription engines, and automated event tracking.

---

## Features

- **Sync & Async Support**: Supports both synchronous (Django, Flask, Celery) and asynchronous (FastAPI, Starlette) Python frameworks.
- **Credit Wallets**: Effortlessly manage credit packages, debits, credits, and ledger histories.
- **Subscriptions Engine**: Add recurring pricing, trial period checks, and subscription access control.
- **Omni-Billing**: Single unified API for fiat, crypto, credit, and subscription setups.
- **Usage-Based Tracking**: Non-blocking background event buffering and reporting.
- **Rewarded Ad Support**: Verified rewarded ad slot integrations to monetize users with zero-credit fallbacks.

---

## Installation

```bash
pip install settlesettle
```

---

## Quick Start

### 1. Initialize the Client

Set the `SETTLESETTLE_API_KEY` environment variable:

```bash
export SETTLESETTLE_API_KEY="ss_live_..."
```

Or pass it directly:

```python
from settlesettle import SettleSettle

settle = SettleSettle(api_key="ss_live_...")
```

---

## Usage Examples

### Synchronous (Django / Flask)

```python
from settlesettle import SettleSettle, InsufficientCreditsError

# Reads SETTLESETTLE_API_KEY from environment
settle = SettleSettle()

def process_ai_query(user_id: str, prompt: str):
    try:
        # 1. Debit the wallet for the action cost
        settle.wallet.debit(user_id, amount=10, description="AI Query")
    except InsufficientCreditsError as e:
        return {
            "error": "insufficient_credits",
            "current_balance": e.current_balance,
            "requested": e.requested_amount,
        }

    # 2. Run the actual business logic
    result = run_ai_query(prompt)

    # 3. Track the usage event (non-blocking, buffered)
    settle.events.track(
        user_id=user_id,
        event_type="AI_QUERY",
        metadata={"prompt_length": len(prompt)}
    )

    return {"result": result}
```

### Asynchronous (FastAPI)

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from settlesettle import AsyncSettleSettle, InsufficientCreditsError

# Initialize async client
settle = AsyncSettleSettle()

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    # Flush buffered events and close HTTP connections on shutdown
    await settle.destroy()

app = FastAPI(lifespan=lifespan)

@app.post("/query")
async def query(user_id: str, prompt: str):
    try:
        await settle.wallet.debit(user_id, amount=10, description="AI Query")
    except InsufficientCreditsError as e:
        raise HTTPException(
            status_code=402,
            detail={
                "error": "insufficient_credits",
                "current_balance": e.current_balance,
                "requested": e.requested_amount,
            }
        )

    result = await run_ai_query(prompt)
    
    # Non-blocking event tracking
    settle.events.track(user_id, "AI_QUERY")
    
    return {"result": result}
```

### Context Manager (Scripts & Cron Jobs)

```python
from settlesettle import SettleSettle

# Context manager guarantees events are flushed and resources freed on exit
with SettleSettle() as settle:
    balance = settle.wallet.get_balance("user_123")
    print(f"Credits remaining: {balance.balance}")
```

---

## Error Handling

All SDK exceptions inherit from `SettleSettleError`:

```python
from settlesettle import (
    SettleSettleError,
    AuthenticationError,
    InsufficientCreditsError,
    ValidationError,
    RateLimitError,
)

try:
    settle.wallet.debit("user_123", amount=100)
except InsufficientCreditsError as e:
    # Trigger payment modal or display rewarded ad slot
    pass
except ValidationError as e:
    # Invalid request inputs
    print(f"Validation failed: {e.fields}")
except AuthenticationError:
    # Invalid API key
    pass
except RateLimitError as e:
    # Back off
    pass
except SettleSettleError as e:
    # Catch-all
    pass
```

---

## Development and Testing

1. Clone the repository and install development dependencies in editable mode:
   ```bash
   pip install -e ".[dev]"
   ```

2. Run tests with `pytest`:
   ```bash
   pytest
   ```

3. Run linting & formatting with `ruff`:
   ```bash
   ruff check settlesettle/
   ruff format settlesettle/
   ```

4. Run type verification with `mypy`:
   ```bash
   mypy settlesettle/
   ```

## License

MIT
