# Daily Reflections Feature - Neo4j Data Model

## Overview

The Daily Reflections feature provides users with daily prompts for self-reflection, tracks their responses over time, and generates insights about their learning and growth patterns.

## Node Types

### ReflectionPrompt
Represents a daily reflection question or prompt.

**Labels**: `REFLECTION_PROMPT`

**Properties**:
- `id` (String, UUID) - Unique identifier
- `category` (String) - Category: "learning", "mindfulness", "gratitude", "growth", "practice"
- `prompt_text` (String) - The reflection question/prompt
- `difficulty` (String) - "beginner", "intermediate", "advanced"
- `tags` (String[]) - Related topics (e.g., ["meditation", "awareness"])
- `created_at` (DateTime) - When created
- `active` (Boolean) - Whether prompt is actively used
- `language` (String) - Language code (e.g., "en", "es")
- `context_hint` (String, optional) - Additional context for the prompt

**Example**:
```cypher
CREATE (p:REFLECTION_PROMPT {
  id: "prompt-001",
  category: "learning",
  prompt_text: "What was the most valuable insight you gained from your practice today?",
  difficulty: "beginner",
  tags: ["learning", "insight", "practice"],
  created_at: datetime(),
  active: true,
  language: "en",
  context_hint: "Reflect on today's meditation or learning session"
})
```

### DailyReflection
Represents a user's response to a daily prompt.

**Labels**: `DAILY_REFLECTION`

**Properties**:
- `id` (String, UUID) - Unique identifier
- `user_id` (String) - User identifier
- `reflection_date` (Date) - Date of reflection (YYYY-MM-DD)
- `response_text` (String) - User's written reflection
- `word_count` (Integer) - Number of words in response
- `mood_rating` (Integer, 1-5, optional) - User's mood at time of reflection
- `energy_level` (Integer, 1-5, optional) - User's energy level
- `sentiment_score` (Float, -1 to 1, optional) - AI-analyzed sentiment
- `created_at` (DateTime) - When reflection was created
- `updated_at` (DateTime) - Last update time
- `time_spent_seconds` (Integer) - Time spent writing reflection
- `completed` (Boolean) - Whether reflection is complete
- `privacy` (String) - "private", "friends", "public"

**Example**:
```cypher
CREATE (r:DAILY_REFLECTION {
  id: "refl-001",
  user_id: "user-123",
  reflection_date: date("2025-01-15"),
  response_text: "Today I realized that mindful breathing helps me...",
  word_count: 87,
  mood_rating: 4,
  energy_level: 3,
  sentiment_score: 0.75,
  created_at: datetime(),
  updated_at: datetime(),
  time_spent_seconds: 180,
  completed: true,
  privacy: "private"
})
```

### ReflectionInsight
AI-generated or user-identified insights from reflections.

**Labels**: `REFLECTION_INSIGHT`

**Properties**:
- `id` (String, UUID) - Unique identifier
- `user_id` (String) - User identifier
- `insight_type` (String) - "pattern", "growth", "challenge", "achievement"
- `insight_text` (String) - The insight description
- `confidence_score` (Float, 0-1) - AI confidence in insight
- `identified_at` (DateTime) - When insight was identified
- `source` (String) - "ai_generated" or "user_identified"
- `time_period` (String) - Time range (e.g., "last_7_days", "last_30_days")
- `supporting_reflection_ids` (String[]) - IDs of reflections supporting this insight

**Example**:
```cypher
CREATE (i:REFLECTION_INSIGHT {
  id: "insight-001",
  user_id: "user-123",
  insight_type: "pattern",
  insight_text: "You tend to have deeper insights when practicing in the morning",
  confidence_score: 0.85,
  identified_at: datetime(),
  source: "ai_generated",
  time_period: "last_30_days",
  supporting_reflection_ids: ["refl-001", "refl-005", "refl-012"]
})
```

### ReflectionStreak
Tracks user's consistency in daily reflections.

**Labels**: `REFLECTION_STREAK`

**Properties**:
- `id` (String, UUID) - Unique identifier
- `user_id` (String) - User identifier
- `current_streak` (Integer) - Current consecutive days
- `longest_streak` (Integer) - Longest streak ever achieved
- `total_reflections` (Integer) - Total number of reflections
- `streak_start_date` (Date) - When current streak started
- `last_reflection_date` (Date) - Most recent reflection date
- `updated_at` (DateTime) - Last update time

**Example**:
```cypher
CREATE (s:REFLECTION_STREAK {
  id: "streak-001",
  user_id: "user-123",
  current_streak: 7,
  longest_streak: 21,
  total_reflections: 45,
  streak_start_date: date("2025-01-08"),
  last_reflection_date: date("2025-01-15"),
  updated_at: datetime()
})
```

## Relationships

### USER -[:COMPLETED]-> DAILY_REFLECTION
Links user to their reflections.

**Properties**:
- `completed_at` (DateTime) - When completed

### DAILY_REFLECTION -[:RESPONDS_TO]-> REFLECTION_PROMPT
Links reflection to its prompt.

**Properties**: None

### DAILY_REFLECTION -[:REFERENCES]-> NOTE
Links reflection to related notes (optional).

**Properties**:
- `relevance_score` (Float, 0-1) - How relevant the note is

### DAILY_REFLECTION -[:ATTACHED_TO]-> CONTENT
Links reflection to content that inspired it (lecture, meditation, etc.).

**Properties**:
- `content_type` (String) - Type of content
- `timestamp` (Integer, optional) - Specific moment in content

### USER -[:HAS_INSIGHT]-> REFLECTION_INSIGHT
Links user to their insights.

**Properties**:
- `acknowledged` (Boolean) - Whether user has seen this insight

### REFLECTION_INSIGHT -[:DERIVED_FROM]-> DAILY_REFLECTION
Links insights to the reflections they're based on.

**Properties**:
- `weight` (Float, 0-1) - How much this reflection contributed to the insight

### USER -[:MAINTAINS_STREAK]-> REFLECTION_STREAK
Links user to their streak.

**Properties**: None

### REFLECTION_PROMPT -[:FOLLOWS]-> REFLECTION_PROMPT
Creates a sequence of related prompts.

**Properties**:
- `sequence_number` (Integer) - Order in sequence
- `sequence_id` (String) - ID of the sequence

## Indexes and Constraints

```cypher
// Constraints
CREATE CONSTRAINT reflection_prompt_id IF NOT EXISTS FOR (p:REFLECTION_PROMPT) REQUIRE p.id IS UNIQUE;
CREATE CONSTRAINT daily_reflection_id IF NOT EXISTS FOR (r:DAILY_REFLECTION) REQUIRE r.id IS UNIQUE;
CREATE CONSTRAINT reflection_insight_id IF NOT EXISTS FOR (i:REFLECTION_INSIGHT) REQUIRE i.id IS UNIQUE;
CREATE CONSTRAINT reflection_streak_id IF NOT EXISTS FOR (s:REFLECTION_STREAK) REQUIRE s.id IS UNIQUE;

// Indexes for performance
CREATE INDEX reflection_by_user IF NOT EXISTS FOR (r:DAILY_REFLECTION) ON (r.user_id);
CREATE INDEX reflection_by_date IF NOT EXISTS FOR (r:DAILY_REFLECTION) ON (r.reflection_date);
CREATE INDEX reflection_by_user_date IF NOT EXISTS FOR (r:DAILY_REFLECTION) ON (r.user_id, r.reflection_date);
CREATE INDEX prompt_by_category IF NOT EXISTS FOR (p:REFLECTION_PROMPT) ON (p.category);
CREATE INDEX prompt_by_active IF NOT EXISTS FOR (p:REFLECTION_PROMPT) ON (p.active);
CREATE INDEX insight_by_user IF NOT EXISTS FOR (i:REFLECTION_INSIGHT) ON (i.user_id);
CREATE INDEX streak_by_user IF NOT EXISTS FOR (s:REFLECTION_STREAK) ON (s.user_id);
```

## Data Model Diagram

```
┌─────────┐                         ┌──────────────────┐
│  USER   │──[:COMPLETED]────────→ │ DAILY_REFLECTION │
└─────────┘                         └──────────────────┘
     │                                      │
     │                                      │
     │                                      ├─[:RESPONDS_TO]──→┌─────────────────────┐
     │                                      │                   │ REFLECTION_PROMPT   │
     │                                      │                   └─────────────────────┘
     │                                      │                            │
     │                                      ├─[:REFERENCES]─────→┌─────┐│
     │                                      │                     │NOTE ││
     │                                      │                     └─────┘│
     │                                      │                            │
     │                                      ├─[:ATTACHED_TO]────→┌─────────┐
     │                                      │                     │CONTENT  │
     │                                      │                     └─────────┘
     │                                      │
     ├─[:HAS_INSIGHT]────→┌─────────────────────┐
     │                     │ REFLECTION_INSIGHT  │←──[:DERIVED_FROM]──┘
     │                     └─────────────────────┘
     │
     └─[:MAINTAINS_STREAK]→┌─────────────────┐
                            │ REFLECTION_STREAK │
                            └─────────────────┘
```

## Example Queries

### Get User's Recent Reflections
```cypher
MATCH (u:USER {id: $userId})-[:COMPLETED]->(r:DAILY_REFLECTION)
WHERE r.reflection_date >= date() - duration('P7D')
RETURN r
ORDER BY r.reflection_date DESC
```

### Get Daily Prompt for User
```cypher
MATCH (p:REFLECTION_PROMPT {active: true})
WHERE p.language = $userLanguage
  AND NOT EXISTS {
    MATCH (:USER {id: $userId})-[:COMPLETED]->(r:DAILY_REFLECTION {reflection_date: date()})
      -[:RESPONDS_TO]->(p)
  }
WITH p
ORDER BY rand()
LIMIT 1
RETURN p
```

### Calculate Reflection Streak
```cypher
MATCH (u:USER {id: $userId})-[:COMPLETED]->(r:DAILY_REFLECTION)
WITH r, r.reflection_date as refDate
ORDER BY refDate DESC
WITH collect(refDate) as dates
UNWIND range(0, size(dates)-1) as i
WITH dates[i] as current, dates[i+1] as previous
WHERE previous IS NOT NULL
  AND duration.between(previous, current).days = 1
RETURN count(*) + 1 as currentStreak
```

### Find Patterns in Reflections
```cypher
MATCH (u:USER {id: $userId})-[:COMPLETED]->(r:DAILY_REFLECTION)
WHERE r.reflection_date >= date() - duration('P30D')
  AND r.sentiment_score IS NOT NULL
WITH avg(r.sentiment_score) as avgSentiment,
     stdev(r.sentiment_score) as sentimentStdDev,
     collect({date: r.reflection_date, mood: r.mood_rating, sentiment: r.sentiment_score}) as data
RETURN avgSentiment, sentimentStdDev, data
```

### Get Insights for User
```cypher
MATCH (u:USER {id: $userId})-[:HAS_INSIGHT]->(i:REFLECTION_INSIGHT)
WHERE i.identified_at >= datetime() - duration('P30D')
OPTIONAL MATCH (i)-[:DERIVED_FROM]->(r:DAILY_REFLECTION)
RETURN i, collect(r) as supporting_reflections
ORDER BY i.confidence_score DESC, i.identified_at DESC
```

## API Endpoints (to be implemented)

### Reflection Management
- `POST /v1/reflections` - Create daily reflection
- `GET /v1/reflections` - List user's reflections (with filters)
- `GET /v1/reflections/:id` - Get single reflection
- `PUT /v1/reflections/:id` - Update reflection
- `DELETE /v1/reflections/:id` - Delete reflection

### Prompts
- `GET /v1/reflections/prompt/today` - Get today's prompt
- `GET /v1/reflections/prompts` - List available prompts
- `POST /v1/reflections/prompts` - Create custom prompt (admin)

### Insights & Analytics
- `GET /v1/reflections/insights` - Get user's insights
- `GET /v1/reflections/patterns` - Get reflection patterns
- `GET /v1/reflections/stats` - Get reflection statistics

### Streaks
- `GET /v1/reflections/streak` - Get current streak
- `GET /v1/reflections/calendar` - Get reflection calendar

## Privacy Considerations

1. **Default Privacy**: All reflections are private by default
2. **User Control**: Users can choose to share specific reflections
3. **AI Analysis**: Users can opt-in/out of AI insight generation
4. **Data Retention**: Reflections are kept indefinitely unless user deletes
5. **Export**: Users can export all their reflections in JSON/PDF format

## Integration Points

1. **Notes Service**: Link reflections to notes
2. **Content Service**: Link reflections to content that inspired them
3. **Notification Service**: Send daily reflection reminders
4. **AI Service**: Generate insights from reflection patterns
5. **User Preferences**: Store reflection preferences and settings
