health_local_data_convert.dart 22 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
import 'dart:math' as math;

import 'package:doublefeel_flutter/core/services/health_raw_data_core_service.dart';
import 'package:doublefeel_flutter/data/models/enums/app_enums.dart';
import 'package:doublefeel_flutter/data/models/health/activity/activity_burn_statistics_data_v2.dart';
import 'package:doublefeel_flutter/data/models/health/hrv/hrv_statistics_data.dart';
import 'package:doublefeel_flutter/data/models/health/sleep/sleep_statistics_data.dart';
import 'package:doublefeel_flutter/pigeon/health_kit_raw_data_api.g.dart';

const _sleepTypeInBed = 0;
const _sleepTypeAsleepUnspecified = 1;
const _sleepTypeAwake = 2;
const _sleepTypeAsleepCore = 3;
const _sleepTypeAsleepDeep = 4;
const _sleepTypeAsleepRem = 5;
const _sleepGoalMinutes = 8 * 60.0;

class LocalHealthDataConvert {
  const LocalHealthDataConvert._();

  static List<DateTime> rangeDays(int dateRangeType, int startDate) {
    final start = dateFromKey(startDate);
    final count = switch (dateRangeType) {
      0 => 7,
      1 => DateTime(start.year, start.month + 1, 0).day,
      2 => DateTime(start.year + 1).difference(DateTime(start.year)).inDays,
      3 => 1,
      _ => 1,
    };
    final first = dateRangeType == 2 ? DateTime(start.year) : start;
    return [for (var i = 0; i < count; i++) first.add(Duration(days: i))];
  }

  static List<DateTime> previousRangeDays(int dateRangeType, int startDate) {
    final start = dateFromKey(startDate);
    final previousStart = switch (dateRangeType) {
      0 => start.subtract(const Duration(days: 7)),
      1 => DateTime(start.year, start.month - 1),
      _ => null,
    };
    if (previousStart == null) return const <DateTime>[];
    return rangeDays(dateRangeType, dateKey(previousStart));
  }

  static SleepStatisticsData sleepStatistics({
    required List<DateTime> days,
    required List<DateTime> previousDays,
    required List<HealthKitRawDataPoint> sleepIntervals,
    required List<HealthKitRawDataPoint> heartRate,
  }) {
    final daily = [
      for (final day in days)
        _sleepDaySummary(
          day,
          sleepIntervals,
          heartRate,
        ),
    ];
    final validSleep = daily.where((e) => e.durationSeconds > 0).toList();
    final previousDaily = [
      for (final day in previousDays)
        _sleepDaySummary(
          day,
          sleepIntervals,
          heartRate,
        ),
    ];
    final previousValidSleep =
        previousDaily.where((e) => e.durationSeconds > 0).toList();
    final allSleepHr = validSleep.expand((e) => e.sleepHr).toList();

    return SleepStatisticsData(
      avgSleepDuration: _averageOrNull(
        validSleep.map((e) => e.durationSeconds).toList(),
      ),
      avgSleepScore: _averageOrNull(
        validSleep.map((e) => e.score).whereType<num>().toList(),
      ),
      avgSleepEvaluate: _averageOrNull(
        validSleep.map((e) => e.evaluate).whereType<num>().toList(),
      ),
      qoqAvgSleepDuration: _averageOrNull(
        previousValidSleep.map((e) => e.durationSeconds).toList(),
      ),
      qoqSleepScore: _averageOrNull(
        previousValidSleep.map((e) => e.score).whereType<num>().toList(),
      ),
      qoqSleepEvaluate: _averageOrNull(
        previousValidSleep.map((e) => e.evaluate).whereType<num>().toList(),
      ),
      sleepTrendList: [
        for (final item in daily)
          SleepTrendList(
            timeKey: dateKey(item.day),
            totalTime: item.durationSeconds,
            score: item.score,
            sleepEvaluate: item.evaluate,
          ),
      ],
      asleepTimeTrendList: [
        for (final item in daily)
          AsleepTimeTrendList(
            timeKey: dateKey(item.day),
            asleepTime: item.asleepTime,
          ),
      ],
      bestSleepInfo: _bestSleepInfo(validSleep),
      worstSleepInfo: _worstSleepInfo(validSleep),
      earliestSleepInfo: _earliestSleepInfo(validSleep),
      latestSleepInfo: _latestSleepInfo(validSleep),
      hrList: [
        for (final point in allSleepHr)
          SleepHrItem(time: point.endTime, value: point.value),
      ],
      avgHr: _averageOrNull(
        allSleepHr.map((e) => e.value).whereType<num>().toList(),
      ),
      maxHr: _maxOrNull(
        allSleepHr.map((e) => e.value).whereType<num>().toList(),
      ),
      minHr: _minOrNull(
        allSleepHr.map((e) => e.value).whereType<num>().toList(),
      ),
    );
  }

  static ActivityBurnStatisticsDataV2 activityBurnStatistics({
    required List<DateTime> days,
    required List<DateTime> previousDays,
    required List<HealthKitRawActivityDataPoint> activity,
    required List<HealthKitRawDataPoint> heartRate,
    required List<HealthKitRawDataPoint> sleepIntervals,
  }) {
    final daily = [
      for (final day in days)
        _activityDaySummary(
          day,
          activity,
        ),
    ];
    final previousDaily = [
      for (final day in previousDays)
        _activityDaySummary(
          day,
          activity,
        ),
    ];
    final latestWithGoal = _latestActivitySummaryWithGoal(daily);

    final data = ActivityBurnStatisticsDataV2(
      totalMove: _sum(daily.map((e) => e.move).toList()),
      totalSteps: _sum(daily.map((e) => e.steps).toList()),
      totalStand: _sum(daily.map((e) => e.standHours).toList()),
      totalExercise: _sum(daily.map((e) => e.exerciseSeconds).toList()),
      avgMove: _averageOrNull(daily.map((e) => e.move).toList()),
      qoqAvgMove: _averageOrNull(previousDaily.map((e) => e.move).toList()),
      activityTargetInfo: _activityTargetInfo(latestWithGoal),
      moveTrendList: [
        for (final item in daily)
          MoveTrendList(
            timeKey: dateKey(item.day).toString(),
            value: item.move,
          ),
      ],
      overallList: [
        for (final item in daily)
          OverallList(
            timeKey: dateKey(item.day),
            value: Value(
              move: item.move,
              stand: item.standHours,
              exercise: item.exerciseSeconds,
            ),
          ),
      ],
      hrList: [
        for (final point in heartRate)
          HrList(
            dataTime: point.endTime,
            date: dateKey(dayOf(point.endTime)),
            dataType: HealthDataUploadType.heartRate.type,
            value: point.value,
            isAsleep: _isInIntervals(point.endTime, sleepIntervals) ? 1 : 0,
          ),
      ],
      sleepTimeList: [
        for (final interval in sleepIntervals)
          SleepTimeList(
            fromTime: interval.startTime,
            toTime: interval.endTime,
          ),
      ],
    )..maxHr = _maxOrNull(
        heartRate.map((e) => e.value).whereType<num>().toList(),
      );
    return data;
  }

  static HrvStatisticsDataV2 hrvStatistics({
    required int dateRangeType,
    required List<DateTime> days,
    required List<HealthRawHrvStressPoint> hrvPoints,
    required List<HealthRawRealtimeStressPoint> realtimePoints,
  }) {
    final daily = [
      for (final day in days) _hrvDaySummary(day, hrvPoints, realtimePoints),
    ];
    final validDaily = daily.where((e) => e.hrvAverage != null).toList();
    final trendList = dateRangeType == 2
        ? _monthlyHrvTrend(validDaily)
        : [
            for (final item in daily)
              HrvTrendList(
                timeKey: dateKey(item.day),
                hrvAverage: item.hrvAverage,
                hrAverage: item.hrAverage,
                state: item.state,
              ),
          ];

    final distribution = _hrvDistribution(validDaily);
    final minDay = _extremeHrv(validDaily, min: true);
    final maxDay = _extremeHrv(validDaily, min: false);

    return HrvStatisticsDataV2(
      hrvTrendList: trendList,
      hrvDistributionList: [
        for (final entry in distribution.entries)
          HrvDistributionList(
            stressId: entry.key,
            dayCounts: entry.value,
          ),
      ],
      dailyDistributionList: [
        for (final item in validDaily)
          DailyDistributionList(
            date: dateKey(item.day),
            hrvLevel: item.state,
          ),
      ],
      hrvMin: minDay == null
          ? null
          : HrvMin(
              value: minDay.hrvAverage,
              timeList: [dateKey(minDay.day)],
            ),
      hrvMax: maxDay == null
          ? null
          : HrvMax(
              value: maxDay.hrvAverage,
              timeList: [dateKey(maxDay.day)],
            ),
    );
  }

  static _SleepDaySummary _sleepDaySummary(
    DateTime day,
    List<HealthKitRawDataPoint> sleepIntervals,
    List<HealthKitRawDataPoint> heartRate,
  ) {
    final windowStart = unixSeconds(day.subtract(const Duration(hours: 12)));
    final windowEnd = unixSeconds(day.add(const Duration(hours: 12)));
    final intervals = sleepIntervals
        .where((e) => e.endTime > windowStart && e.startTime < windowEnd)
        .toList();
    final summary = _sleepSummary(intervals, windowStart, windowEnd);
    final score = _sleepScore(summary);
    final sleepStageIntervals = intervals
        .where((e) => _isAsleepSleepType(e.dataType))
        .toList(growable: false);
    final heartRateIntervals =
        sleepStageIntervals.isEmpty ? intervals : sleepStageIntervals;
    final sleepHr = heartRate
        .where((point) => heartRateIntervals.any((interval) =>
            point.endTime > interval.startTime &&
            point.endTime <= interval.endTime))
        .toList();
    return _SleepDaySummary(
      day: day,
      durationSeconds: (summary.totalAsleepMinutes * 60).round(),
      asleepTime: intervals.isEmpty
          ? null
          : intervals.map((e) => e.startTime).reduce(math.min),
      score: score == 0 ? null : score,
      evaluate: _sleepEvaluate(score),
      sleepHr: sleepHr,
    );
  }

  static _ActivityDaySummary _activityDaySummary(
    DateTime day,
    List<HealthKitRawActivityDataPoint> activity,
  ) {
    final start = unixSeconds(day);
    final end = unixSeconds(day.add(const Duration(days: 1)));
    final dayActivity =
        activity.where((e) => e.endTime >= start && e.endTime < end).toList();
    final latest = dayActivity.isEmpty ? null : dayActivity.last;
    return _ActivityDaySummary(
      day: day,
      move: latest?.activeEnergyBurned ?? 0,
      steps: latest?.appleMoveTime ?? 0,
      standHours: latest?.appleStandHours ?? 0,
      exerciseSeconds: (latest?.appleExerciseTime ?? 0) * 60,
      moveGoal: latest?.activeEnergyBurnedGoal,
      stepGoal: latest?.appleMoveTimeGoal,
      standGoal: latest?.standHoursGoal,
      exerciseGoalSeconds: latest?.exerciseTimeGoal == null
          ? null
          : latest!.exerciseTimeGoal! * 60,
    );
  }

  static _ActivityDaySummary? _latestActivitySummaryWithGoal(
    List<_ActivityDaySummary> daily,
  ) {
    for (final item in daily.reversed) {
      if (item.hasGoal) return item;
    }
    return null;
  }

  static ActivityTargetInfo? _activityTargetInfo(
    _ActivityDaySummary? summary,
  ) {
    if (summary == null || !summary.hasGoal) return null;
    return ActivityTargetInfo(
      move: summary.moveGoal,
      step: summary.stepGoal,
      stand: summary.standGoal,
      exercise: summary.exerciseGoalSeconds,
    );
  }

  static _HrvDaySummary _hrvDaySummary(
    DateTime day,
    List<HealthRawHrvStressPoint> hrv,
    List<HealthRawRealtimeStressPoint> realtime,
  ) {
    final start = unixSeconds(day);
    final end = unixSeconds(day.add(const Duration(days: 1)));
    final dayHrv =
        hrv.where((e) => e.rawEndTime >= start && e.rawEndTime < end).toList();
    final dayRealtime = realtime
        .where((e) => e.rawEndTime >= start && e.rawEndTime < end)
        .toList();
    final hrvAverage = _averageOrNull(dayHrv.map((e) => e.result).toList());
    return _HrvDaySummary(
      day: day,
      hrvAverage: hrvAverage?.toDouble(),
      hrAverage:
          _averageOrNull(dayRealtime.map((e) => e.result).toList())?.toDouble(),
      state: hrvAverage == null ? null : _hrvStateFromValue(hrvAverage),
    );
  }

  static List<HrvTrendList> _monthlyHrvTrend(List<_HrvDaySummary> daily) {
    final byMonth = <int, List<_HrvDaySummary>>{};
    for (final item in daily) {
      byMonth.putIfAbsent(item.day.month, () => <_HrvDaySummary>[]).add(item);
    }
    return [
      for (final entry in byMonth.entries)
        HrvTrendList(
          timeKey: entry.key,
          hrvAverage: _averageOrNull(
            entry.value.map((e) => e.hrvAverage).whereType<num>().toList(),
          )?.toDouble(),
          hrAverage: _averageOrNull(
            entry.value.map((e) => e.hrAverage).whereType<num>().toList(),
          )?.toDouble(),
          state: _modeState(entry.value.map((e) => e.state).whereType<int>()),
        ),
    ];
  }

  static Map<int, int> _hrvDistribution(List<_HrvDaySummary> daily) {
    final result = <int, int>{};
    for (final item in daily) {
      final state = item.state;
      if (state == null) continue;
      result[state] = (result[state] ?? 0) + 1;
    }
    return result;
  }

  static _HrvDaySummary? _extremeHrv(
    List<_HrvDaySummary> daily, {
    required bool min,
  }) {
    _HrvDaySummary? result;
    for (final item in daily) {
      if (item.hrvAverage == null) continue;
      if (result == null) {
        result = item;
        continue;
      }
      if (min && item.hrvAverage! < result.hrvAverage!) result = item;
      if (!min && item.hrvAverage! > result.hrvAverage!) result = item;
    }
    return result;
  }

  static BestSleepInfo? _bestSleepInfo(List<_SleepDaySummary> daily) {
    final item = daily.where((e) => e.score != null).fold<_SleepDaySummary?>(
          null,
          (best, item) =>
              best == null || item.score! > best.score! ? item : best,
        );
    return item == null
        ? null
        : BestSleepInfo(
            timeKey: dateKey(item.day),
            totalTime: item.durationSeconds,
            score: item.score,
          );
  }

  static WorstSleepInfo? _worstSleepInfo(List<_SleepDaySummary> daily) {
    final item = daily.where((e) => e.score != null).fold<_SleepDaySummary?>(
          null,
          (worst, item) =>
              worst == null || item.score! < worst.score! ? item : worst,
        );
    return item == null
        ? null
        : WorstSleepInfo(
            timeKey: dateKey(item.day),
            totalTime: item.durationSeconds,
            score: item.score,
          );
  }

  static EarliestSleepInfo? _earliestSleepInfo(List<_SleepDaySummary> daily) {
    final sorted = daily.where((e) => e.asleepTime != null).toList()
      ..sort((a, b) => a.asleepTime!.compareTo(b.asleepTime!));
    final item = sorted.isEmpty ? null : sorted.first;
    return item == null
        ? null
        : EarliestSleepInfo(
            timeKey: dateKey(item.day),
            asleepTime: item.asleepTime,
          );
  }

  static LatestSleepInfo? _latestSleepInfo(List<_SleepDaySummary> daily) {
    final sorted = daily.where((e) => e.asleepTime != null).toList()
      ..sort((a, b) => b.asleepTime!.compareTo(a.asleepTime!));
    final item = sorted.isEmpty ? null : sorted.first;
    return item == null
        ? null
        : LatestSleepInfo(
            timeKey: dateKey(item.day),
            asleepTime: item.asleepTime,
          );
  }

  static _SleepSummary _sleepSummary(
    List<HealthKitRawDataPoint> intervals,
    int windowStart,
    int windowEnd,
  ) {
    var inBedMinutes = 0.0;
    var asleepMinutes = 0.0;
    var awakeMinutes = 0.0;
    var coreMinutes = 0.0;
    var deepMinutes = 0.0;
    var remMinutes = 0.0;
    var wakeCount = 0;
    var earliestStart = windowEnd;
    var latestEnd = windowStart;

    for (final interval in intervals) {
      final clippedStart = math.max(interval.startTime, windowStart);
      final clippedEnd = math.min(interval.endTime, windowEnd);
      final minutes = math.max(0, clippedEnd - clippedStart) / 60.0;
      if (minutes <= 0) continue;
      earliestStart = math.min(earliestStart, clippedStart);
      latestEnd = math.max(latestEnd, clippedEnd);
      switch (interval.dataType) {
        case _sleepTypeInBed:
          inBedMinutes += minutes;
          break;
        case _sleepTypeAwake:
          awakeMinutes += minutes;
          wakeCount += 1;
          break;
        case _sleepTypeAsleepCore:
          coreMinutes += minutes;
          asleepMinutes += minutes;
          break;
        case _sleepTypeAsleepDeep:
          deepMinutes += minutes;
          asleepMinutes += minutes;
          break;
        case _sleepTypeAsleepRem:
          remMinutes += minutes;
          asleepMinutes += minutes;
          break;
        case _sleepTypeAsleepUnspecified:
          asleepMinutes += minutes;
          break;
        default:
          asleepMinutes += minutes;
          break;
      }
    }

    if (inBedMinutes <= 0 && latestEnd > earliestStart) {
      inBedMinutes = (latestEnd - earliestStart) / 60.0;
    }
    if (inBedMinutes <= 0) {
      inBedMinutes = asleepMinutes + awakeMinutes;
    }

    return _SleepSummary(
      timeInBedMinutes: inBedMinutes,
      totalAsleepMinutes: asleepMinutes,
      awakeMinutes: awakeMinutes,
      coreMinutes: coreMinutes,
      deepMinutes: deepMinutes,
      remMinutes: remMinutes,
      wakeCount: wakeCount,
      sleepGoalMinutes: _sleepGoalMinutes,
    );
  }

  static int _sleepScore(_SleepSummary sleep) {
    if (sleep.timeInBedMinutes <= 0 || sleep.totalAsleepMinutes <= 0) return 0;
    final durationRatio = math.min(
      sleep.totalAsleepMinutes / sleep.sleepGoalMinutes,
      1.0,
    );
    final durationScore = durationRatio * 40;
    final efficiency = sleep.totalAsleepMinutes / sleep.timeInBedMinutes;
    final efficiencyScore = math.min(efficiency / 0.9, 1.0) * 25;
    final deepRatio = sleep.deepMinutes / sleep.totalAsleepMinutes;
    final deepScore = math.min(deepRatio / 0.18, 1.0) * 15;
    final remRatio = sleep.remMinutes / sleep.totalAsleepMinutes;
    final remScore = math.min(remRatio / 0.22, 1.0) * 10;
    final awakePenalty = math.min(
      sleep.wakeCount * 2 + sleep.awakeMinutes / 10,
      10,
    );
    final rawScore =
        durationScore + efficiencyScore + deepScore + remScore - awakePenalty;
    return _mappedSleepScore(rawScore);
  }

  static int _mappedSleepScore(num rawScore) {
    final clamped = rawScore.clamp(0, 100).toDouble();
    final mapped = switch (clamped) {
      < 64 => clamped / 64 * 60,
      < 74 => 60 + (clamped - 64) / 10 * 25,
      _ => math.min(math.max(86, 85 + (clamped - 74) / 26 * 15), 100),
    };
    return mapped.round().clamp(0, 100);
  }

  static num? _sleepEvaluate(int score) {
    if (score <= 0) return null;
    if (score >= 85) return 1;
    if (score >= 60) return 2;
    return 3;
  }

  static bool _isAsleepSleepType(int type) {
    return type == _sleepTypeAsleepUnspecified ||
        type == _sleepTypeAsleepCore ||
        type == _sleepTypeAsleepDeep ||
        type == _sleepTypeAsleepRem;
  }

  static int _hrvStateFromValue(num value) {
    if (value >= 30) return 4;
    if (value >= 21) return 3;
    if (value >= 17) return 2;
    return 1;
  }

  static int? _modeState(Iterable<int> states) {
    final counts = <int, int>{};
    for (final state in states) {
      counts[state] = (counts[state] ?? 0) + 1;
    }
    if (counts.isEmpty) return null;
    return counts.entries.reduce((a, b) => a.value >= b.value ? a : b).key;
  }

  static bool _isInIntervals(int time, List<HealthKitRawDataPoint> intervals) {
    return intervals.any((e) => time > e.startTime && time <= e.endTime);
  }

  static DateTime dateFromKey(int key) {
    final year = key ~/ 10000;
    final month = (key ~/ 100) % 100;
    final day = key % 100;
    return DateTime(year, month, day);
  }

  static DateTime dayOf(int seconds) {
    final date = DateTime.fromMillisecondsSinceEpoch(seconds * 1000);
    return DateTime(date.year, date.month, date.day);
  }

  static int dateKey(DateTime date) =>
      date.year * 10000 + date.month * 100 + date.day;

  static int unixSeconds(DateTime date) => date.millisecondsSinceEpoch ~/ 1000;

  static num _sum(List<num?> values) {
    return values.whereType<num>().fold<num>(0, (sum, value) => sum + value);
  }

  static num? _averageOrNull(List<num> values) {
    if (values.isEmpty) return null;
    return _sum(values) / values.length;
  }

  static num? _maxOrNull(List<num> values) {
    if (values.isEmpty) return null;
    return values.reduce(math.max);
  }

  static num? _minOrNull(List<num> values) {
    if (values.isEmpty) return null;
    return values.reduce(math.min);
  }
}

class _SleepDaySummary {
  const _SleepDaySummary({
    required this.day,
    required this.durationSeconds,
    required this.asleepTime,
    required this.score,
    required this.evaluate,
    required this.sleepHr,
  });

  final DateTime day;
  final num durationSeconds;
  final num? asleepTime;
  final num? score;
  final num? evaluate;
  final List<HealthKitRawDataPoint> sleepHr;
}

class _SleepSummary {
  const _SleepSummary({
    required this.timeInBedMinutes,
    required this.totalAsleepMinutes,
    required this.awakeMinutes,
    required this.coreMinutes,
    required this.deepMinutes,
    required this.remMinutes,
    required this.wakeCount,
    required this.sleepGoalMinutes,
  });

  final double timeInBedMinutes;
  final double totalAsleepMinutes;
  final double awakeMinutes;
  final double coreMinutes;
  final double deepMinutes;
  final double remMinutes;
  final int wakeCount;
  final double sleepGoalMinutes;
}

class _ActivityDaySummary {
  const _ActivityDaySummary({
    required this.day,
    required this.move,
    required this.steps,
    required this.standHours,
    required this.exerciseSeconds,
    required this.moveGoal,
    required this.stepGoal,
    required this.standGoal,
    required this.exerciseGoalSeconds,
  });

  final DateTime day;
  final num move;
  final num steps;
  final num standHours;
  final num exerciseSeconds;
  final num? moveGoal;
  final num? stepGoal;
  final num? standGoal;
  final num? exerciseGoalSeconds;

  bool get hasGoal =>
      moveGoal != null ||
      stepGoal != null ||
      standGoal != null ||
      exerciseGoalSeconds != null;
}

class _HrvDaySummary {
  const _HrvDaySummary({
    required this.day,
    required this.hrvAverage,
    required this.hrAverage,
    required this.state,
  });

  final DateTime day;
  final double? hrvAverage;
  final double? hrAverage;
  final int? state;
}