# Tara Content Management Guide

Complete guide to managing meditation content for the Tara platform, including
content creation, validation, processing, and publishing workflows.

## Table of Contents

- [Content Overview](#content-overview)
- [Directory Structure](#directory-structure)
- [Content Types](#content-types)
- [Creating Content](#creating-content)
- [Content Schemas](#content-schemas)
- [Media Requirements](#media-requirements)
- [Validation](#validation)
- [Publishing Workflow](#publishing-workflow)
- [Content Operations](#content-operations)
- [Localization](#localization)
- [Best Practices](#best-practices)

---

## Content Overview

Tara's content system is file-based, using JSON metadata files and associated
media assets stored in a structured directory hierarchy. Content is validated
against JSON schemas, processed for multiple quality levels, and deployed to
CDN/S3 for distribution.

### Content Types Summary

| Type        | Description                   | Location                         |
| ----------- | ----------------------------- | -------------------------------- |
| Meditations | Individual guided meditations | `meditations/{category}/{slug}/` |
| Courses     | Multi-day meditation programs | `courses/{course-slug}/`         |
| Teachers    | Instructor profiles           | `teachers/{teacher-slug}/`       |
| Sounds      | Background sounds and music   | `sounds/{type}/`                 |
| Collections | Curated content groupings     | `collections/{collection-slug}/` |

---

## Directory Structure

```
apps/tara/content/
├── meditations/                    # Individual meditations
│   └── {category}/                 # Category folder
│       └── {meditation-slug}/      # Meditation folder
│           ├── metadata.json       # Content metadata
│           ├── audio.mp3           # Primary audio file
│           ├── thumbnail.jpg       # Cover image (1024x1024)
│           └── transcript.md       # Optional transcript
│
├── courses/                        # Multi-day programs
│   └── {course-slug}/
│       ├── metadata.json           # Course metadata
│       ├── thumbnail.jpg           # Course thumbnail
│       ├── cover.jpg               # Wide banner image
│       └── lessons/
│           └── {day-number}/       # e.g., 01, 02, 03
│               ├── metadata.json   # Lesson metadata
│               ├── audio.mp3       # Lesson audio
│               └── thumbnail.jpg   # Lesson thumbnail
│
├── teachers/                       # Instructor profiles
│   └── {teacher-slug}/
│       ├── metadata.json           # Teacher metadata
│       ├── photo.jpg               # Profile photo
│       └── bio.md                  # Extended biography
│
├── sounds/                         # Background audio
│   ├── ambient/                    # Nature sounds, white noise
│   │   └── {sound-slug}.json       # Sound metadata
│   ├── bells/                      # Meditation bells
│   └── music/                      # Background music
│
├── collections/                    # Curated collections
│   └── {collection-slug}/
│       └── metadata.json           # Collection metadata
│
└── schemas/                        # JSON Schema definitions
    ├── meditation.schema.json
    ├── course.schema.json
    ├── teacher.schema.json
    ├── sound.schema.json
    └── collection.schema.json
```

---

## Content Types

### Categories

All meditation content belongs to one of these categories:

| Category        | Slug              | Description                    |
| --------------- | ----------------- | ------------------------------ |
| Sleep           | `sleep`           | Guided sleep meditations       |
| Stress Relief   | `stress`          | Stress and anxiety relief      |
| Focus           | `focus`           | Concentration and productivity |
| Anxiety         | `anxiety`         | Anxiety management techniques  |
| Morning         | `morning`         | Start-your-day routines        |
| Evening         | `evening`         | Wind-down practices            |
| Breathwork      | `breathwork`      | Breathing exercises            |
| Body Scan       | `body_scan`       | Body awareness practices       |
| Visualization   | `visualization`   | Guided imagery                 |
| Gratitude       | `gratitude`       | Gratitude and appreciation     |
| Self Compassion | `self_compassion` | Self-love and acceptance       |
| Relationships   | `relationships`   | Loving-kindness and connection |
| Work            | `work`            | Workplace mindfulness          |
| Creativity      | `creativity`      | Creative flow and inspiration  |
| General         | `general`         | General mindfulness practices  |

### Meditation Types

| Type         | Description                         |
| ------------ | ----------------------------------- |
| `guided`     | Instructor-led meditation           |
| `unguided`   | Timer-only with optional background |
| `music`      | Music-based meditation              |
| `soundscape` | Nature sounds and ambient audio     |
| `story`      | Narrative sleep stories             |

### Experience Levels

| Level          | Target Audience                       |
| -------------- | ------------------------------------- |
| `beginner`     | New to meditation (< 1 month)         |
| `intermediate` | Regular practice (1-6 months)         |
| `advanced`     | Experienced practitioners (6+ months) |

---

## Creating Content

### Creating a Meditation

1. **Create directory structure:**

```bash
mkdir -p apps/tara/content/meditations/stress/release-tension
```

2. **Create metadata.json:**

```json
{
  "$schema": "../../../schemas/meditation.schema.json",
  "id": "550e8400-e29b-41d4-a716-446655440002",
  "slug": "release-tension",
  "title": "Release Tension",
  "description": "A guided meditation to release physical tension and mental stress...",
  "shortDescription": "Release tension from body and mind in this calming practice.",
  "category": "stress",
  "contentType": "guided",
  "durationSeconds": 900,
  "experienceLevel": "beginner",
  "isPremium": false,
  "isFeatured": false,
  "audio": {
    "file": "audio.mp3",
    "format": "mp3",
    "bitrate": 128,
    "sampleRate": 44100,
    "channels": 2
  },
  "thumbnail": {
    "file": "thumbnail.jpg",
    "alt": "Calm sunset over a peaceful meadow",
    "color": "#E8A87C"
  },
  "teacher": {
    "id": "550e8400-e29b-41d4-a716-446655440100",
    "slug": "sarah-chen",
    "name": "Sarah Chen"
  },
  "tags": ["stress relief", "relaxation", "tension", "body scan"],
  "backgroundSounds": [
    {
      "id": "rain-soft",
      "name": "Soft Rain",
      "defaultVolume": 0.3
    }
  ],
  "transcript": {
    "file": "transcript.md",
    "language": "en"
  },
  "relatedMeditations": ["calm-your-mind", "body-scan-relaxation"],
  "publishedAt": "2024-01-20T00:00:00Z",
  "updatedAt": "2024-01-20T00:00:00Z",
  "version": "1.0.0"
}
```

3. **Add media files:**
   - `audio.mp3` - The meditation audio
   - `thumbnail.jpg` - 1024x1024 cover image
   - `transcript.md` - Optional transcript

4. **Validate content:**

```bash
pnpm nx run tara-content:validate --path=meditations/stress/release-tension
```

### Creating a Course

1. **Create directory structure:**

```bash
mkdir -p apps/tara/content/courses/7-day-stress-relief/{lessons/01,lessons/02,...}
```

2. **Create course metadata.json:**

```json
{
  "$schema": "../../schemas/course.schema.json",
  "id": "550e8400-e29b-41d4-a716-446655440200",
  "slug": "7-day-stress-relief",
  "title": "7-Day Stress Relief Program",
  "subtitle": "Transform Your Relationship with Stress",
  "description": "A comprehensive 7-day program designed to help you understand, manage, and reduce stress...",
  "shortDescription": "Transform stress into calm in just one week.",
  "category": "stress",
  "totalDays": 7,
  "estimatedDurationMinutes": 70,
  "experienceLevel": "beginner",
  "isPremium": true,
  "isFeatured": true,
  "thumbnail": {
    "file": "thumbnail.jpg",
    "alt": "7-Day Stress Relief Course",
    "color": "#6366F1"
  },
  "coverImage": {
    "file": "cover.jpg",
    "alt": "Peaceful mountain landscape"
  },
  "teacher": {
    "id": "550e8400-e29b-41d4-a716-446655440100",
    "slug": "sarah-chen",
    "name": "Sarah Chen"
  },
  "tags": ["stress", "anxiety", "beginner", "7 days"],
  "benefits": [
    "Understand your stress response",
    "Learn practical calming techniques",
    "Build a sustainable meditation habit",
    "Improve sleep quality"
  ],
  "lessons": [
    {
      "day": 1,
      "title": "Understanding Stress",
      "slug": "understanding-stress",
      "description": "Explore what stress is and how it affects your body and mind.",
      "durationSeconds": 600
    },
    {
      "day": 2,
      "title": "The Power of Breath",
      "slug": "power-of-breath",
      "description": "Learn breathing techniques to activate your relaxation response.",
      "durationSeconds": 600
    }
  ],
  "schedule": {
    "type": "daily",
    "recommendedTime": "morning"
  },
  "completion": {
    "certificateEnabled": true,
    "badgeId": "stress-relief-master"
  },
  "publishedAt": "2024-01-20T00:00:00Z",
  "version": "1.0.0"
}
```

3. **Create lesson metadata for each day:**

```json
// lessons/01/metadata.json
{
  "$schema": "../../../../schemas/meditation.schema.json",
  "id": "550e8400-e29b-41d4-a716-446655440201",
  "slug": "understanding-stress",
  "title": "Day 1: Understanding Stress",
  "description": "In this first session, we explore what stress is...",
  "category": "stress",
  "contentType": "guided",
  "durationSeconds": 600,
  "experienceLevel": "beginner",
  "isPremium": true,
  "audio": {
    "file": "audio.mp3",
    "format": "mp3",
    "bitrate": 128,
    "sampleRate": 44100,
    "channels": 2
  },
  "thumbnail": {
    "file": "thumbnail.jpg",
    "alt": "Day 1 - Understanding Stress"
  },
  "teacher": {
    "slug": "sarah-chen",
    "name": "Sarah Chen"
  },
  "series": {
    "id": "7-day-stress-relief",
    "position": 1
  },
  "publishedAt": "2024-01-20T00:00:00Z",
  "version": "1.0.0"
}
```

### Creating a Teacher Profile

1. **Create directory:**

```bash
mkdir -p apps/tara/content/teachers/david-kim
```

2. **Create metadata.json:**

```json
{
  "$schema": "../../schemas/teacher.schema.json",
  "id": "550e8400-e29b-41d4-a716-446655440101",
  "slug": "david-kim",
  "name": "David Kim",
  "title": "Sleep Specialist & Meditation Teacher",
  "bio": "David Kim is a certified sleep coach and meditation teacher...",
  "shortBio": "Sleep specialist helping people achieve restful, restorative sleep.",
  "photo": {
    "file": "photo.jpg",
    "alt": "David Kim, sleep specialist"
  },
  "credentials": [
    {
      "title": "Certified Sleep Coach",
      "organization": "Sleep Science Academy",
      "year": 2018
    }
  ],
  "specialties": ["Sleep meditation", "Yoga nidra", "Relaxation techniques"],
  "yearsExperience": 10,
  "location": {
    "city": "Los Angeles",
    "country": "USA"
  },
  "voice": {
    "style": "calm",
    "accent": "American",
    "gender": "male"
  },
  "categories": ["sleep", "evening", "relaxation"],
  "isFeatured": false,
  "isVerified": true,
  "joinedAt": "2024-01-15T00:00:00Z"
}
```

3. **Add bio.md for extended biography:**

```markdown
# David Kim

## Background

David Kim is a certified sleep coach and meditation teacher with over 10 years
of experience helping people achieve restful, restorative sleep...

## Teaching Philosophy

David believes that quality sleep is the foundation of well-being...

## Credentials

- Certified Sleep Coach, Sleep Science Academy (2018)
- Yoga Nidra Teacher Training, iRest Institute (2019)
```

---

## Content Schemas

### Schema Validation

All content must conform to JSON schemas located in
`apps/tara/content/schemas/`:

| Schema                   | Validates         |
| ------------------------ | ----------------- |
| `meditation.schema.json` | Meditations       |
| `course.schema.json`     | Courses           |
| `teacher.schema.json`    | Teacher profiles  |
| `sound.schema.json`      | Background sounds |
| `collection.schema.json` | Collections       |

### Key Schema Fields

**Meditation Required Fields:**

- `id` - UUID v4
- `slug` - URL-friendly identifier
- `title` - Display title
- `description` - Full description
- `category` - From allowed categories
- `contentType` - guided, unguided, music, soundscape, story
- `durationSeconds` - Duration in seconds (60-7200)
- `experienceLevel` - beginner, intermediate, advanced
- `isPremium` - Subscription required
- `audio` - Audio file configuration

**Teacher Required Fields:**

- `id` - UUID v4
- `slug` - URL-friendly identifier
- `name` - Display name
- `bio` - Full biography (50-5000 chars)

**Course Required Fields:**

- `id` - UUID v4
- `slug` - URL-friendly identifier
- `title` - Display title
- `description` - Full description
- `category` - From allowed categories
- `totalDays` - Number of lessons (3-365)
- `experienceLevel` - beginner, intermediate, advanced
- `isPremium` - Subscription required

---

## Media Requirements

### Audio Specifications

**Formats:**

- **Primary**: MP3 (most compatible)
- **Alternative**: M4A/AAC (better quality at lower bitrates)

**Quality Levels:**

| Quality  | Bitrate | Sample Rate | Use Case          |
| -------- | ------- | ----------- | ----------------- |
| High     | 256kbps | 44.1kHz     | WiFi streaming    |
| Standard | 128kbps | 44.1kHz     | Default streaming |
| Low      | 64kbps  | 22.05kHz    | Cellular/offline  |

**Technical Requirements:**

- Mono or stereo (voice centered)
- Normalized to -16 LUFS
- No clipping or distortion
- Fade in/out at start/end
- Minimal silence at beginning (< 0.5s)
- ID3 tags embedded

### Image Specifications

**Thumbnail Sizes:**

| Size      | Resolution | Use Case         |
| --------- | ---------- | ---------------- |
| Large     | 1024x1024  | Full detail view |
| Medium    | 512x512    | Card displays    |
| Small     | 256x256    | List views       |
| Thumbnail | 128x128    | Small thumbnails |

**Format Requirements:**

- JPEG for photos, PNG for graphics
- sRGB color space
- 80-90% JPEG quality
- 1:1 aspect ratio for thumbnails
- 16:9 or 2:1 for banner images

**Teacher Photos:**

- Minimum 500x500 pixels
- Professional headshot
- Neutral or simple background
- Good lighting, face clearly visible

### Naming Conventions

**Files:**

- Lowercase with hyphens: `calm-your-mind`
- No spaces or special characters
- Descriptive but concise
- Examples: `morning-energy-boost`, `5-minute-breathing`

**Slugs:**

- Pattern: `^[a-z0-9]+(?:-[a-z0-9]+)*$`
- 3-100 characters
- Must be unique within category/type

---

## Validation

### Running Validation

```bash
# Validate all content
pnpm nx run tara-content:validate

# Validate specific content
pnpm nx run tara-content:validate --path=meditations/stress/calm-your-mind

# Validate with verbose output
pnpm nx run tara-content:validate --verbose

# Check only (no processing)
pnpm nx run tara-content:validate --check-only
```

### Validation Checks

**Schema Validation:**

- Required fields present
- Field types correct
- Values within allowed ranges
- Enum values valid
- String patterns match

**File Validation:**

- Referenced files exist
- File formats correct
- File sizes within limits
- Image dimensions correct
- Audio duration matches metadata

**Relationship Validation:**

- Teacher IDs exist
- Related meditations exist
- Course lesson IDs sequential
- Collection items valid

### Common Validation Errors

| Error                    | Cause                            | Fix                       |
| ------------------------ | -------------------------------- | ------------------------- |
| `missing required field` | Required field not in metadata   | Add the field             |
| `invalid enum value`     | Value not in allowed list        | Use allowed value         |
| `string too short/long`  | String length out of bounds      | Adjust string length      |
| `file not found`         | Referenced file doesn't exist    | Add file or fix reference |
| `invalid UUID format`    | ID not valid UUID v4             | Generate valid UUID       |
| `slug pattern mismatch`  | Slug contains invalid characters | Use lowercase, hyphens    |

---

## Publishing Workflow

### Content Pipeline

```
┌─────────────────────────────────────────────────────────────────────────┐
│                      Content Publishing Pipeline                         │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌────────┐│
│  │  Create  │──►│ Validate │──►│ Process  │──►│  Upload  │──►│ Publish││
│  │ Content  │   │  Schema  │   │  Media   │   │  to CDN  │   │ to DB  ││
│  └──────────┘   └──────────┘   └──────────┘   └──────────┘   └────────┘│
│       │              │              │              │              │     │
│       ▼              ▼              ▼              ▼              ▼     │
│  ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌────────┐│
│  │ metadata │   │  Errors  │   │  Audio:  │   │   S3:    │   │  API:  ││
│  │   .json  │   │  Report  │   │ normalize│   │ high/med │   │ catalog││
│  │ audio.mp3│   │          │   │ transcode│   │ /low/    │   │ update ││
│  │ thumb.jpg│   │          │   │ Image:   │   │ images/  │   │        ││
│  └──────────┘   └──────────┘   │ resize   │   └──────────┘   └────────┘│
│                                └──────────┘                             │
│                                                                          │
└──────────────────────────────────────────────────────────────────────────┘
```

### Processing Commands

```bash
# Process specific content
pnpm nx run tara-content:process --path=meditations/stress/calm-your-mind

# Process all pending content
pnpm nx run tara-content:process --all

# Process with specific quality levels
pnpm nx run tara-content:process --path=meditations/stress/calm-your-mind --quality=high,standard

# Dry run (no actual processing)
pnpm nx run tara-content:process --dry-run

# Skip audio processing (images only)
pnpm nx run tara-content:process --skip-audio

# Force reprocessing
pnpm nx run tara-content:process --force
```

### Publishing Steps

1. **Create content** in appropriate directory
2. **Validate** schema and files
3. **Review** content for quality
4. **Process** media (transcoding, resizing)
5. **Upload** to CDN/S3
6. **Sync** to database catalog
7. **Verify** in staging environment
8. **Release** to production

### Environment Promotion

```bash
# Deploy to staging
pnpm nx run tara-content:deploy --env=staging

# Deploy to production (requires approval)
pnpm nx run tara-content:deploy --env=production

# Deploy specific content
pnpm nx run tara-content:deploy --path=meditations/stress/calm-your-mind --env=production
```

---

## Content Operations

### Updating Content

1. **Update metadata.json** with changes
2. **Increment version** (e.g., 1.0.0 → 1.0.1)
3. **Update `updatedAt`** timestamp
4. **Revalidate** and **reprocess** if media changed
5. **Deploy** to environments

```json
{
  "version": "1.0.1",
  "updatedAt": "2024-02-01T00:00:00Z"
}
```

### Archiving Content

To remove content from the app without deleting files:

```json
{
  "status": "archived",
  "archivedAt": "2024-02-01T00:00:00Z",
  "archiveReason": "Replaced by updated version"
}
```

### Content Analytics

Query content performance:

```bash
# Top performing meditations
pnpm nx run tara-content:analytics --metric=plays --period=30d --limit=10

# Low engagement content
pnpm nx run tara-content:analytics --metric=completion-rate --threshold=0.5

# Content by category
pnpm nx run tara-content:analytics --group-by=category
```

---

## Localization

### Supported Languages

| Code | Language | Status    |
| ---- | -------- | --------- |
| en   | English  | Primary   |
| es   | Spanish  | Supported |
| fr   | French   | Supported |
| de   | German   | Supported |
| ja   | Japanese | Supported |
| zh   | Chinese  | Supported |

### Localized Content Structure

```
meditations/stress/calm-your-mind/
├── metadata.json           # Primary (English)
├── metadata.es.json        # Spanish
├── metadata.fr.json        # French
├── audio.mp3               # Primary audio
├── audio.es.mp3            # Spanish audio
├── thumbnail.jpg           # Shared image
└── transcript.md           # Primary transcript
```

### Localized Metadata

```json
// metadata.es.json
{
  "$schema": "../../../schemas/meditation.schema.json",
  "baseRef": "calm-your-mind",
  "locale": "es",
  "title": "Calma Tu Mente",
  "description": "Una meditación guiada relajante para ayudarte a liberar la tensión...",
  "shortDescription": "Libera la tensión y encuentra paz interior.",
  "audio": {
    "file": "audio.es.mp3",
    "format": "mp3",
    "bitrate": 128
  },
  "transcript": {
    "file": "transcript.es.md",
    "language": "es"
  }
}
```

---

## Best Practices

### Content Quality Guidelines

**Audio:**

- Professional recording quality
- Clear, calm voice (for guided meditations)
- Appropriate pacing (not too fast)
- Smooth transitions between sections
- No background noise or artifacts

**Metadata:**

- Descriptive, accurate titles
- Compelling descriptions (sell the benefit)
- Appropriate tags for discoverability
- Accurate duration information
- Correct experience level assignment

**Images:**

- High-quality, professional images
- Calming, meditation-appropriate imagery
- Consistent style across content
- Proper alt text for accessibility

### SEO and Discoverability

**Titles:**

- Clear, descriptive
- Include primary benefit
- 3-10 words typical

**Descriptions:**

- Lead with benefits
- Include technique mentioned
- Target audience clear
- 2-4 sentences for short description

**Tags:**

- 5-15 relevant tags
- Include synonyms
- Include duration (e.g., "10 minutes")
- Include technique type

### Content Scheduling

**Release Cadence:**

- New meditations: 2-4 per week
- New courses: 1-2 per month
- Featured content rotation: Weekly

**Seasonal Content:**

- Plan holiday content 4-6 weeks ahead
- Create evergreen content for year-round use
- Update featured collections seasonally

### Quality Checklist

Before publishing, verify:

- [ ] Schema validation passes
- [ ] Audio plays completely without issues
- [ ] Image displays correctly at all sizes
- [ ] Teacher profile exists and is complete
- [ ] Related content links work
- [ ] Content tested on mobile app
- [ ] Accessibility requirements met
- [ ] Premium flag correct
- [ ] Category assignment accurate
- [ ] Tags comprehensive and accurate

---

## Additional Resources

- [API Documentation](../api/README.md) - Content API endpoints
- [Development Guide](./README.md) - Local development setup
- [Architecture](../architecture.md) - System overview
- [Content README](../../../apps/tara/content/README.md) - Quick reference
