# Crowd Control API Reference

`@aphrodite/crowd-control` — Viewer interaction system connecting streaming
platforms to in-game effects with a coin economy, effect queue, approval
workflow, and rate limiting.

---

## Architecture

```
Streaming Platform (Twitch, YouTube, TikTok, etc.)
     │
     ├──► Connection Manager ──► Authentication ──► Platform Events
     │
     ├──► Coin Economy ──► Wallet Management ──► Earning / Spending
     │
     ├──► Effect System ──► Queue ──► Approval ──► Execution
     │
     └──► Rate Limiter ──► Per-Viewer / Global Limits
```

---

## Platform Support

### Stream Platforms

| Platform  | Protocol              |
| --------- | --------------------- |
| `Twitch`  | PubSub WebSocket      |
| `YouTube` | PubSub WebSocket      |
| `TikTok`  | PubSub WebSocket      |
| `Discord` | PubSub WebSocket      |
| `Kick`    | PubSub WebSocket      |
| `Custom`  | SimpleTCP / REST Poll |

### Connection Protocols

| Protocol    | Description                 |
| ----------- | --------------------------- |
| `SimpleTCP` | Basic TCP socket connection |
| `PubSub`    | WebSocket pub/sub (primary) |
| `REST Poll` | HTTP polling fallback       |

### Connection States

```
Disconnected → Connecting → Connected → Authenticated → Active
                                                          ↓
                                                        Paused
                    ↑                                     ↓
              Reconnecting ←──── Error ←──────────────────┘
```

| State           | Description                    |
| --------------- | ------------------------------ |
| `Disconnected`  | No connection                  |
| `Connecting`    | Establishing connection        |
| `Connected`     | Socket open, not authenticated |
| `Authenticated` | Identity confirmed             |
| `Active`        | Fully operational              |
| `Paused`        | Temporarily suspended          |
| `Reconnecting`  | Attempting reconnection        |
| `Error`         | Connection error               |

---

## Viewer Identity

```typescript
interface ViewerIdentity {
  userId: string;
  displayName: string;
  platform: StreamPlatform;
  permission: ViewerPermission;
  subscriberTier: number; // 0 = non-sub, 1–3
  isModerator: boolean;
  isVip: boolean;
}
```

### Viewer Permissions

| Permission    | Level | Who qualifies      |
| ------------- | ----- | ------------------ |
| `Anyone`      | 0     | All viewers        |
| `Follower`    | 1     | Followers          |
| `Subscriber`  | 2     | Active subscribers |
| `VIP`         | 3     | VIP status holders |
| `Moderator`   | 4     | Channel moderators |
| `Broadcaster` | 5     | Channel owner      |

---

## Coin Economy

### CoinWallet

```typescript
interface CoinWallet {
  balance: number;
  totalEarned: number;
  totalSpent: number;
  earnMultiplier: number; // default: 1.0 (2.0 for subscribers)
}
```

### Earning Rates

| Activity     | Coins earned      | Limit            |
| ------------ | ----------------- | ---------------- |
| Watching     | 10 coins/min      | Continuous       |
| Chat message | 2 coins/msg       | 20 coins/min max |
| Subscription | 500 coins         | One-time per sub |
| Gifted sub   | 200 coins/gift    | Per gift         |
| Bits cheered | 50 coins/100 bits | Per cheer        |

Subscribers earn at **2× rate** on all coin sources.

### CoinTransaction

```typescript
interface CoinTransaction {
  id: string;
  userId: string;
  amount: number; // positive = earn, negative = spend
  reason: string;
  effectId: string | null;
  timestamp: number;
}
```

---

## Effect System

### EffectDefinition

```typescript
interface EffectDefinition {
  id: string;
  name: string;
  description: string;
  category: EffectCategory;
  rarity: EffectRarity;
  cost: number; // coins
  cooldownMs: number;
  durationMs: number;
  minPermission: ViewerPermission;
  params: Record<string, unknown>;
  enabled: boolean;
  visibleInMenu: boolean;
  tags: string[];
}
```

### Effect Categories

| Category      | Description                     |
| ------------- | ------------------------------- |
| `Visual`      | Screen-wide visual effects      |
| `Audio`       | Sound effects, music changes    |
| `Gameplay`    | Power-ups, obstacles            |
| `Character`   | Character modifications         |
| `Environment` | Weather, lighting changes       |
| `Social`      | Crowd-visible notifications     |
| `Combo`       | Multi-category compound effects |

### Effect Rarity

| Rarity      | Base Cost | Description       |
| ----------- | --------- | ----------------- |
| `Common`    | 50        | Readily available |
| `Uncommon`  | 150       | Moderate rarity   |
| `Rare`      | 500       | Infrequent        |
| `Epic`      | 1000      | Rare and powerful |
| `Legendary` | 2500      | Extremely rare    |

### EffectInstance

```typescript
interface EffectInstance {
  id: string;
  effectId: string;
  requestedBy: ViewerIdentity;
  status: EffectStatus;
  queuePosition: number;
  requestedAt: number;
  startedAt: number | null;
  completedAt: number | null;
  cancelledAt: number | null;
  error: string | null;
}
```

### Effect Status Lifecycle

```
Queued → Active → Completed
  ↓        ↓
Cancelled  Failed
  ↓
Refunded
  ↓
Expired
```

| Status      | Description                |
| ----------- | -------------------------- |
| `Queued`    | Waiting in effect queue    |
| `Active`    | Currently executing        |
| `Completed` | Finished successfully      |
| `Cancelled` | Cancelled before execution |
| `Failed`    | Error during execution     |
| `Refunded`  | Coins returned to viewer   |
| `Expired`   | Timed out in queue         |

### Effect Priority

| Priority   | Value | Use case          |
| ---------- | ----- | ----------------- |
| `Low`      | 0     | Common effects    |
| `Normal`   | 1     | Standard effects  |
| `Medium`   | 2     | Uncommon effects  |
| `High`     | 3     | Rare/epic effects |
| `Critical` | 4     | Legendary effects |

---

## Queue Management

### Queue Configuration

| Setting          | Default | Description                  |
| ---------------- | ------- | ---------------------------- |
| `maxQueueSize`   | 50      | Maximum queued effects       |
| `maxConcurrent`  | 3       | Simultaneous active effects  |
| `minDelayMs`     | 500     | Minimum time between effects |
| `queueTimeoutMs` | 300000  | Max time in queue (5 min)    |

### Processing

Effects are processed in priority order. Same-priority effects process FIFO.
When the queue is full, new requests are rejected and coins refunded.

---

## Rate Limiting

| Limit                 | Default        | Scope                 |
| --------------------- | -------------- | --------------------- |
| Global rate limit     | 10 effects/min | All viewers           |
| Per-viewer rate limit | 3 effects/min  | Single viewer         |
| Burst allowance       | varies         | Short burst tolerance |

When a rate limit is hit, the `rateLimitHit` event fires with cooldown
information.

---

## Configuration

### CrowdControlConfig

```typescript
interface CrowdControlConfig {
  // Connection
  platform: StreamPlatform;
  connectionProtocol: ConnectionProtocol;
  reconnectIntervalMs: number;
  maxReconnectAttempts: number;

  // Queue
  maxQueueSize: number; // 50
  maxConcurrentEffects: number; // 3
  minEffectDelayMs: number; // 500
  queueTimeoutMs: number; // 300000

  // Economy
  coinsPerMinuteWatching: number; // 10
  coinsPerChatMessage: number; // 2
  maxChatCoinsPerMinute: number; // 20
  coinsPerSubscription: number; // 500
  coinsPerGiftedSub: number; // 200
  coinsPerHundredBits: number; // 50
  subscriberCoinMultiplier: number; // 2.0

  // Rate limiting
  globalRateLimitPerMinute: number; // 10
  perViewerRateLimitPerMinute: number; // 3

  // Approval
  requireApproval: boolean; // false
  autoApprovePermission: ViewerPermission; // Anyone
}
```

---

## Events

### Connection Events

| Event                    | Payload                | When                        |
| ------------------------ | ---------------------- | --------------------------- |
| `connectionStateChanged` | `{ prev, next }`       | Connection state transition |
| `platformConnected`      | `{ platform }`         | Connected to platform       |
| `platformDisconnected`   | `{ platform, reason }` | Disconnected                |

### Effect Events

| Event             | Payload                | When                    |
| ----------------- | ---------------------- | ----------------------- |
| `effectRequested` | `{ instance, viewer }` | Viewer requests effect  |
| `effectStarted`   | `{ instance }`         | Effect begins executing |
| `effectCompleted` | `{ instance }`         | Effect finishes         |
| `effectCancelled` | `{ instance, reason }` | Effect cancelled        |
| `effectFailed`    | `{ instance, error }`  | Effect failed           |
| `effectRefunded`  | `{ instance, amount }` | Coins refunded          |

### Economy Events

| Event          | Payload                              | When                |
| -------------- | ------------------------------------ | ------------------- |
| `coinsChanged` | `{ userId, balance, delta, reason }` | Coin balance change |
| `rateLimitHit` | `{ userId, limit, cooldownMs }`      | Rate limit reached  |

### Queue Events

| Event       | Payload                   | When              |
| ----------- | ------------------------- | ----------------- |
| `queueFull` | `{ queueSize, rejected }` | Queue at capacity |

### Chat Events

| Event             | Payload                       | When                  |
| ----------------- | ----------------------------- | --------------------- |
| `messageReceived` | `{ userId, message, badges }` | Chat message received |

### Error Events

| Event   | Payload                      | When      |
| ------- | ---------------------------- | --------- |
| `error` | `{ code, message, details }` | Any error |

---

## Integration with Game Event Bus

The crowd control system emits `social.*` events on the game event bus:

| Game Event              | Crowd Control Source |
| ----------------------- | -------------------- |
| `social.tip`            | Coin spend / tip     |
| `social.chat-message`   | Chat message         |
| `social.follow`         | New follower         |
| `social.subscribe`      | New subscriber       |
| `social.raid`           | Incoming raid        |
| `social.crowd-reaction` | Effect execution     |

This allows all other subsystems (device reactions, music engine, scene
composer, animation triggers) to respond to viewer interactions through the
standard event bus pipeline.
