# Pixwell Python SDK

Official Python SDK for the [Pixwell Screenshot API](https://pixwell.dev).

## Installation

```bash
pip install pixwell
```

## Quick Start

```python
from pixwell import Pixwell

client = Pixwell(api_key="your-api-key")

# Capture a screenshot
screenshot = client.screenshot(
    url="https://example.com",
    width=1920,
    height=1080,
    format="png"
)

# Save to file
with open("screenshot.png", "wb") as f:
    f.write(screenshot.data)
```

## Async Support

```python
import asyncio
from pixwell import AsyncPixwell

async def main():
    async with AsyncPixwell(api_key="your-api-key") as client:
        screenshot = await client.screenshot(
            url="https://example.com",
            width=1920,
            height=1080
        )
        with open("screenshot.png", "wb") as f:
            f.write(screenshot.data)

asyncio.run(main())
```

## API Reference

### Constructor

```python
client = Pixwell(
    api_key="your-api-key",      # Required: Your API key
    base_url="https://...",       # Optional: API base URL
    timeout=60.0,                 # Optional: Request timeout in seconds
)
```

### Methods

#### `screenshot(**options) -> ScreenshotResponse`

Capture a screenshot of a webpage.

```python
screenshot = client.screenshot(
    url="https://example.com",    # Required: URL to capture
    width=1280,                   # Optional: Viewport width (default: 1280)
    height=720,                   # Optional: Viewport height (default: 720)
    full_page=False,              # Optional: Capture full page (default: False)
    format="png",                 # Optional: 'png', 'jpeg', 'webp' (default: 'png')
    quality=80,                   # Optional: Image quality 1-100 (default: 80)
    mobile=False,                 # Optional: Emulate mobile (default: False)
    dark_mode=False,              # Optional: Enable dark mode (default: False)
    delay=0,                      # Optional: Wait before capture in ms (max: 10000)
    selector=None,                # Optional: CSS selector to capture
    cache_ttl=0,                  # Optional: Cache TTL in seconds (max: 3600)
)

# Response
screenshot.data          # bytes: Screenshot image data
screenshot.content_type  # str: e.g., "image/png"
screenshot.size          # int: Image size in bytes
screenshot.duration_ms   # int: Capture duration
screenshot.cached        # bool: Whether served from cache
```

#### `batch(urls, **options) -> BatchResponse`

Capture multiple screenshots in a single request.

```python
import base64

batch = client.batch(
    urls=["https://example.com", "https://google.com"],
    width=1280,
    height=720,
    format="png"
)

# Process results
for result in batch.results:
    if result.success:
        image_data = base64.b64decode(result.data)
        with open(f"screenshot-{hash(result.url)}.png", "wb") as f:
            f.write(image_data)
    else:
        print(f"Failed: {result.url} - {result.error_message}")

# Summary
print(f"Succeeded: {batch.summary.succeeded}/{batch.summary.total}")
```

#### `usage() -> UsageResponse`

Get current usage statistics.

```python
usage = client.usage()

print(f"Daily: {usage.daily.used}/{usage.daily.limit}")
print(f"Monthly: {usage.monthly.used}/{usage.monthly.limit}")
print(f"Plan: {usage.plan.name}")
```

## Error Handling

The SDK raises typed exceptions for different failure scenarios:

```python
from pixwell import (
    Pixwell,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    CaptureError,
    NetworkError,
)

try:
    screenshot = client.screenshot(url="https://example.com")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except ValidationError as e:
    print(f"Invalid parameter: {e.message}")
except CaptureError as e:
    print(f"Capture failed: {e.message}")
except NetworkError as e:
    print(f"Network error: {e.message}")
```

## Context Manager

Both sync and async clients support context managers:

```python
# Sync
with Pixwell(api_key="your-api-key") as client:
    screenshot = client.screenshot(url="https://example.com")

# Async
async with AsyncPixwell(api_key="your-api-key") as client:
    screenshot = await client.screenshot(url="https://example.com")
```

## Type Hints

This SDK includes full type hints for IDE support:

```python
from pixwell import ScreenshotOptions, ScreenshotResponse, BatchResponse, UsageResponse
```

## License

MIT
