# @lilith/partner-sdk

Official TypeScript/JavaScript SDK for the Lilith Partner API.

## Installation

```bash
npm install @lilith/partner-sdk node-fetch
```

## Quick Start

```typescript
import { LilithPartnerClient } from '@lilith/partner-sdk';

// Initialize the client
const client = new LilithPartnerClient({
  apiKey: 'lilith_live_your_api_key_here',
  baseURL: 'https://api.lilith.example.com/partner', // optional
});

// Generate AI chat response
const chatResponse = await client.chat({
  message: 'What is mindfulness?',
  persona: 'zen_master',
});
console.log(chatResponse.response);

// Synthesize speech
const ttsResponse = await client.synthesizeSpeech({
  text: 'Welcome to your mindfulness practice',
  voice_id: 'calm_female_01',
  format: 'opus',
});
console.log(`Audio URL: ${ttsResponse.audio_url}`);
```

## Partner Registration

```typescript
// Register a new partner account
const registration = await client.registerPartner({
  organization_name: 'My Company',
  contact_email: 'contact@mycompany.com',
  contact_name: 'John Doe',
  website_url: 'https://mycompany.com',
  use_case_description: 'Building a meditation app',
  tier_request: 'professional',
});

console.log(`Partner ID: ${registration.partner_id}`);
console.log(`Status: ${registration.status}`);
```

## API Key Management

```typescript
// Generate a new API key (after partner approval)
const apiKey = await client.createAPIKey(partnerId, {
  name: 'Production API Key',
  description: 'Main API key for production use',
  scopes: ['chat', 'content', 'tts'],
  environment: 'production',
});

console.log(`API Key: ${apiKey.api_key}`);
console.log(`Rate Limits: ${JSON.stringify(apiKey.rate_limits)}`);

// List all API keys
const keys = await client.listAPIKeys(partnerId);
console.log(`Total keys: ${keys.total_keys}`);
```

## Chat API

```typescript
const response = await client.chat({
  message: 'Teach me about meditation',
  persona: 'zen_master',
  user_id: 'optional-user-id',
});

console.log(response.response);
console.log(`Processing time: ${response.processing_time_ms}ms`);
```

## Content API

```typescript
// Retrieve content
const content = await client.getContent();
console.log(`Found ${content.total_count} items`);

content.content.forEach((item) => {
  console.log(`${item.title} (${item.type}, ${item.duration_minutes}min)`);
});
```

## Text-to-Speech API

```typescript
const audio = await client.synthesizeSpeech({
  text: 'Close your eyes and breathe deeply',
  voice_id: 'calm_female_01',
  format: 'opus',
});

console.log(`Audio URL: ${audio.audio_url}`);
console.log(`Duration: ${audio.duration_sec} seconds`);
```

## Webhooks

```typescript
const webhook = await client.createWebhook(partnerId, {
  url: 'https://myapp.com/webhooks/lilith',
  events: ['chat.completed', 'tts.generated'],
  description: 'Main webhook endpoint',
});

console.log(`Webhook ID: ${webhook.subscription_id}`);
console.log(`Secret: ${webhook.secret}`); // Use for signature verification
```

## Analytics

```typescript
// Get partner usage analytics
const analytics = await client.getAnalytics(partnerId, {
  timeframe: 'week',
  includeDetails: true,
});

console.log(`Total requests: ${analytics.summary.total_requests}`);
console.log(`Active API keys: ${analytics.summary.active_api_keys}`);
console.log(`Error rate: ${analytics.summary.error_rate * 100}%`);

// Endpoint-specific usage
Object.entries(analytics.usage_by_endpoint).forEach(([endpoint, stats]) => {
  console.log(`${endpoint}: ${stats.requests} requests (${stats.percentage}%)`);
});
```

## Error Handling

```typescript
import { PartnerAPIClientError } from '@lilith/partner-sdk';

try {
  const response = await client.chat({
    message: 'Hello',
    persona: 'zen_master',
  });
} catch (error) {
  if (error instanceof PartnerAPIClientError) {
    if (error.isRateLimitError()) {
      console.error(
        `Rate limit exceeded. Retry after ${error.getRetryAfter()} seconds`
      );
    } else if (error.isAuthError()) {
      console.error('Authentication error:', error.message);
    } else if (error.isScopeError()) {
      console.error('Insufficient scope for this operation');
    } else {
      console.error(`API error [${error.errorCode}]: ${error.message}`);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## Advanced Usage

### Custom Base URL

```typescript
const client = new LilithPartnerClient({
  apiKey: 'your_api_key',
  baseURL: 'https://custom-api.example.com',
  timeout: 60000, // 60 seconds
});
```

### Bearer Token Authentication

The SDK automatically uses the provided `apiKey` with the `X-API-Key` header. To
use Bearer token authentication, you can pass the token as the `apiKey`:

```typescript
const client = new LilithPartnerClient({
  apiKey: 'your_token_here',
});
// The client will use: Authorization: Bearer your_token_here
```

## Rate Limiting

The Partner API enforces rate limits based on your tier:

- **Starter**: 50 req/min, 500 req/hour, 5,000 req/day
- **Professional**: 200 req/min, 5,000 req/hour, 50,000 req/day
- **Enterprise**: 1,000 req/min, 25,000 req/hour, 500,000 req/day

Rate limit errors include a `retry_after` value indicating when you can retry
the request.

## TypeScript Support

This SDK is written in TypeScript and includes full type definitions:

```typescript
import type {
  ChatRequest,
  ChatResponse,
  PartnerAnalytics,
  RateLimits,
} from '@lilith/partner-sdk';

const request: ChatRequest = {
  message: 'Hello',
  persona: 'zen_master',
};

const response: ChatResponse = await client.chat(request);
```

## API Reference

### Client Methods

- `registerPartner(request)` - Register new partner account
- `approvePartner(partnerId, request)` - Approve partner (admin)
- `createAPIKey(partnerId, request)` - Generate API key
- `listAPIKeys(partnerId)` - List partner's API keys
- `chat(request)` - Generate AI chat response
- `getContent(query?)` - Retrieve content
- `synthesizeSpeech(request)` - Text-to-speech synthesis
- `getAnalytics(partnerId, options?)` - Get usage analytics
- `getEndpointMetrics(timeframe?)` - Get endpoint metrics (admin)
- `createWebhook(partnerId, request)` - Create webhook subscription
- `getDocumentation()` - Get OpenAPI documentation
- `getTiers()` - Get tier information
- `checkHealth()` - Check API health

### Error Methods

- `isRateLimitError()` - Check if rate limit error
- `isAuthError()` - Check if authentication error
- `isScopeError()` - Check if scope/permission error
- `getRetryAfter()` - Get retry-after value for rate limits

## License

MIT

## Support

For support, please contact partners@lilith.example.com or visit
https://docs.lilith.example.com
