# Analytics API

This document provides comprehensive documentation for the Lilith Analytics
Service API, which enables event tracking, session management, user/content
metrics, and funnel analysis.

## Overview

The Analytics API provides enterprise-grade analytics capabilities:

- **Event Tracking**: Track user actions and behaviors with contextual data
- **Session Management**: Manage user sessions with device and context
  information
- **Metrics**: Query user, content, and platform-level metrics
- **Funnel Analysis**: Define and analyze conversion funnels

---

## Table of Contents

1. [Event Tracking](#event-tracking)
2. [Session Management](#session-management)
3. [Metrics](#metrics)
4. [Funnel Analysis](#funnel-analysis)
5. [Error Handling](#error-handling)

---

## Event Tracking

### Track Single Event

Track a user action or behavior.

**Endpoint:** `POST /v1/events/track`

**Request Body:**

| Field            | Type   | Required | Description                                    |
| ---------------- | ------ | -------- | ---------------------------------------------- |
| `event_name`     | string | Yes      | Name of the event (e.g., `meditation_started`) |
| `session_id`     | string | Yes      | Session ID from session start                  |
| `event_category` | string | No       | Category (auto-categorized if not provided)    |
| `properties`     | object | No       | Custom event properties                        |
| `context`        | object | No       | Additional context (device, location)          |
| `timestamp`      | string | No       | ISO 8601 timestamp (defaults to now)           |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/events/track" \
  -H "Content-Type: application/json" \
  -d '{
    "event_name": "meditation_started",
    "session_id": "sess_abc123",
    "event_category": "engagement",
    "properties": {
      "meditation_id": "med_12345",
      "duration_minutes": 10,
      "type": "breathing"
    },
    "context": {
      "page": "/meditations/breathing"
    }
  }'
```

**Response:**

```json
{
  "success": true,
  "event_id": "evt_xyz789"
}
```

**Event Categories:** | Category | Description | |----------|-------------| |
`navigation` | Page views and navigation | | `engagement` | Content interactions
| | `conversion` | Goal completions | | `error` | Error events | | `system` |
System events |

### Track Batch Events

Track multiple events in a single request (max 1000 events).

**Endpoint:** `POST /v1/events/track/batch`

**Request Body:**

| Field    | Type  | Required | Description            |
| -------- | ----- | -------- | ---------------------- |
| `events` | array | Yes      | Array of event objects |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/events/track/batch" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      {
        "event_name": "page_view",
        "session_id": "sess_abc123",
        "properties": { "page": "/home" }
      },
      {
        "event_name": "button_click",
        "session_id": "sess_abc123",
        "properties": { "button_id": "start_meditation" }
      }
    ]
  }'
```

**Response:**

```json
{
  "success": true,
  "events_tracked": 2,
  "event_ids": ["evt_001", "evt_002"]
}
```

### Query Events (Admin)

Query tracked events with filtering (requires admin access).

**Endpoint:** `GET /v1/events`

**Query Parameters:**

| Parameter        | Type   | Description                    |
| ---------------- | ------ | ------------------------------ |
| `user_id`        | string | Filter by user ID              |
| `session_id`     | string | Filter by session ID           |
| `event_name`     | string | Filter by event name           |
| `event_category` | string | Filter by category             |
| `start_date`     | string | Start of date range (ISO 8601) |
| `end_date`       | string | End of date range (ISO 8601)   |
| `limit`          | number | Max results (default: 100)     |
| `offset`         | number | Pagination offset              |

---

## Session Management

### Start Session

Start a new analytics session.

**Endpoint:** `POST /v1/sessions/start`

**Request Body:**

| Field          | Type   | Required | Description                                        |
| -------------- | ------ | -------- | -------------------------------------------------- |
| `anonymous_id` | string | Yes      | Anonymous identifier (device ID or generated UUID) |
| `context`      | object | No       | Session context (device, location, UTM params)     |

**Context Object:**

| Field               | Type   | Description                  |
| ------------------- | ------ | ---------------------------- |
| `device_type`       | string | mobile, tablet, desktop      |
| `device_os`         | string | iOS, Android, Windows, macOS |
| `device_os_version` | string | OS version                   |
| `browser`           | string | Browser name                 |
| `browser_version`   | string | Browser version              |
| `screen_resolution` | string | e.g., "1920x1080"            |
| `viewport_size`     | string | e.g., "1200x800"             |
| `language`          | string | Browser language             |
| `timezone`          | string | Timezone name                |
| `country`           | string | Country code                 |
| `region`            | string | Region/state                 |
| `city`              | string | City name                    |
| `referrer`          | string | Referring URL                |
| `utm_source`        | string | UTM source                   |
| `utm_medium`        | string | UTM medium                   |
| `utm_campaign`      | string | UTM campaign                 |
| `utm_term`          | string | UTM term                     |
| `utm_content`       | string | UTM content                  |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/sessions/start" \
  -H "Content-Type: application/json" \
  -d '{
    "anonymous_id": "device_12345",
    "context": {
      "device_type": "mobile",
      "device_os": "iOS",
      "device_os_version": "17.0",
      "browser": "Safari",
      "language": "en-US",
      "timezone": "America/New_York",
      "utm_source": "instagram",
      "utm_campaign": "meditation_promo"
    }
  }'
```

**Response:**

```json
{
  "success": true,
  "session_id": "sess_abc123",
  "started_at": "2024-01-15T10:30:00.000Z"
}
```

### End Session

End an active session.

**Endpoint:** `POST /v1/sessions/{sessionId}/end`

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/sessions/sess_abc123/end"
```

**Response:**

```json
{
  "success": true,
  "session_id": "sess_abc123",
  "duration_seconds": 1800,
  "event_count": 45,
  "page_views": 12
}
```

### Get Session Details

Retrieve session information.

**Endpoint:** `GET /v1/sessions/{sessionId}`

**Response:**

```json
{
  "session": {
    "id": "sess_abc123",
    "user_id": "user_12345",
    "anonymous_id": "device_12345",
    "started_at": "2024-01-15T10:30:00.000Z",
    "ended_at": null,
    "duration_seconds": null,
    "is_active": true,
    "event_count": 45,
    "page_views": 12,
    "first_event": "page_view",
    "last_event": "meditation_completed",
    "entry_page": "/home",
    "exit_page": null,
    "context": {
      "device_type": "mobile",
      "device_os": "iOS",
      "utm_source": "instagram"
    }
  }
}
```

### Identify User

Associate a user ID with an anonymous session (after login).

**Endpoint:** `POST /v1/sessions/{sessionId}/identify`

**Request Body:**

| Field     | Type   | Required | Description           |
| --------- | ------ | -------- | --------------------- |
| `user_id` | string | Yes      | Authenticated user ID |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/sessions/sess_abc123/identify" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_12345"
  }'
```

**Response:**

```json
{
  "success": true,
  "session_id": "sess_abc123",
  "user_id": "user_12345"
}
```

### Track Page View

Track a page view within a session.

**Endpoint:** `POST /v1/sessions/{sessionId}/page_view`

**Request Body:**

| Field        | Type   | Required | Description                                |
| ------------ | ------ | -------- | ------------------------------------------ |
| `page_path`  | string | Yes      | Page path (e.g., `/meditations/breathing`) |
| `page_title` | string | No       | Page title                                 |
| `referrer`   | string | No       | Previous page                              |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/sessions/sess_abc123/page_view" \
  -H "Content-Type: application/json" \
  -d '{
    "page_path": "/meditations/breathing",
    "page_title": "Breathing Meditation",
    "referrer": "/explore"
  }'
```

### List Active Sessions

List currently active sessions (admin).

**Endpoint:** `GET /v1/sessions`

**Query Parameters:**

| Parameter     | Type    | Description                    |
| ------------- | ------- | ------------------------------ |
| `active_only` | boolean | Filter to active sessions only |
| `limit`       | number  | Max results                    |
| `offset`      | number  | Pagination offset              |

---

## Metrics

### Service Metrics (Admin)

Get internal service metrics.

**Endpoint:** `GET /v1/metrics/service`

**Response:**

```json
{
  "metrics": {
    "eventsTracked": 125000,
    "eventsBuffered": 45,
    "activeSessions": 230,
    "sessionsStarted": 5420,
    "funnelsRegistered": 8,
    "errors": 12
  }
}
```

### User Metrics

Get metrics for a specific user.

**Endpoint:** `GET /v1/metrics/users/{userId}`

**Query Parameters:**

| Parameter    | Type   | Description                            |
| ------------ | ------ | -------------------------------------- |
| `period`     | string | `hourly`, `daily`, `weekly`, `monthly` |
| `start_date` | string | Start of period (ISO 8601)             |
| `end_date`   | string | End of period (ISO 8601)               |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/metrics/users/user_12345?period=weekly" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "metrics": {
    "user_id": "user_12345",
    "period": "weekly",
    "period_start": "2024-01-08T00:00:00.000Z",
    "period_end": "2024-01-15T00:00:00.000Z",
    "total_sessions": 12,
    "total_session_duration_seconds": 7200,
    "avg_session_duration_seconds": 600,
    "total_events": 450,
    "total_page_views": 85,
    "unique_pages_viewed": 15,
    "content_items_viewed": 8,
    "content_items_completed": 5,
    "meditations_started": 10,
    "meditations_completed": 8,
    "ai_conversations": 3,
    "ai_messages_sent": 25,
    "ai_messages_received": 25,
    "daily_streak": 7,
    "weekly_active_days": 6
  }
}
```

### Content Metrics

Get metrics for specific content.

**Endpoint:** `GET /v1/metrics/content/{contentId}`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/metrics/content/med_12345?period=daily" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "metrics": {
    "content_id": "med_12345",
    "period": "daily",
    "period_start": "2024-01-14T00:00:00.000Z",
    "period_end": "2024-01-15T00:00:00.000Z",
    "total_views": 1250,
    "unique_viewers": 890,
    "avg_view_duration_seconds": 420,
    "total_view_duration_seconds": 525000,
    "completion_rate": 0.72,
    "likes": 145,
    "shares": 32,
    "bookmarks": 89,
    "comments": 23,
    "total_ratings": 156,
    "avg_rating": 4.7,
    "views_from_search": 320,
    "views_from_recommendations": 580,
    "views_from_direct": 250,
    "views_from_referral": 100
  }
}
```

### Platform Metrics

Get aggregated platform-wide metrics.

**Endpoint:** `GET /v1/metrics/platform`

**Response:**

```json
{
  "period": "daily",
  "period_start": "2024-01-14T00:00:00.000Z",
  "period_end": "2024-01-15T00:00:00.000Z",
  "total_sessions": 12500,
  "active_sessions": 230,
  "avg_session_duration_seconds": 480,
  "total_events": 450000,
  "events_per_session": 36,
  "daily_active_users": 8500,
  "weekly_active_users": 25000,
  "monthly_active_users": 85000,
  "avg_events_per_user": 53,
  "content_views": 45000,
  "content_completions": 12000,
  "avg_completion_rate": 0.68,
  "ai_conversations": 3200,
  "ai_messages": 28000
}
```

### Real-time Metrics

Get real-time platform metrics.

**Endpoint:** `GET /v1/metrics/realtime`

**Response:**

```json
{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "active_users": 230,
  "events_last_minute": 450,
  "events_last_5_minutes": 2100,
  "active_meditations": 45,
  "active_conversations": 28
}
```

### Top Content

Get top performing content.

**Endpoint:** `GET /v1/metrics/top-content`

**Query Parameters:**

| Parameter      | Type   | Description                                             |
| -------------- | ------ | ------------------------------------------------------- |
| `metric`       | string | Sort by: `views`, `completions`, `rating`, `engagement` |
| `period`       | string | Time period                                             |
| `limit`        | number | Number of results                                       |
| `content_type` | string | Filter by content type                                  |

---

## Funnel Analysis

### Create Funnel

Define a conversion funnel.

**Endpoint:** `POST /v1/funnels`

**Request Body:**

| Field         | Type   | Required | Description           |
| ------------- | ------ | -------- | --------------------- |
| `name`        | string | Yes      | Funnel name           |
| `description` | string | No       | Funnel description    |
| `steps`       | array  | Yes      | Array of funnel steps |

**Step Object:**

| Field              | Type   | Required | Description                   |
| ------------------ | ------ | -------- | ----------------------------- |
| `name`             | string | Yes      | Step name                     |
| `event_name`       | string | Yes      | Event that triggers this step |
| `event_properties` | object | No       | Required event properties     |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/funnels" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Meditation Completion Funnel",
    "description": "Tracks user journey from viewing to completing a meditation",
    "steps": [
      {
        "name": "View Meditation",
        "event_name": "meditation_viewed"
      },
      {
        "name": "Start Meditation",
        "event_name": "meditation_started"
      },
      {
        "name": "Complete Meditation",
        "event_name": "meditation_completed"
      },
      {
        "name": "Rate Meditation",
        "event_name": "meditation_rated"
      }
    ]
  }'
```

**Response:**

```json
{
  "id": "funnel_abc123",
  "name": "Meditation Completion Funnel",
  "description": "Tracks user journey from viewing to completing a meditation",
  "steps": [
    { "name": "View Meditation", "event_name": "meditation_viewed" },
    { "name": "Start Meditation", "event_name": "meditation_started" },
    { "name": "Complete Meditation", "event_name": "meditation_completed" },
    { "name": "Rate Meditation", "event_name": "meditation_rated" }
  ],
  "is_active": true,
  "created_at": "2024-01-15T10:30:00.000Z",
  "updated_at": "2024-01-15T10:30:00.000Z"
}
```

### List Funnels

Get all defined funnels.

**Endpoint:** `GET /v1/funnels`

**Query Parameters:**

| Parameter     | Type    | Description              |
| ------------- | ------- | ------------------------ |
| `active_only` | boolean | Filter to active funnels |
| `limit`       | number  | Max results              |
| `offset`      | number  | Pagination offset        |

### Get Funnel

Get funnel by ID.

**Endpoint:** `GET /v1/funnels/{funnelId}`

### Update Funnel

Update funnel configuration.

**Endpoint:** `PATCH /v1/funnels/{funnelId}`

### Delete Funnel

Delete a funnel.

**Endpoint:** `DELETE /v1/funnels/{funnelId}`

### Analyze Funnel

Get funnel performance analysis.

**Endpoint:** `GET /v1/funnels/{funnelId}/analyze`

**Query Parameters:**

| Parameter    | Type   | Description             |
| ------------ | ------ | ----------------------- |
| `start_date` | string | Analysis start date     |
| `end_date`   | string | Analysis end date       |
| `segment`    | string | User segment to analyze |

**Response:**

```json
{
  "funnel_id": "funnel_abc123",
  "funnel_name": "Meditation Completion Funnel",
  "period": {
    "start": "2024-01-01T00:00:00.000Z",
    "end": "2024-01-15T00:00:00.000Z"
  },
  "total_entries": 10000,
  "completion_rate": 0.35,
  "avg_time_to_complete_seconds": 1800,
  "steps": [
    {
      "step": 1,
      "name": "View Meditation",
      "event_name": "meditation_viewed",
      "users": 10000,
      "conversion_rate": 1.0,
      "drop_off_rate": 0
    },
    {
      "step": 2,
      "name": "Start Meditation",
      "event_name": "meditation_started",
      "users": 6500,
      "conversion_rate": 0.65,
      "drop_off_rate": 0.35
    },
    {
      "step": 3,
      "name": "Complete Meditation",
      "event_name": "meditation_completed",
      "users": 4200,
      "conversion_rate": 0.646,
      "drop_off_rate": 0.354
    },
    {
      "step": 4,
      "name": "Rate Meditation",
      "event_name": "meditation_rated",
      "users": 3500,
      "conversion_rate": 0.833,
      "drop_off_rate": 0.167
    }
  ]
}
```

### Funnel Templates

Get pre-defined funnel templates.

**Endpoint:** `GET /v1/funnels/templates`

**Response:**

```json
{
  "templates": [
    {
      "id": "onboarding",
      "name": "User Onboarding",
      "description": "Track new user onboarding completion",
      "steps": [
        { "name": "Sign Up", "event_name": "user_registered" },
        { "name": "Complete Profile", "event_name": "profile_completed" },
        {
          "name": "First Meditation",
          "event_name": "first_meditation_completed"
        }
      ]
    },
    {
      "id": "subscription",
      "name": "Subscription Conversion",
      "description": "Track free to paid conversion",
      "steps": [
        { "name": "View Pricing", "event_name": "pricing_viewed" },
        { "name": "Start Trial", "event_name": "trial_started" },
        { "name": "Subscribe", "event_name": "subscription_created" }
      ]
    }
  ]
}
```

---

## Error Handling

### Error Codes

| Code                             | HTTP Status | Description                           |
| -------------------------------- | ----------- | ------------------------------------- |
| `analytics.missing_fields`       | 400         | Required fields are missing           |
| `analytics.missing_anonymous_id` | 400         | anonymous_id is required for sessions |
| `analytics.invalid_batch`        | 400         | Batch events array is invalid         |
| `analytics.batch_too_large`      | 400         | Batch exceeds 1000 events limit       |
| `analytics.session_not_found`    | 404         | Session does not exist                |
| `analytics.funnel_not_found`     | 404         | Funnel does not exist                 |
| `analytics.invalid_funnel`       | 400         | Funnel configuration is invalid       |

### Example Error Response

```json
{
  "error": "Missing required fields",
  "code": "analytics.missing_fields",
  "details": {
    "required": ["event_name", "session_id"]
  }
}
```

---

## SDK Integration

### TypeScript/JavaScript

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

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

// Start a session
const session = await client.analytics.startSession({
  anonymousId: 'device_12345',
  context: {
    deviceType: 'mobile',
    deviceOs: 'iOS',
  },
});

// Track an event
await client.analytics.trackEvent({
  eventName: 'meditation_started',
  sessionId: session.sessionId,
  properties: {
    meditationId: 'med_12345',
    duration: 10,
  },
});

// Identify user after login
await client.analytics.identify({
  sessionId: session.sessionId,
  userId: 'user_12345',
});

// Get user metrics
const metrics = await client.analytics.getUserMetrics('user_12345', {
  period: 'weekly',
});

// Analyze funnel
const funnelAnalysis = await client.analytics.analyzeFunnel('funnel_abc123', {
  startDate: '2024-01-01',
  endDate: '2024-01-15',
});
```

---

## Related Documentation

- [Authentication](./authentication.md) - API authentication
- [Error Codes](./error-codes.md) - Complete error reference
- [Rate Limits](./rate-limits.md) - Rate limiting policies

---

## Questions?

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