# Lilith Partner API

Comprehensive Partner API for third-party integrations with the Lilith AI Wisdom Platform.

## Overview

The Partner API provides programmatic access to Lilith's core capabilities:
- **AI-powered chat** with wisdom personas (Zen Master, Stoic Mentor, Sufi Guide)
- **Content catalog** access for lectures, meditations, and courses
- **Text-to-speech synthesis** with wisdom-optimized voices
- **Usage analytics** and reporting
- **Webhook events** for real-time notifications

## Quick Start

### 1. Register Partner Account

```bash
curl -X POST https://api.lilith.example.com/v1/partners/register \
  -H "Content-Type: application/json" \
  -d '{
    "organization_name": "Your Company",
    "contact_email": "dev@yourcompany.com",
    "contact_name": "John Doe",
    "website_url": "https://yourcompany.com",
    "use_case_description": "Building a meditation app",
    "tier_request": "professional"
  }'
```

**Response:**
```json
{
  "partner_id": "partner-123",
  "status": "pending_approval",
  "tier": "starter",
  "estimated_approval_time": "2-3 business days"
}
```

### 2. Generate API Key (After Approval)

```bash
curl -X POST https://api.lilith.example.com/v1/partners/partner-123/api-keys \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production API Key",
    "scopes": ["chat", "content", "tts"],
    "environment": "production"
  }'
```

**Response:**
```json
{
  "key_id": "key-456",
  "api_key": "lilith_live_a1b2c3d4e5f6...",
  "rate_limits": {
    "requests_per_minute": 200,
    "requests_per_hour": 5000,
    "requests_per_day": 50000
  }
}
```

### 3. Make API Request

```bash
curl -X POST https://api.lilith.example.com/v1/partner/chat \
  -H "X-API-Key: lilith_live_a1b2c3d4e5f6..." \
  -H "Content-Type: application/json" \
  -d '{
    "message": "How can I find inner peace?",
    "persona": "zen_master"
  }'
```

**Response:**
```json
{
  "response": "Inner peace begins with accepting that chaos is part of life's natural flow...",
  "persona": "zen_master",
  "citations": [],
  "processing_time_ms": 250
}
```

## Authentication

All API requests require authentication via API key:

**Option 1: X-API-Key Header** (Recommended)
```bash
curl -H "X-API-Key: lilith_live_..." https://api.lilith.example.com/v1/partner/content
```

**Option 2: Authorization Bearer Token**
```bash
curl -H "Authorization: Bearer lilith_live_..." https://api.lilith.example.com/v1/partner/content
```

## Rate Limiting

Rate limits are enforced per API key based on your tier:

| Tier | Requests/Min | Requests/Hour | Requests/Day |
|------|--------------|---------------|--------------|
| **Starter** | 50 | 500 | 5,000 |
| **Professional** | 200 | 5,000 | 50,000 |
| **Enterprise** | 1,000 | 25,000 | 500,000 |

When rate limits are exceeded, you'll receive a `429 Too Many Requests` response:

```json
{
  "code": "partner.rate_limit_exceeded",
  "message": "Rate limit exceeded",
  "retry_after": 60,
  "limit_type": "minute"
}
```

**Best Practices:**
- Implement exponential backoff with jitter
- Monitor usage via analytics endpoint
- Subscribe to `usage.threshold` webhooks (80%, 90%, 100%)
- Cache responses when appropriate

## API Endpoints

### Chat API

Generate AI responses from wisdom personas:

```javascript
const response = await fetch('https://api.lilith.example.com/v1/partner/chat', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.LILITH_API_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    message: 'How can I cultivate mindfulness?',
    persona: 'zen_master',
    user_id: 'user-789' // Optional for conversation tracking
  })
});

const data = await response.json();
console.log(data.response);
```

**Supported Personas:**
- `zen_master` - Zen Buddhist wisdom and mindfulness
- `stoic_mentor` - Stoic philosophy and resilience
- `sufi_guide` - Sufi mysticism and spiritual insights

### Content API

Access the content catalog:

```javascript
const response = await fetch('https://api.lilith.example.com/v1/partner/content?type=meditation&limit=10', {
  headers: {
    'X-API-Key': process.env.LILITH_API_KEY
  }
});

const data = await response.json();
console.log(data.content); // Array of content items
```

**Query Parameters:**
- `type` - Filter by content type: `lecture`, `meditation`, `course`
- `category` - Filter by category
- `limit` - Maximum results (default: 20, max: 100)

### Text-to-Speech API

Convert text to speech:

```javascript
const response = await fetch('https://api.lilith.example.com/v1/partner/tts/synthesize', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.LILITH_API_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    text: 'Welcome to your daily meditation practice',
    voice_id: 'calm_female_01',
    format: 'opus'
  })
});

const data = await response.json();
console.log(data.audio_url); // URL to download audio file
```

**Supported Formats:**
- `opus` - Recommended for streaming (low bandwidth)
- `mp3` - Universal compatibility
- `wav` - Highest quality (large files)

## Usage Analytics

Monitor your API usage:

```javascript
const response = await fetch('https://api.lilith.example.com/v1/partners/partner-123/analytics?timeframe=week&include_details=true', {
  headers: {
    'X-API-Key': process.env.LILITH_API_KEY
  }
});

const analytics = await response.json();
console.log(analytics.summary);
// {
//   total_requests: 12450,
//   active_api_keys: 3,
//   rate_limit_hits: 15,
//   average_response_time_ms: 245,
//   error_rate: 0.02
// }
```

**Analytics Features:**
- Request volume by endpoint
- Response time trends
- Error rate monitoring
- Quota utilization tracking
- Per-key detailed breakdown

## Webhooks

Subscribe to real-time events:

```javascript
const response = await fetch('https://api.lilith.example.com/v1/partners/partner-123/webhooks', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.LILITH_API_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://api.yourapp.com/webhooks/lilith',
    events: ['chat.completed', 'usage.threshold'],
    secret: 'your_webhook_secret',
    description: 'Production webhook'
  })
});
```

**Available Events:**
- `chat.completed` - Chat request completed
- `content.updated` - Content catalog updated
- `usage.threshold` - Usage threshold reached (80%, 90%, 100%)
- `key.expired` - API key expired

**Webhook Security:**
- All webhooks are signed with HMAC-SHA256
- Verify signature using provided secret:

```javascript
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(payload).digest('hex');
  return signature === digest;
}

// Express.js example
app.post('/webhooks/lilith', (req, res) => {
  const signature = req.headers['x-lilith-signature'];
  const isValid = verifyWebhook(JSON.stringify(req.body), signature, process.env.WEBHOOK_SECRET);

  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook event
  console.log(req.body.event, req.body.data);
  res.status(200).send('OK');
});
```

## Error Handling

The API uses standard HTTP status codes and returns errors in a consistent format:

```json
{
  "code": "partner.error_code",
  "message": "Human-readable error message"
}
```

**Common Error Codes:**

| Status | Code | Description |
|--------|------|-------------|
| 400 | `partner.bad_request` | Invalid request parameters |
| 401 | `partner.missing_api_key` | API key not provided |
| 401 | `partner.invalid_api_key` | Invalid API key |
| 401 | `partner.key_expired` | API key has expired |
| 403 | `partner.not_approved` | Partner account not approved |
| 403 | `partner.insufficient_scope` | API key lacks required scope |
| 404 | `partner.not_found` | Resource not found |
| 429 | `partner.rate_limit_exceeded` | Rate limit exceeded |
| 500 | `partner.server_error` | Internal server error |

**Error Handling Best Practices:**

```javascript
async function makeApiRequest(endpoint, options) {
  try {
    const response = await fetch(endpoint, options);

    if (!response.ok) {
      const error = await response.json();

      // Handle rate limiting
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        console.log(`Rate limited. Retry after ${retryAfter} seconds`);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        return makeApiRequest(endpoint, options); // Retry
      }

      // Handle other errors
      throw new Error(`API Error: ${error.code} - ${error.message}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API request failed:', error);
    throw error;
  }
}
```

## Partner Tiers

### Starter (Free)
- **Rate Limits:** 50 req/min, 500 req/hour, 5,000 req/day
- **Features:** Basic chat API, Content access, Email support
- **Best For:** Development and small-scale usage

### Professional ($299/month)
- **Rate Limits:** 200 req/min, 5,000 req/hour, 50,000 req/day
- **Features:** All Starter features + TTS API, Webhooks, Priority support
- **Best For:** Production applications and growing businesses

### Enterprise (Custom Pricing)
- **Rate Limits:** 1,000 req/min, 25,000 req/hour, 500,000 req/day
- **Features:** All Professional features + Custom rate limits, SLA guarantees, Dedicated support
- **Best For:** Large-scale applications with custom requirements

Get tier information:
```bash
curl https://api.lilith.example.com/v1/tiers
```

## OpenAPI Specification

Full OpenAPI 3.1 specification available at:
- **File:** [`openapi.yaml`](./openapi.yaml)
- **Endpoint:** `GET https://api.lilith.example.com/v1/docs`

## SDK Support

Official SDKs available:
- **TypeScript/JavaScript** - `@lilith/partner-sdk`
- **Python** - `lilith-partner-sdk`

Coming soon:
- Ruby
- Go
- Java

## Development

### Running Locally

```bash
# Install dependencies
npm install

# Set environment variables
export JWT_SECRET="your-secret"
export REDIS_HOST="localhost"
export REDIS_PORT=6379

# Start server
npm start

# Development mode with auto-reload
npm run dev
```

### Testing

```bash
# Run tests
npm test

# Run with coverage
npm run test:coverage
```

### API Documentation

Generate and serve OpenAPI documentation:

```bash
# Validate OpenAPI spec
npx @redocly/cli lint openapi.yaml

# Generate SDK
npx @openapitools/openapi-generator-cli generate \
  -i openapi.yaml \
  -g typescript-fetch \
  -o ./sdk/typescript

# Serve interactive docs
npx @redocly/cli preview-docs openapi.yaml
```

## Support

- **Documentation:** https://partners.lilith.example.com/docs
- **Email:** partners@lilith.example.com
- **Status Page:** https://status.lilith.example.com

## License

Proprietary - See [Terms of Service](https://lilith.example.com/partner-api-terms)
