# Lilith HTTP API Reference

## Overview

The Lilith API provides RESTful endpoints for chat, content, lectures, and audio
services. This document summarizes the key endpoints; for complete
specifications, see `../openapi/openapi.yaml`.

## Base URLs

| Environment | URL                              |
| ----------- | -------------------------------- |
| Production  | `https://api.lilith.app`         |
| Staging     | `https://staging.api.lilith.app` |
| Local       | `http://localhost:8080`          |

## Authentication

All authenticated endpoints require a Bearer token in the Authorization header:

```http
Authorization: Bearer <access_token>
```

### Obtaining Tokens

```http
POST /v1/auth/token
Content-Type: application/json

{
  "grant_type": "password",
  "email": "user@example.com",
  "password": "secure_password"
}
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "refresh_token": "dGhpcyBpcyBhIHJlZnJl...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### Refreshing Tokens

```http
POST /v1/auth/token
Content-Type: application/json

{
  "grant_type": "refresh_token",
  "refresh_token": "dGhpcyBpcyBhIHJlZnJl..."
}
```

## Common Headers

| Header              | Required | Description                              |
| ------------------- | -------- | ---------------------------------------- |
| `Authorization`     | Yes\*    | Bearer token for authenticated endpoints |
| `X-Correlation-ID`  | No       | Trace ID for request correlation         |
| `X-Idempotency-Key` | No       | Ensures idempotent retries               |
| `Accept-Language`   | No       | Preferred response language              |

## Error Responses

All errors follow this format:

```json
{
  "code": "chat.rate_limited",
  "message": "Rate limit exceeded. Please try again later.",
  "details": {
    "retry_after": 60
  },
  "trace_id": "abc123"
}
```

### Common Error Codes

| HTTP Status | Code                | Description              |
| ----------- | ------------------- | ------------------------ |
| 400         | `*.invalid_request` | Malformed request        |
| 401         | `auth.unauthorized` | Missing or invalid token |
| 403         | `auth.forbidden`    | Insufficient permissions |
| 404         | `*.not_found`       | Resource not found       |
| 429         | `*.rate_limited`    | Too many requests        |
| 500         | `*.internal_error`  | Server error             |

---

## Chat API

### Create Chat Message

Start or continue a conversation with an AI persona.

```http
POST /v1/chat
Authorization: Bearer <token>
Content-Type: application/json

{
  "conversation_id": "uuid",          // Optional, creates new if omitted
  "persona": "zen_master",
  "input": {
    "text": "How do I quiet my mind?",
    "audio": null                     // Base64 audio for voice input
  },
  "mode": "text",                     // "text" or "voice"
  "options": {
    "cite": true,                     // Include citations
    "depth": "practical",             // "practical" or "scholarly"
    "stream": true                    // SSE streaming
  }
}
```

**Streaming Response (SSE):**

```
event: token
data: {"text":"The"}

event: token
data: {"text":" key"}

event: citation
data: {"source":"Shunryu Suzuki","confidence":0.92}

event: done
data: {"message_id":"uuid","latency_ms":1834}
```

**Non-Streaming Response:**

```json
{
  "conversation_id": "uuid",
  "message_id": "uuid",
  "text": "The key to quieting the mind...",
  "citations": [
    {
      "text": "In the beginner's mind...",
      "source": "Zen Mind, Beginner's Mind",
      "confidence": 0.92
    }
  ],
  "audio_url": "https://cdn.../audio.opus",
  "latency_ms": 1834
}
```

### Get Conversation

Retrieve conversation history.

```http
GET /v1/conversations/{conversation_id}
Authorization: Bearer <token>
```

**Response:**

```json
{
  "id": "uuid",
  "persona": "zen_master",
  "messages": [
    {
      "id": "uuid",
      "role": "user",
      "text": "How do I quiet my mind?",
      "created_at": "2025-01-15T10:30:00Z"
    },
    {
      "id": "uuid",
      "role": "assistant",
      "text": "The key to quieting the mind...",
      "citations": [...],
      "created_at": "2025-01-15T10:30:02Z"
    }
  ],
  "created_at": "2025-01-15T10:30:00Z"
}
```

### List Conversations

```http
GET /v1/conversations?limit=20&offset=0
Authorization: Bearer <token>
```

---

## Lecture API

### Generate Lecture

Request an AI-generated lecture on a topic.

```http
POST /v1/lectures
Authorization: Bearer <token>
Content-Type: application/json

{
  "topic": "The concept of non-self in Buddhism",
  "duration_min": 10,
  "tradition": ["buddhism", "zen"],
  "lang": "en-US",
  "voice": "calm_female_1",
  "outline_level": "detailed",
  "include_citations": true
}
```

**Response:**

```json
{
  "lecture_id": "lec_abc123",
  "status": "generating",
  "estimated_duration_ms": 600000,
  "stream_url": "https://cdn.../stream.m3u8",
  "transcript_url": "https://cdn.../transcript.json",
  "created_at": "2025-01-15T10:30:00Z"
}
```

### Get Lecture Status

```http
GET /v1/lectures/{lecture_id}
Authorization: Bearer <token>
```

**Response:**

```json
{
  "lecture_id": "lec_abc123",
  "status": "ready",
  "progress_pct": 100,
  "duration_ms": 598000,
  "stream_url": "https://cdn.../stream.m3u8",
  "transcript_url": "https://cdn.../transcript.json",
  "citations": [...],
  "created_at": "2025-01-15T10:30:00Z",
  "completed_at": "2025-01-15T10:32:00Z"
}
```

---

## TTS API

### Synthesize Speech

Convert text or SSML to audio.

```http
POST /v1/tts:synthesize
Authorization: Bearer <token>
Content-Type: application/json

{
  "voice_id": "calm_female_1",
  "ssml": "<speak><prosody rate='90%'>Hello world</prosody></speak>",
  "format": "opus",
  "stream": true
}
```

**Streaming Response:** Binary audio stream

**Non-Streaming Response:**

```json
{
  "audio_url": "https://cdn.../audio.opus",
  "duration_ms": 1500,
  "format": "opus"
}
```

### List Voices

```http
GET /v1/tts/voices
```

**Response:**

```json
{
  "voices": [
    {
      "id": "calm_female_1",
      "name": "Serene",
      "gender": "female",
      "language": "en-US",
      "style": "calm",
      "sample_url": "https://cdn.../sample.opus"
    }
  ]
}
```

---

## Content API

### List Content

```http
GET /v1/content?type=meditation&tradition=zen&limit=20
Authorization: Bearer <token>
```

**Response:**

```json
{
  "items": [
    {
      "id": "uuid",
      "type": "meditation",
      "title": "Breath Awareness",
      "duration_min": 10,
      "tradition": "zen",
      "thumbnail_url": "https://cdn.../thumb.jpg"
    }
  ],
  "total": 150,
  "offset": 0,
  "limit": 20
}
```

### Get Content Detail

```http
GET /v1/content/{content_id}
Authorization: Bearer <token>
```

### Download Content (Offline)

```http
GET /v1/content/{content_id}/download
Authorization: Bearer <token>
```

**Response:**

```json
{
  "download_url": "https://cdn.../encrypted.zip",
  "license_token": "eyJ...",
  "expires_at": "2025-01-22T10:30:00Z",
  "checksum": "sha256:abc123..."
}
```

---

## User API

### Get Profile

```http
GET /v1/users/me
Authorization: Bearer <token>
```

**Response:**

```json
{
  "id": "uuid",
  "display_name": "Seeker",
  "locale": "en-US",
  "timezone": "America/New_York",
  "preferences": {
    "preferred_personas": ["zen_master", "stoic_mentor"],
    "preferred_voices": ["calm_female_1"],
    "citation_mode": true,
    "depth": "practical"
  },
  "created_at": "2024-06-01T00:00:00Z"
}
```

### Update Preferences

```http
PATCH /v1/users/me/preferences
Authorization: Bearer <token>
Content-Type: application/json

{
  "citation_mode": false,
  "depth": "scholarly"
}
```

---

## Progress API

### Get Progress

```http
GET /v1/progress
Authorization: Bearer <token>
```

**Response:**

```json
{
  "meditation_minutes": 1250,
  "courses_completed": 3,
  "current_streak_days": 14,
  "longest_streak_days": 30,
  "content_progress": [
    {
      "content_id": "uuid",
      "progress_pct": 75,
      "last_position_ms": 450000,
      "updated_at": "2025-01-15T10:00:00Z"
    }
  ]
}
```

### Update Progress

```http
POST /v1/progress
Authorization: Bearer <token>
Content-Type: application/json

{
  "content_id": "uuid",
  "progress_pct": 80,
  "position_ms": 480000
}
```

---

## Notification API

### Register Device

```http
POST /v1/notifications/devices
Authorization: Bearer <token>
Content-Type: application/json

{
  "platform": "ios",
  "token": "device_push_token"
}
```

### Update Preferences

```http
PATCH /v1/notifications/preferences
Authorization: Bearer <token>
Content-Type: application/json

{
  "daily_reminder": true,
  "reminder_time": "08:00",
  "quiet_hours_start": "22:00",
  "quiet_hours_end": "07:00"
}
```

---

## Health & Monitoring

### Health Check

```http
GET /v1/health
```

**Response:**

```json
{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2025-01-15T10:30:00Z"
}
```

### Metrics

```http
GET /v1/metrics
```

Returns Prometheus-formatted metrics.

---

## Rate Limits

| Endpoint             | Limit | Window   |
| -------------------- | ----- | -------- |
| `/v1/chat`           | 60    | 1 minute |
| `/v1/lectures`       | 10    | 1 minute |
| `/v1/tts:synthesize` | 30    | 1 minute |
| Other endpoints      | 100   | 1 minute |

Rate limit headers are included in responses:

- `X-RateLimit-Limit`: Maximum requests
- `X-RateLimit-Remaining`: Remaining requests
- `X-RateLimit-Reset`: Reset timestamp

---

## WebSocket API

### Real-Time Chat

Connect to `/ws` for real-time chat and voice:

```javascript
const ws = new WebSocket('wss://api.lilith.app/ws');

ws.send(
  JSON.stringify({
    type: 'auth',
    token: 'Bearer ...',
  })
);

ws.send(
  JSON.stringify({
    type: 'chat',
    payload: {
      persona: 'zen_master',
      input: { text: 'Hello' },
    },
  })
);

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === 'token') {
    // Streaming token
  }
};
```

---

## SDK Examples

### TypeScript

```typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY
});

// Chat
const response = await client.chat({
  persona: 'zen_master',
  message: 'How do I meditate?',
  options: { cite: true }
});

// Stream chat
for await (const token of client.chatStream({...})) {
  console.log(token.text);
}
```

### Python

```python
from lilith import LilithClient

client = LilithClient(api_key=os.environ['LILITH_API_KEY'])

# Chat
response = client.chat(
    persona='zen_master',
    message='How do I meditate?',
    options={'cite': True}
)

# Stream chat
for token in client.chat_stream(...):
    print(token.text, end='')
```

---

## Related Documentation

- **OpenAPI Specification**: `../openapi/openapi.yaml`
- **Authentication Guide**: `../../docs/guides/authentication.md`
- **SDK Documentation**: `../../docs/sdk-guides/`
