# {{ package_name }} - AI Assistant Documentation

Generated: {{ timestamp }}
API Version: {{ api_version }}

## Overview

This is a generated Swift client for Centrifugo RPC communication.
It provides type-safe access to server-side RPC methods.

## Architecture

### Components

1. **CentrifugoRPCClient** (`RPCClient.swift`)
   - Low-level WebSocket communication
   - Correlation ID pattern for RPC over pub/sub
   - Connection management
   - Timeout handling

2. **APIClient** (`APIClient.swift`)
   - High-level typed API wrapper
   - Generated methods for each RPC endpoint
   - Delegates to CentrifugoRPCClient

3. **Types** (`Types.swift`)
   - Codable request/response models
   - Generated from Pydantic models

4. **AnyCodable** (`AnyCodable.swift`)
   - Type-erased JSON handling
   - Used for dynamic payloads

### Communication Pattern

```
Client → publish to "rpc.requests" → Centrifugo → Server
Server → publish to "user#userId" → Centrifugo → Client
```

## Available RPC Methods

{% for method in methods %}
### `{{ method.swift_name }}`

- **RPC Name:** `{{ method.rpc_name }}`
- **Parameters:** `{{ method.param_type }}`
- **Returns:** `{{ method.return_type }}`
- **Fire-and-forget:** {{ "Yes" if method.no_wait else "No" }}
- **Description:** {{ method.docstring }}

{% endfor %}

## Available Types

{% for model in models %}
- `{{ model }}`
{% endfor %}

## Usage Examples

### Basic Connection

```swift
import {{ package_name }}

let api = try APIClient(
    url: "ws://localhost:8000/connection/websocket",
    token: "jwt-token",
    userId: "user-123"
)

try await api.connect()
defer { Task { await api.disconnect() } }
```

### Making RPC Calls

```swift
{% if methods %}
{% set method = methods[0] %}
// {{ method.docstring }}
let result = try await api.{{ method.swift_name }}(params: {{ method.param_type }}(...))
{% endif %}
```

### Error Handling

```swift
do {
    let result = try await api.someMethod(params: params)
} catch RPCError.timeout {
    // Handle timeout
} catch RPCError.serverError(let code, let message) {
    // Handle server error
} catch {
    // Handle other errors
}
```

## CRITICAL: Authentication

### Token Types (DO NOT CONFUSE!)

| Token Type | Format | Usage |
|------------|--------|-------|
| **Centrifugo JWT** | `eyJhbGciOi...` | WebSocket connection - USE THIS! |
| CLI Token | `clit_xxx...` | REST API only - NOT for Centrifugo! |
| JWT Access Token | `eyJ...` | REST API auth header |

### Getting Centrifugo JWT Token

**Option 1: From User Profile (Recommended)**

Django includes Centrifugo token in profile response:

```json
// GET /cfg/accounts/profile/
{
  "centrifugo": {
    "token": "eyJhbGciOi...",      // <-- Use THIS for WebSocket
    "centrifugo_url": "ws://...",
    "expires_at": "2025-...",
    "channels": ["user#4"]
  }
}
```

**Option 2: Dedicated Endpoint**

```
GET /cfg/centrifugo/auth/token/
Authorization: Bearer <jwt_access_token>
```

### Common Mistake

❌ **WRONG:** Using CLI token for Centrifugo connection
```swift
// BAD - CLI token is NOT a JWT!
let api = try APIClient(
    url: "ws://...",
    token: cliToken,  // clit_xxx format - WRONG!
    userId: "4"
)
// Result: Centrifugo sees user="" (empty), connection rejected
```

✅ **CORRECT:** Using Centrifugo JWT from profile
```swift
// GOOD - Use JWT from profile.centrifugo.token
let api = try APIClient(
    url: profile.centrifugo.centrifugoUrl,
    token: profile.centrifugo.token,  // eyJhbGciOi... format
    userId: String(profile.id)
)
```

## Important Notes for AI Assistants

1. **AUTHENTICATION:** Token MUST be a Centrifugo JWT (from profile or `/cfg/centrifugo/auth/token/`), NOT CLI token!

2. **Thread Safety:** Both `CentrifugoRPCClient` and `APIClient` are Swift actors - all methods are inherently thread-safe.

3. **Async/Await:** All RPC methods are async - always use `await` when calling.

4. **Connection Lifecycle:** Always call `connect()` before making RPC calls, and `disconnect()` when done.

5. **Fire-and-forget Methods:** Methods with `no_wait=True` don't return a response - use `send()` internally.

6. **Type Safety:** All parameters and return types are strongly typed using generated Codable structs.

7. **Error Types:** Use `RPCError` enum for error handling:
   - `.notConnected` - Call `connect()` first
   - `.timeout` - Request exceeded timeout
   - `.serverError(code, message)` - Server returned an error
   - `.encodingError` - Failed to encode request
   - `.decodingError` - Failed to decode response

8. **Debugging:** If Centrifugo server logs show `user: ""`, authentication failed - check token type!

## Regeneration

This code is auto-generated. To regenerate:

```bash
python manage.py generate_centrifugo_clients --output ./sdk --swift
```

Do not manually edit generated files - changes will be lost on regeneration.

---

*Generated by Centrifugo Codegen for Swift*
