# Content Recommendation API

This document provides comprehensive documentation for the Lilith Content
Service Recommendation API, including personalized recommendations,
collaborative filtering, user interactions, experiments, and analytics.

## Overview

The Recommendation API provides intelligent content recommendations using:

- **Collaborative Filtering**: User-user and item-item similarity
- **Content-Based Filtering**: Feature similarity and embeddings
- **Hybrid Recommendations**: Combined approach with configurable weights
- **Contextual Signals**: Device, time of day, available time
- **A/B Testing**: Experiment variants with analytics
- **Explainability**: Optional explanations for why content was recommended

---

## Table of Contents

1. [Types and Enums](#types-and-enums)
2. [Recommendation Endpoints](#recommendation-endpoints)
3. [User Interactions](#user-interactions)
4. [User Profiles](#user-profiles)
5. [Feedback](#feedback)
6. [Content Indexing (Admin)](#content-indexing-admin)
7. [Experiments](#experiments)
8. [Analytics](#analytics)
9. [Error Handling](#error-handling)

---

## Types and Enums

### Content Types

| Type         | Description        |
| ------------ | ------------------ |
| `lesson`     | Course lessons     |
| `meditation` | Meditation content |
| `persona`    | AI personas        |
| `course`     | Full courses       |
| `wisdom`     | Wisdom teachings   |

### Recommendation Strategies

| Strategy               | Description                            |
| ---------------------- | -------------------------------------- |
| `user_user`            | Users who liked this also liked...     |
| `item_item`            | Similar items based on co-interactions |
| `matrix_factorization` | Latent factor model                    |
| `embedding_similarity` | Vector similarity                      |
| `tag_overlap`          | Shared tags/categories                 |
| `sequence_next`        | Next in learning path                  |
| `diversity_aware`      | Ensure varied results                  |

### Interaction Types

| Type           | Weight | Description              |
| -------------- | ------ | ------------------------ |
| `view`         | 1.0    | Started viewing          |
| `complete`     | 3.0    | Finished content         |
| `like`         | 2.5    | Explicit positive signal |
| `dislike`      | -2.0   | Explicit negative signal |
| `save`         | 2.0    | Bookmarked for later     |
| `share`        | 1.5    | Shared externally        |
| `rate`         | 2.0    | Rated content            |
| `comment`      | 1.5    | Left feedback            |
| `start`        | 0.5    | Started content          |
| `pause`        | 0.5    | Paused playback          |
| `skip`         | -0.5   | Skipped ahead            |
| `repeat`       | 2.0    | Re-watched/repeated      |
| `search_click` | 1.5    | Clicked from search      |

### Recommendation Scores

Each recommendation includes multiple scoring components:

```json
{
  "relevance": 0.85, // Content match to user
  "popularity": 0.72, // General popularity
  "recency": 0.6, // How recent/fresh
  "diversity": 0.45, // How different from prior recommendations
  "novelty": 0.3, // How new to this user
  "contextMatch": 0.9, // Match to current context
  "final": 0.78 // Weighted combination
}
```

---

## Recommendation Endpoints

### Get Personalized Recommendations (GET)

Retrieve personalized recommendations for a user.

**Endpoint:** `GET /v1/recommendations/:userId`

**Path Parameters:**

| Parameter | Type   | Description     |
| --------- | ------ | --------------- |
| `userId`  | string | User identifier |

**Query Parameters:**

| Parameter          | Type    | Description                                |
| ------------------ | ------- | ------------------------------------------ |
| `types`            | string  | Comma-separated content types              |
| `limit`            | integer | Max results (default: 20, max: 100)        |
| `offset`           | integer | Pagination offset                          |
| `strategy`         | string  | Comma-separated strategies                 |
| `diversity`        | number  | Diversity factor (0-1)                     |
| `novelty`          | number  | Novelty factor (0-1)                       |
| `experimentId`     | string  | A/B test experiment ID                     |
| `explain`          | boolean | Include explanations                       |
| `sessionId`        | string  | Session identifier                         |
| `deviceType`       | string  | `mobile`, `tablet`, `desktop`              |
| `timeOfDay`        | string  | `morning`, `afternoon`, `evening`, `night` |
| `availableMinutes` | integer | Available time in minutes                  |
| `locale`           | string  | Content locale                             |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/recommendations/user_123?types=meditation,lesson&limit=10&explain=true" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "items": [
    {
      "id": "meditation_456",
      "contentType": "meditation",
      "title": "Morning Calm",
      "slug": "morning-calm",
      "description": "Start your day with peace",
      "thumbnailUrl": "https://cdn.lilith.app/thumbs/morning-calm.jpg",
      "durationMinutes": 10,
      "difficulty": "beginner",
      "tags": ["morning", "calm", "beginner"],
      "score": 0.92,
      "scores": {
        "relevance": 0.95,
        "popularity": 0.8,
        "recency": 0.7,
        "diversity": 0.6,
        "novelty": 0.4,
        "contextMatch": 0.9,
        "final": 0.92
      },
      "explanation": {
        "type": "personalized",
        "strategy": "user_user",
        "reason": "Based on your interest in morning meditation practices",
        "factors": [
          {
            "name": "tag_match",
            "weight": 0.3,
            "contribution": 0.27,
            "description": "Matches tags: morning, calm"
          },
          {
            "name": "similar_users",
            "weight": 0.4,
            "contribution": 0.36,
            "description": "85% of similar users enjoyed this"
          }
        ]
      },
      "position": 0
    }
  ],
  "total": 50,
  "requestId": "req_abc123",
  "userId": "user_123",
  "strategy": ["user_user", "content_based"],
  "experimentId": "exp_001",
  "experimentVariant": "variant_a",
  "generatedAt": "2024-01-01T00:00:00.000Z",
  "latencyMs": 45,
  "cached": false
}
```

### Get Personalized Recommendations (POST)

Get recommendations with advanced filtering via request body.

**Endpoint:** `POST /v1/recommendations`

**Request Body:**

| Field                 | Type     | Required | Description               |
| --------------------- | -------- | -------- | ------------------------- |
| `userId`              | string   | Yes      | User identifier           |
| `contentType`         | string[] | No       | Content types to include  |
| `excludeIds`          | string[] | No       | Content IDs to exclude    |
| `limit`               | integer  | No       | Max results (default: 20) |
| `offset`              | integer  | No       | Pagination offset         |
| `strategy`            | string[] | No       | Recommendation strategies |
| `diversityFactor`     | number   | No       | Diversity (0-1)           |
| `noveltyFactor`       | number   | No       | Novelty (0-1)             |
| `experimentId`        | string   | No       | Experiment ID             |
| `includeExplanations` | boolean  | No       | Include explanations      |
| `context`             | object   | No       | Context information       |

**Context Object:**

| Field              | Type     | Description             |
| ------------------ | -------- | ----------------------- |
| `sessionId`        | string   | Session identifier      |
| `deviceType`       | string   | Device type             |
| `timeOfDay`        | string   | Time of day             |
| `dayOfWeek`        | integer  | Day of week (0-6)       |
| `recentContentIds` | string[] | Recently viewed content |
| `availableMinutes` | integer  | Available time          |
| `locale`           | string   | Content locale          |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/recommendations" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user_123",
    "contentType": ["meditation"],
    "excludeIds": ["med_001", "med_002"],
    "limit": 10,
    "diversityFactor": 0.3,
    "noveltyFactor": 0.5,
    "context": {
      "deviceType": "mobile",
      "timeOfDay": "morning",
      "availableMinutes": 15
    },
    "includeExplanations": true
  }'
```

### Get Similar Content

Get content similar to a specific item.

**Endpoint:** `GET /v1/recommendations/similar/:contentId`

**Query Parameters:**

| Parameter | Type    | Description               |
| --------- | ------- | ------------------------- |
| `limit`   | integer | Max results (default: 10) |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/recommendations/similar/meditation_123?limit=5" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "items": [
    {
      "id": "meditation_456",
      "contentType": "meditation",
      "title": "Evening Calm",
      "score": 0.89,
      "position": 0
    }
  ],
  "total": 5
}
```

### Get Trending Content

Get currently trending content.

**Endpoint:** `GET /v1/recommendations/trending`

**Query Parameters:**

| Parameter | Type    | Description                   |
| --------- | ------- | ----------------------------- |
| `types`   | string  | Comma-separated content types |
| `limit`   | integer | Max results (default: 20)     |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/recommendations/trending?types=meditation&limit=10" \
  -H "Authorization: Bearer <access_token>"
```

---

## User Interactions

### Record Interaction

Record a user interaction with content.

**Endpoint:** `POST /v1/recommendations/interactions`

**Request Body:**

| Field               | Type    | Required | Description                   |
| ------------------- | ------- | -------- | ----------------------------- |
| `userId`            | string  | Yes      | User identifier               |
| `contentId`         | string  | Yes      | Content identifier            |
| `contentType`       | string  | Yes      | Content type                  |
| `interactionType`   | string  | Yes      | Interaction type              |
| `weight`            | number  | No       | Custom weight override        |
| `durationSeconds`   | integer | No       | Time spent                    |
| `completionPercent` | number  | No       | Completion percentage (0-100) |
| `rating`            | number  | No       | Rating if applicable (0-5)    |
| `metadata`          | object  | No       | Additional metadata           |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/recommendations/interactions" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user_123",
    "contentId": "meditation_456",
    "contentType": "meditation",
    "interactionType": "complete",
    "durationSeconds": 600,
    "completionPercent": 100
  }'
```

### Record Click Event

Record when a user clicks on a recommendation.

**Endpoint:** `POST /v1/recommendations/click`

**Request Body:**

| Field               | Type    | Required | Description                        |
| ------------------- | ------- | -------- | ---------------------------------- |
| `requestId`         | string  | Yes      | Original recommendation request ID |
| `contentId`         | string  | Yes      | Clicked content ID                 |
| `contentType`       | string  | Yes      | Content type                       |
| `position`          | integer | Yes      | Position in results (0-indexed)    |
| `strategy`          | string  | No       | Recommendation strategy            |
| `experimentId`      | string  | No       | Experiment ID                      |
| `experimentVariant` | string  | No       | Experiment variant                 |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/recommendations/click" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "requestId": "req_abc123",
    "contentId": "meditation_456",
    "contentType": "meditation",
    "position": 2,
    "strategy": "user_user",
    "experimentId": "exp_001",
    "experimentVariant": "variant_a"
  }'
```

---

## User Profiles

### Get User Profile

Retrieve a user's recommendation profile.

**Endpoint:** `GET /v1/recommendations/profile/:userId`

**Response:**

```json
{
  "userId": "user_123",
  "interests": ["meditation", "mindfulness", "yoga"],
  "preferredContentTypes": ["meditation", "lesson"],
  "preferredDifficulty": "beginner",
  "preferredDuration": { "min": 5, "max": 20 },
  "preferredTraditions": ["zen", "mindfulness"],
  "learningGoals": ["stress relief", "better sleep"],
  "interactionHistory": {
    "totalInteractions": 150,
    "completionRate": 0.75,
    "averageRating": 4.2
  },
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-15T00:00:00.000Z"
}
```

### Update User Profile

Update user preferences for recommendations.

**Endpoint:** `PUT /v1/recommendations/profile/:userId`

**Request Body:**

| Field                   | Type     | Description                |
| ----------------------- | -------- | -------------------------- |
| `interests`             | string[] | User interests             |
| `preferredContentTypes` | string[] | Preferred content types    |
| `preferredDifficulty`   | string   | Preferred difficulty level |
| `preferredDuration`     | object   | Preferred duration range   |
| `preferredTraditions`   | string[] | Preferred traditions       |
| `learningGoals`         | string[] | Learning goals             |

**Request:**

```bash
curl -X PUT "https://api.lilith.app/v1/recommendations/profile/user_123" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "interests": ["meditation", "mindfulness"],
    "preferredContentTypes": ["meditation"],
    "preferredDifficulty": "beginner",
    "preferredDuration": { "min": 5, "max": 15 },
    "learningGoals": ["stress relief"]
  }'
```

---

## Feedback

### Submit Recommendation Feedback

Provide feedback on a recommendation.

**Endpoint:** `POST /v1/recommendations/feedback/:userId`

**Request Body:**

| Field          | Type   | Required | Description         |
| -------------- | ------ | -------- | ------------------- |
| `contentId`    | string | Yes      | Content ID          |
| `feedbackType` | string | Yes      | Feedback type       |
| `requestId`    | string | Yes      | Original request ID |

**Feedback Types:**

| Type           | Description                    |
| -------------- | ------------------------------ |
| `helpful`      | Recommendation was helpful     |
| `not_helpful`  | Recommendation was not helpful |
| `irrelevant`   | Content was irrelevant         |
| `already_seen` | User has already seen this     |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/recommendations/feedback/user_123" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "contentId": "meditation_456",
    "feedbackType": "helpful",
    "requestId": "req_abc123"
  }'
```

---

## Content Indexing (Admin)

### Index Content Features

Index content for recommendations.

**Endpoint:** `POST /v1/recommendations/index`

**Request Body:**

| Field             | Type     | Required | Description      |
| ----------------- | -------- | -------- | ---------------- |
| `id`              | string   | Yes      | Content ID       |
| `contentType`     | string   | Yes      | Content type     |
| `title`           | string   | Yes      | Content title    |
| `slug`            | string   | Yes      | URL slug         |
| `tags`            | string[] | No       | Tags             |
| `categories`      | string[] | No       | Categories       |
| `difficulty`      | string   | No       | Difficulty level |
| `tradition`       | string   | No       | Tradition        |
| `durationMinutes` | integer  | No       | Duration         |
| `instructorId`    | string   | No       | Instructor ID    |
| `language`        | string   | No       | Language         |
| `embedding`       | number[] | No       | Vector embedding |

### Update Popularity Metrics

Update content popularity scores.

**Endpoint:** `PUT /v1/recommendations/index/:contentId/popularity`

**Request Body:**

| Field            | Type    | Description           |
| ---------------- | ------- | --------------------- |
| `viewCount`      | integer | Total views           |
| `uniqueViewers`  | integer | Unique viewers        |
| `recentViews7d`  | integer | Views in last 7 days  |
| `recentViews30d` | integer | Views in last 30 days |
| `trendingScore`  | number  | Trending score        |

### Update Quality Metrics

Update content quality scores.

**Endpoint:** `PUT /v1/recommendations/index/:contentId/quality`

**Request Body:**

| Field            | Type    | Description            |
| ---------------- | ------- | ---------------------- |
| `averageRating`  | number  | Average rating (0-5)   |
| `ratingCount`    | integer | Total ratings          |
| `completionRate` | number  | Completion rate (0-1)  |
| `repeatViewRate` | number  | Repeat view rate (0-1) |
| `shareRate`      | number  | Share rate (0-1)       |

---

## Experiments

### Get Active Experiments

Retrieve all active A/B test experiments.

**Endpoint:** `GET /v1/recommendations/experiments`

**Response:**

```json
{
  "experiments": [
    {
      "id": "exp_001",
      "name": "Diversity Factor Test",
      "description": "Testing impact of diversity factor on engagement",
      "status": "active",
      "variants": [
        {
          "id": "control",
          "name": "Control",
          "weight": 50,
          "config": { "diversityFactor": 0.3 }
        },
        {
          "id": "variant_a",
          "name": "High Diversity",
          "weight": 50,
          "config": { "diversityFactor": 0.6 }
        }
      ],
      "startDate": "2024-01-01T00:00:00.000Z",
      "endDate": "2024-02-01T00:00:00.000Z"
    }
  ]
}
```

---

## Analytics

### Get Recommendation Analytics

Retrieve recommendation performance analytics.

**Endpoint:** `GET /v1/recommendations/analytics`

**Query Parameters:**

| Parameter   | Type   | Required | Description           |
| ----------- | ------ | -------- | --------------------- |
| `startDate` | string | Yes      | Start date (ISO 8601) |
| `endDate`   | string | Yes      | End date (ISO 8601)   |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/recommendations/analytics?startDate=2024-01-01&endDate=2024-01-31" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "totalRecommendations": 50000,
  "uniqueUsers": 5000,
  "clickThroughRate": 0.25,
  "conversionRate": 0.15,
  "averageLatencyMs": 42,
  "cacheHitRate": 0.65,
  "strategyPerformance": {
    "user_user": { "impressions": 20000, "clicks": 5500, "ctr": 0.275 },
    "item_item": { "impressions": 15000, "clicks": 3600, "ctr": 0.24 },
    "content_based": { "impressions": 15000, "clicks": 3400, "ctr": 0.227 }
  },
  "experimentResults": {
    "exp_001": {
      "control": { "impressions": 10000, "clicks": 2400, "ctr": 0.24 },
      "variant_a": { "impressions": 10000, "clicks": 2800, "ctr": 0.28 }
    }
  },
  "topRecommendedContent": [
    { "contentId": "meditation_456", "impressions": 1500, "clicks": 450 }
  ],
  "period": {
    "startDate": "2024-01-01T00:00:00.000Z",
    "endDate": "2024-01-31T23:59:59.999Z"
  }
}
```

---

## Error Handling

### Error Codes

| Code                   | HTTP Status | Description                       |
| ---------------------- | ----------- | --------------------------------- |
| `RECOMMENDATION_ERROR` | 500         | General recommendation error      |
| `NOT_FOUND`            | 404         | User profile or content not found |
| `INVALID_REQUEST`      | 400         | Invalid request parameters        |

---

## SDK Integration

### TypeScript/JavaScript

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

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

// Get personalized recommendations
const recommendations = await client.recommendations.getPersonalized({
  userId: 'user_123',
  contentType: ['meditation'],
  limit: 10,
  diversityFactor: 0.3,
  context: {
    deviceType: 'mobile',
    timeOfDay: 'morning',
    availableMinutes: 15,
  },
  includeExplanations: true,
});

// Get similar content
const similar = await client.recommendations.getSimilar('meditation_123', {
  limit: 5,
});

// Get trending
const trending = await client.recommendations.getTrending({
  types: ['meditation'],
  limit: 10,
});

// Record interaction
await client.recommendations.recordInteraction({
  userId: 'user_123',
  contentId: 'meditation_456',
  contentType: 'meditation',
  interactionType: 'complete',
  durationSeconds: 600,
});

// Update profile
await client.recommendations.updateProfile('user_123', {
  interests: ['meditation', 'mindfulness'],
  preferredDuration: { min: 5, max: 15 },
});

// Submit feedback
await client.recommendations.submitFeedback('user_123', {
  contentId: 'meditation_456',
  feedbackType: 'helpful',
  requestId: 'req_abc123',
});
```

---

## Related Documentation

- [Search API](./search-api.md) - Content search
- [Lesson API](./lesson-api.md) - Course lessons
- [Meditation API](./meditation-api.md) - Meditation content
- [Analytics API](./analytics-api.md) - Platform analytics

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
