|
| 1 | +import 'package:flutter/foundation.dart'; |
| 2 | + |
| 3 | +import '../../../core/services/ai_service.dart'; |
| 4 | +import '../models/pattern_analysis.dart'; |
| 5 | + |
| 6 | +/// Feeds the full [PatternAnalysis] into the AI and returns a short |
| 7 | +/// narrative that reads like the body talking to its human — keeping |
| 8 | +/// the BodyPress journal spirit alive on the Patterns page. |
| 9 | +class PatternNarrativeService { |
| 10 | + final AiService _ai; |
| 11 | + |
| 12 | + PatternNarrativeService(this._ai); |
| 13 | + |
| 14 | + /// Generate a 3–5 sentence narrative summarising the user's patterns. |
| 15 | + /// |
| 16 | + /// Returns `null` on any failure (no AI configured, network, etc.). |
| 17 | + Future<String?> generate(PatternAnalysis analysis) async { |
| 18 | + if (analysis.analyzedCaptures == 0) return null; |
| 19 | + |
| 20 | + final prompt = _buildPrompt(analysis); |
| 21 | + try { |
| 22 | + final result = await _ai.ask( |
| 23 | + prompt, |
| 24 | + systemPrompt: _systemPrompt, |
| 25 | + temperature: 0.75, |
| 26 | + maxTokens: 300, |
| 27 | + ); |
| 28 | + // Strip surrounding quotes if the model wraps it |
| 29 | + return result.trim().replaceAll(RegExp(r"""^["']+|["']+$"""), ''); |
| 30 | + } catch (e) { |
| 31 | + debugPrint('[PatternNarrative] AI error: $e'); |
| 32 | + return null; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // ── Prompts ───────────────────────────────────────────────────────────── |
| 37 | + |
| 38 | + static const _systemPrompt = ''' |
| 39 | +You are writing a short body-pattern narrative for BodyPress — a personal body journal app. |
| 40 | +Speak as the body itself, addressing the user in second person ("you"). |
| 41 | +Be warm, wise, and grounded in the data provided. No fluff. |
| 42 | +3–5 sentences maximum. No headings, no bullet points, no markdown. |
| 43 | +Highlight the most meaningful pattern or correlation you see. |
| 44 | +End with one forward-looking observation or gentle nudge.'''; |
| 45 | + |
| 46 | + String _buildPrompt(PatternAnalysis a) { |
| 47 | + final buf = StringBuffer(); |
| 48 | + buf.writeln('Here is the user\'s aggregated body-pattern data:'); |
| 49 | + buf.writeln(); |
| 50 | + |
| 51 | + // Captures |
| 52 | + buf.writeln( |
| 53 | + '• ${a.analyzedCaptures} of ${a.totalCaptures} captures analysed.', |
| 54 | + ); |
| 55 | + |
| 56 | + // Energy |
| 57 | + buf.writeln( |
| 58 | + '• Energy breakdown: ' |
| 59 | + 'high ${a.energyBreakdown['high'] ?? 0}, ' |
| 60 | + 'medium ${a.energyBreakdown['medium'] ?? 0}, ' |
| 61 | + 'low ${a.energyBreakdown['low'] ?? 0}.', |
| 62 | + ); |
| 63 | + |
| 64 | + // Top themes + trends |
| 65 | + if (a.topThemes.isNotEmpty) { |
| 66 | + final themed = a.topThemes |
| 67 | + .take(6) |
| 68 | + .map((e) { |
| 69 | + final trend = a.themeTrends[e.key]; |
| 70 | + final arrow = trend != null && trend.abs() > 0.15 |
| 71 | + ? (trend > 0 ? ' ↑' : ' ↓') |
| 72 | + : ''; |
| 73 | + return '${e.key} ×${e.value}$arrow'; |
| 74 | + }) |
| 75 | + .join(', '); |
| 76 | + buf.writeln('• Top themes: $themed.'); |
| 77 | + } |
| 78 | + |
| 79 | + // Theme–energy links |
| 80 | + if (a.themeEnergyMap.isNotEmpty) { |
| 81 | + final links = <String>[]; |
| 82 | + for (final entry in a.themeEnergyMap.entries) { |
| 83 | + final counts = entry.value; |
| 84 | + final total = |
| 85 | + (counts['high'] ?? 0) + |
| 86 | + (counts['medium'] ?? 0) + |
| 87 | + (counts['low'] ?? 0); |
| 88 | + if (total < 3) continue; |
| 89 | + final highPct = ((counts['high'] ?? 0) / total * 100).round(); |
| 90 | + final lowPct = ((counts['low'] ?? 0) / total * 100).round(); |
| 91 | + if (highPct >= 60) { |
| 92 | + links.add('"${entry.key}" → high energy $highPct%'); |
| 93 | + } else if (lowPct >= 60) { |
| 94 | + links.add('"${entry.key}" → low energy $lowPct%'); |
| 95 | + } |
| 96 | + } |
| 97 | + if (links.isNotEmpty) { |
| 98 | + buf.writeln('• Theme–energy correlations: ${links.join('; ')}.'); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + // Co-occurrences |
| 103 | + if (a.coOccurrences.isNotEmpty) { |
| 104 | + final pairs = a.coOccurrences |
| 105 | + .take(4) |
| 106 | + .map((e) => '${e.key} ×${e.value}') |
| 107 | + .join(', '); |
| 108 | + buf.writeln('• Co-occurring themes: $pairs.'); |
| 109 | + } |
| 110 | + |
| 111 | + // Rhythms |
| 112 | + if (a.timeOfDayDistribution.isNotEmpty) { |
| 113 | + final sorted = a.timeOfDayDistribution.entries.toList() |
| 114 | + ..sort((a, b) => b.value.compareTo(a.value)); |
| 115 | + final peak = sorted.first; |
| 116 | + buf.writeln( |
| 117 | + '• Peak capture window: ${peak.key} (${peak.value} captures).', |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + // Body signals |
| 122 | + if (a.bodySignalDistribution.isNotEmpty) { |
| 123 | + final sorted = a.bodySignalDistribution.entries.toList() |
| 124 | + ..sort((a, b) => b.value.compareTo(a.value)); |
| 125 | + final top = sorted.take(3).map((e) => '${e.key} ×${e.value}').join(', '); |
| 126 | + buf.writeln('• Body signals: $top.'); |
| 127 | + } |
| 128 | + |
| 129 | + // AI pattern hints |
| 130 | + if (a.aggregatedPatternHints.isNotEmpty) { |
| 131 | + final hints = a.aggregatedPatternHints |
| 132 | + .take(4) |
| 133 | + .map((e) => e.key) |
| 134 | + .join(', '); |
| 135 | + buf.writeln('• AI-observed patterns: $hints.'); |
| 136 | + } |
| 137 | + |
| 138 | + // Recurring signals |
| 139 | + if (a.topSignals.isNotEmpty) { |
| 140 | + final sigs = a.topSignals |
| 141 | + .take(4) |
| 142 | + .map((e) => '${e.key} ×${e.value}') |
| 143 | + .join(', '); |
| 144 | + buf.writeln('• Recurring signals: $sigs.'); |
| 145 | + } |
| 146 | + |
| 147 | + buf.writeln(); |
| 148 | + buf.writeln( |
| 149 | + 'Write a short narrative (3–5 sentences) that synthesises these ' |
| 150 | + 'patterns. Speak as the body. Be specific — reference the actual ' |
| 151 | + 'themes and data. Plain text only.', |
| 152 | + ); |
| 153 | + |
| 154 | + return buf.toString(); |
| 155 | + } |
| 156 | +} |
0 commit comments