Skip to content

Offline gym log for Android. No account, no ads, no internet.

28.6 KB
Raw Blame
import 'dart:convert';
import 'dart:math' as math;

import 'package:archive/archive.dart';

import '../catalog/opengym_ids.dart';

const double _lbPerKg = 2.2046226218;

enum ImportFormat {
  hevy,
  strong,
  lyfta,
  fitbod,
  liftosaur,
  stronglifts,
  jefit,
  fitnotes,
  gymmane,
  openGym,
  generic,
  hevyWeights,
  strongWeights,
  weights,
  unknown,
}

extension ImportFormatX on ImportFormat {
  bool get isWeights =>
      this == ImportFormat.hevyWeights ||
      this == ImportFormat.strongWeights ||
      this == ImportFormat.weights;
}

class ParsedSet {
  ParsedSet(this.reps, this.weightKg, {this.rpe, this.note = '', this.sec, this.km});
  final int reps;
  final int? sec;
  final double? km;
  final String note;
  final double weightKg;
  final double? rpe;
}

class ParsedWeight {
  ParsedWeight(this.date, this.kg);
  final DateTime date;
  final double kg;
}

class ParsedExercise {
  ParsedExercise(this.name, this.muscle, {this.id});
  final String name;
  final String? muscle;
  final String? id;
  final List<ParsedSet> sets = [];
}

class ParsedSession {
  ParsedSession(this.date, this.durationSec);
  final DateTime date;
  final int durationSec;
  final List<ParsedExercise> exercises = [];
}

class ImportResult {
  ImportResult(this.format, this.sessions, {this.weights = const []});
  final ImportFormat format;
  final List<ParsedSession> sessions;
  final List<ParsedWeight> weights;

  bool get isEmpty => sessions.isEmpty && weights.isEmpty;
}

class _Fmt {
  const _Fmt({
    required this.date,
    required this.exercise,
    required this.reps,
    required this.weightKg,
    required this.weightLb,
    this.weightPlain,
    this.group,
    this.muscle,
    this.endDate,
    this.durationText,
    this.durationSec,
    this.setType,
    this.warmupFlag,
    this.unit,
  });

  final List<String> date;
  final List<String> exercise;
  final List<String> reps;
  final List<String> weightKg;
  final List<String> weightLb;
  final List<String>? weightPlain;
  final List<String>? group;
  final List<String>? muscle;
  final List<String>? endDate;
  final List<String>? durationText;
  final List<String>? durationSec;
  final List<String>? setType;
  final List<String>? warmupFlag;
  final List<String>? unit;
  List<String> get rpe => const ['rpe', 'completed rpe'];
  List<String> get setSec => const ['duration_seconds', 'seconds', 'duration (s)', 'time (s)', 'set duration'];
  List<String> get setClock => const ['time', 'set time'];
  List<String> get km => const ['distance_km', 'distance (km)', 'km'];
  List<String> get miles => const ['distance_miles', 'distance_mi', 'distance (mi)', 'distance (miles)', 'miles'];
  List<String> get meters => const ['distance_m', 'distance (m)', 'distance (meters)', 'distance (metres)', 'meters', 'metres'];
  List<String> get setOrder => const ['set order', 'set_order'];
  List<String> get note => const ['note', 'notes', 'set_notes'];
  List<String> get rir => const ['rir'];
  List<String> get effort => const ['rir/rpe', 'rpe/rir'];
}

const _formats = <ImportFormat, _Fmt>{
  ImportFormat.hevy: _Fmt(
    date: ['start_time'],
    endDate: ['end_time'],
    group: ['title'],
    exercise: ['exercise_title'],
    reps: ['reps'],
    weightKg: ['weight_kg'],
    weightLb: ['weight_lbs', 'weight_lb'],
    setType: ['set_type'],
  ),
  ImportFormat.strong: _Fmt(
    date: ['date'],
    group: ['workout #', 'workout name'],
    exercise: ['exercise name'],
    reps: ['reps'],
    weightKg: ['weight (kg)'],
    weightLb: ['weight (lbs)', 'weight (lb)'],
    weightPlain: ['weight'],
    durationText: ['duration'],
    durationSec: ['duration (sec)', 'duration (seconds)'],
  ),
  ImportFormat.lyfta: _Fmt(
    date: ['date'],
    group: ['title'],
    exercise: ['exercise'],
    reps: ['reps'],
    weightKg: [],
    weightLb: [],
    weightPlain: ['weight'],
    durationText: ['duration'],
    setType: ['set type'],
  ),
  ImportFormat.fitbod: _Fmt(
    date: ['date'],
    exercise: ['exercise'],
    reps: ['reps'],
    weightKg: ['weight(kg)', 'weight (kg)'],
    weightLb: ['weight(lbs)', 'weight(lb)', 'weight (lbs)'],
    warmupFlag: ['iswarmup'],
  ),
  ImportFormat.liftosaur: _Fmt(
    date: ['workout datetime'],
    group: ['day name'],
    exercise: ['exercise'],
    reps: ['completed reps'],
    weightKg: [],
    weightLb: [],
    weightPlain: ['completed weight value'],
    unit: ['completed weight unit'],
    warmupFlag: ['is warmup set?'],
  ),
  ImportFormat.fitnotes: _Fmt(
    date: ['date'],
    exercise: ['exercise'],
    reps: ['reps'],
    weightKg: ['weight (kg)'],
    weightLb: ['weight (lbs)', 'weight (lb)'],
    weightPlain: ['weight'],
    muscle: ['category'],
  ),
  ImportFormat.gymmane: _Fmt(
    date: ['date'],
    exercise: ['exercise'],
    reps: ['reps'],
    weightKg: ['weight_kg'],
    weightLb: [],
    setType: ['set_type'],
    muscle: ['muscle'],
  ),
  ImportFormat.generic: _Fmt(
    date: _genericDateCols,
    exercise: _genericExerciseCols,
    reps: _genericRepCols,
    weightKg: _weightKgCols,
    weightLb: _weightLbCols,
    weightPlain: _genericWeightCols,
    group: ['workout', 'routine', 'rutina', 'plan', 'entrenamiento', 'training'],
    muscle: ['category', 'muscle', 'categoria', 'categoría', 'musculo', 'músculo'],
  ),
};

const _genericDateCols = [
  'date', 'fecha', 'datum', 'data', 'day', 'dia', 'día', 'timestamp', 'start_time', 'time',
];
const _genericExerciseCols = [
  'exercise', 'exercise name', 'exercise_name', 'ejercicio', 'exercicio', 'exercício',
  'übung', 'ubung', 'uebung', 'esercizio', 'exercice', 'name', 'nombre',
];
const _genericRepCols = [
  'reps', 'rep', 'repetitions', 'repeticiones', 'repetições', 'repeticoes',
  'wiederholungen', 'ripetizioni', 'répétitions', 'repetitions_count',
];
const _genericWeightCols = ['weight', 'peso', 'gewicht', 'poids', 'carga'];

const _anyWeight = ['weight (kg)', 'weight (lbs)', 'weight (lb)', 'weight', 'weight_kg'];
const _weightKgCols = ['weight_kg', 'weight (kg)', 'weight kg', 'peso (kg)'];
const _weightLbCols = ['weight_lbs', 'weight_lb', 'weight (lbs)', 'weight (lb)', 'weight lbs'];
const _dateCols = ['date', 'fecha', 'start_time', 'time'];

ImportFormat detectFormat(String csv) {
  if (_backupOf(csv) != null) return ImportFormat.openGym;
  if (_isJefit(csv)) return ImportFormat.jefit;
  final cols = _header(csv);
  if (cols.isEmpty) return ImportFormat.unknown;
  if (cols.contains('date (yyyy/mm/dd)') && cols.contains('exercise') && cols.any(_slRepsCol.hasMatch)) {
    return ImportFormat.stronglifts;
  }
  if (cols.contains('exercise_title') && cols.contains('start_time')) return ImportFormat.hevy;
  if (cols.contains('workout datetime') && cols.contains('is warmup set?')) return ImportFormat.liftosaur;
  if (cols.contains('exercise name') && cols.contains('set order')) return ImportFormat.strong;
  if (cols.contains('exercise') &&
      cols.contains('set type') &&
      cols.contains('title') &&
      (cols.contains('rir/rpe') || cols.any((c) => c.startsWith('recordlevel')))) {
    return ImportFormat.lyfta;
  }
  if (cols.contains('exercise') && cols.contains('reps') && cols.contains('iswarmup')) {
    return ImportFormat.fitbod;
  }
  if (cols.contains('weight_kg') && (cols.contains('est_1rm_kg') || cols.contains('volume_kg'))) {
    return ImportFormat.gymmane;
  }
  if (cols.contains('exercise') && cols.contains('category') && _pick(cols, _anyWeight) != null) {
    return ImportFormat.fitnotes;
  }
  final exerciseCol = _pick(cols, _genericExerciseCols);
  final repsCol = _pick(cols, _genericRepCols);
  final genericDate = _pick(cols, _genericDateCols);
  if (exerciseCol != null && repsCol != null && genericDate != null) return ImportFormat.generic;
  final hasExercise = cols.any((c) => c.contains('exercise') || c.contains('ejercicio'));
  final dateCol = _pick(cols, _dateCols);
  final weightCol = _pick(cols, [..._weightKgCols, ..._weightLbCols, 'weight', 'peso']);
  if (!hasExercise && dateCol != null && weightCol != null) {
    if (cols.contains('fat_percent') || cols.contains('weight_lbs') && cols.length > 3) {
      return ImportFormat.hevyWeights;
    }
    if (cols.length <= 3) return ImportFormat.strongWeights;
    return ImportFormat.weights;
  }
  return ImportFormat.unknown;
}

bool needsUnitChoice(String csv) {
  final format = detectFormat(csv);
  if (format == ImportFormat.jefit) return true;
  final cols = _header(csv);
  if (format.isWeights) {
    if (_pick(cols, _weightKgCols) != null || _pick(cols, _weightLbCols) != null) return false;
    return _pick(cols, ['weight', 'peso']) != null;
  }
  final fmt = _formats[format];
  if (fmt == null) return false;
  if (_pick(cols, fmt.unit ?? const []) != null) return false;
  if (_pick(cols, fmt.weightKg) != null || _pick(cols, fmt.weightLb) != null) return false;
  return _pick(cols, fmt.weightPlain ?? const []) != null;
}

final _slRepsCol = RegExp(r'^set (\d+) \(reps\)$');

String _cell(List<String> row, int i) => i < 0 || i >= row.length ? '' : row[i].trim();

(int, int)? _clock(String s) {
  final m = RegExp(r'^(\d{1,2}):(\d{2})\s*([ap])?\.?\s*m?\.?$', caseSensitive: false).firstMatch(s.trim());
  if (m == null) return null;
  var h = int.parse(m.group(1)!);
  final min = int.parse(m.group(2)!);
  final half = m.group(3)?.toLowerCase();
  if (half != null) h = h % 12 + (half == 'p' ? 12 : 0);
  return h < 24 && min < 60 ? (h, min) : null;
}

ImportResult _parseStrongLifts(String csv) {
  final rows = _rows(csv, _delimiter(csv));
  if (rows.length < 2) return ImportResult(ImportFormat.stronglifts, const []);
  final head = rows.first.map(_norm).toList();
  final date = head.indexOf('date (yyyy/mm/dd)');
  final number = head.indexOf('workout');
  final exercise = head.indexOf('exercise');
  final start = head.indexOf('start time (h:mm)');
  final end = head.indexOf('end time (h:mm)');
  final notes = head.indexOf('notes');
  final pairs = <(int, int, bool)>[];
  for (var i = 0; i < head.length; i++) {
    final m = _slRepsCol.firstMatch(head[i]);
    if (m == null) continue;
    final kg = head.indexOf('set ${m.group(1)} (kg)');
    final lb = head.indexOf('set ${m.group(1)} (lb)');
    if (kg >= 0) {
      pairs.add((i, kg, false));
    } else if (lb >= 0) {
      pairs.add((i, lb, true));
    }
  }
  final sessions = <String, ParsedSession>{};
  for (final row in rows.skip(1)) {
    final day = RegExp(r'^(\d{4})[/-](\d{1,2})[/-](\d{1,2})$').firstMatch(_cell(row, date));
    final name = _cell(row, exercise);
    if (day == null || name.isEmpty) continue;
    final from = _clock(_cell(row, start));
    final to = _clock(_cell(row, end));
    final session = sessions.putIfAbsent('${_cell(row, date)}#${_cell(row, number)}', () {
      final when = DateTime(int.parse(day.group(1)!), int.parse(day.group(2)!), int.parse(day.group(3)!),
          from?.$1 ?? 0, from?.$2 ?? 0);
      var seconds = 0;
      if (from != null && to != null) {
        final minutes = (to.$1 * 60 + to.$2) - (from.$1 * 60 + from.$2);
        if (minutes > 0) seconds = minutes * 60;
      }
      return ParsedSession(when, seconds);
    });
    final parsed = ParsedExercise(name, null);
    final note = _setNote(_cell(row, notes));
    for (final (repsCol, weightCol, lb) in pairs) {
      final reps = double.tryParse(_cell(row, repsCol).replaceAll(',', '.'))?.round() ?? 0;
      if (reps <= 0) continue;
      final weight = double.tryParse(_cell(row, weightCol).replaceAll(',', '.')) ?? 0;
      parsed.sets.add(ParsedSet(reps, lb ? weight / _lbPerKg : weight, note: parsed.sets.isEmpty ? note : ''));
    }
    if (parsed.sets.isNotEmpty) session.exercises.add(parsed);
  }
  return ImportResult(ImportFormat.stronglifts, [
    for (final s in sessions.values)
      if (s.exercises.isNotEmpty) s,
  ]);
}

bool _isJefit(String text) =>
    RegExp(r'^\s*###\s*EXERCISE LOGS\s*#+\s*$', multiLine: true, caseSensitive: false).hasMatch(text);

Map<String, List<List<String>>> _jefitSections(String text) {
  final lines = <String, List<String>>{};
  List<String>? current;
  for (final line in text.replaceFirst('', '').split(RegExp(r'\r?\n'))) {
    final m = RegExp(r'^\s*###\s*(.*?)\s*#+\s*$').firstMatch(line);
    if (m != null) {
      current = lines.putIfAbsent(m.group(1)!.toLowerCase(), () => []);
      continue;
    }
    if (current != null && line.trim().isNotEmpty) current.add(line);
  }
  return {
    for (final e in lines.entries)
      if (e.value.isNotEmpty) e.key: _rows(e.value.join('\n'), ','),
  };
}

ImportResult _parseJefit(String text, bool isLb) {
  final sections = _jefitSections(text);
  final logs = sections['exercise logs'];
  if (logs == null || logs.length < 2) return ImportResult(ImportFormat.jefit, const []);
  final head = logs.first.map(_norm).toList();
  final sessionCol = head.indexOf('belongsession');
  final nameCol = head.indexOf('ename');
  final dateCol = head.indexOf('mydate');
  final logsCol = head.indexOf('logs');
  if (nameCol < 0 || dateCol < 0 || logsCol < 0) return ImportResult(ImportFormat.jefit, const []);
  final starts = <String, (DateTime, int)>{};
  final info = sections['workout sessions'];
  if (info != null && info.length > 1) {
    final h = info.first.map(_norm).toList();
    final id = h.indexOf('_id');
    final st = h.indexOf('starttime');
    final total = h.indexOf('total_time');
    if (id >= 0 && st >= 0) {
      for (final row in info.skip(1)) {
        final seconds = int.tryParse(_cell(row, st));
        if (seconds == null || seconds <= 0) continue;
        starts[_cell(row, id)] =
            (DateTime.fromMillisecondsSinceEpoch(seconds * 1000), int.tryParse(_cell(row, total)) ?? 0);
      }
    }
  }
  final sessions = <String, ParsedSession>{};
  final setPattern = RegExp(r'^\s*(\d+(?:\.\d+)?)?\s*x\s*(\d+)\s*$', caseSensitive: false);
  for (final row in logs.skip(1)) {
    final d = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(_cell(row, dateCol));
    final name = _cell(row, nameCol);
    if (d == null || name.isEmpty) continue;
    final day = DateTime(int.parse(d.group(1)!), int.parse(d.group(2)!), int.parse(d.group(3)!));
    final id = sessionCol >= 0 ? _cell(row, sessionCol) : '';
    final start = starts[id];
    final sameDay = start != null && _dayId(start.$1) == _dayId(day);
    final session = sessions.putIfAbsent(
        id.isEmpty ? _dayId(day) : id, () => ParsedSession(sameDay ? start.$1 : day, sameDay ? start.$2 : 0));
    final parsed = ParsedExercise(name, null);
    for (final part in _cell(row, logsCol).split(',')) {
      final m = setPattern.firstMatch(part);
      if (m == null) continue;
      final reps = int.parse(m.group(2)!);
      if (reps <= 0) continue;
      final weight = double.tryParse(m.group(1) ?? '') ?? 0;
      parsed.sets.add(ParsedSet(reps, isLb ? weight / _lbPerKg : weight));
    }
    if (parsed.sets.isNotEmpty) session.exercises.add(parsed);
  }
  return ImportResult(ImportFormat.jefit, [
    for (final s in sessions.values)
      if (s.exercises.isNotEmpty) s,
  ]);
}

String? openGymBackupFromZip(List<int> bytes) {
  Archive archive;
  try {
    archive = ZipDecoder().decodeBytes(bytes);
  } catch (_) {
    return null;
  }
  for (final file in archive.files) {
    if (!file.isFile || file.name.split('/').last != 'opengym-backup.json') continue;
    try {
      final text = utf8.decode(file.content as List<int>, allowMalformed: true);
      return _backupOf(text) == null ? null : text;
    } catch (_) {
      return null;
    }
  }
  return null;
}

String? weightCsvFromZip(List<int> bytes) {
  Archive archive;
  try {
    archive = ZipDecoder().decodeBytes(bytes);
  } catch (_) {
    return null;
  }
  String? best;
  for (final file in archive.files) {
    if (!file.isFile) continue;
    final name = file.name.split('/').last.toLowerCase();
    if (!name.endsWith('.csv')) continue;
    if (!name.contains('weight') && !name.contains('peso')) continue;
    if (name.contains('percentage') || name.contains('fat')) continue;
    String text;
    try {
      text = String.fromCharCodes(file.content as List<int>);
    } catch (_) {
      continue;
    }
    best = text;
    if (name == 'weight.csv') break;
  }
  return best;
}

List<ParsedWeight> parseWeights(String csv, {bool isLb = false}) {
  final rows = _rows(csv, _delimiter(csv));
  if (rows.length < 2) return const [];

  final index = <String, int>{};
  for (var i = 0; i < rows.first.length; i++) {
    index[_norm(rows.first[i])] = i;
  }
  final cols = index.keys.toList();

  final dateCol = _pick(cols, _dateCols);
  if (dateCol == null) return const [];
  final kgCol = _pick(cols, _weightKgCols);
  final lbCol = _pick(cols, _weightLbCols);
  final plainCol = kgCol == null && lbCol == null ? _pick(cols, ['weight', 'peso']) : null;
  if (kgCol == null && lbCol == null && plainCol == null) return const [];

  String cell(List<String> row, String? name) {
    final i = name == null ? null : index[name];
    return (i == null || i >= row.length) ? '' : row[i].trim();
  }

  final out = <ParsedWeight>[];
  for (final row in rows.skip(1)) {
    final date = _parseDate(cell(row, dateCol));
    if (date == null) continue;
    final kg = _weightKg(
      kg: cell(row, kgCol),
      lb: cell(row, lbCol),
      plain: cell(row, plainCol),
      plainIsLb: isLb,
    );
    if (kg <= 0) continue;
    out.add(ParsedWeight(date, kg));
  }
  return out;
}

ImportResult parseImport(String csv, {bool isLb = false}) {
  final format = detectFormat(csv);
  if (format == ImportFormat.openGym) return _parseOpenGym(_backupOf(csv)!);
  if (format == ImportFormat.stronglifts) return _parseStrongLifts(csv);
  if (format == ImportFormat.jefit) return _parseJefit(csv, isLb);
  if (format.isWeights) {
    return ImportResult(format, const [], weights: parseWeights(csv, isLb: isLb));
  }
  final fmt = _formats[format];
  if (fmt == null) return ImportResult(format, const []);

  final rows = _rows(csv, _delimiter(csv));
  if (rows.length < 2) return ImportResult(format, const []);

  final index = <String, int>{};
  for (var i = 0; i < rows.first.length; i++) {
    index[_norm(rows.first[i])] = i;
  }
  final cols = index.keys.toList();

  String cell(List<String> row, List<String>? names) {
    final name = _pick(cols, names ?? const []);
    final i = name == null ? null : index[name];
    return (i == null || i >= row.length) ? '' : row[i].trim();
  }

  final kgCol = _pick(cols, fmt.weightKg);
  final lbCol = _pick(cols, fmt.weightLb);
  final plainCol = _pick(cols, fmt.weightPlain ?? const []);

  final sessions = <String, ParsedSession>{};
  final exercisesOf = <String, Map<String, ParsedExercise>>{};

  double num(String v) => double.tryParse(v.replaceAll(',', '.')) ?? 0;
  final clockCol = format == ImportFormat.fitnotes ? _pick(cols, fmt.setClock) : null;

  for (final row in rows.skip(1)) {
    final reps = int.tryParse(cell(row, fmt.reps)) ?? num(cell(row, fmt.reps)).round();
    var sec = num(cell(row, fmt.setSec)).round();
    if (sec <= 0 && clockCol != null) sec = _parseDuration(cell(row, [clockCol]));
    var km = num(cell(row, fmt.km));
    if (km <= 0) km = num(cell(row, fmt.miles)) * 1.609344;
    if (km <= 0) km = num(cell(row, fmt.meters)) / 1000;
    if (reps <= 0 && sec <= 0 && km <= 0) continue;
    if (_norm(cell(row, fmt.setOrder)).startsWith('rest')) continue;
    if (_norm(cell(row, fmt.setType)).startsWith('warmup') ||
        _norm(cell(row, fmt.setType)).startsWith('warm_up') ||
        _norm(cell(row, fmt.warmupFlag)) == 'true' ||
        _norm(cell(row, fmt.warmupFlag)) == '1') {
      continue;
    }

    final date = _parseDate(cell(row, fmt.date));
    if (date == null) continue;
    final name = cell(row, fmt.exercise);
    if (name.isEmpty) continue;

    final kg = _weightKg(
      kg: kgCol == null ? '' : cell(row, [kgCol]),
      lb: lbCol == null ? '' : cell(row, [lbCol]),
      plain: plainCol == null ? '' : cell(row, [plainCol]),
      plainIsLb: fmt.unit == null ? isLb : _norm(cell(row, fmt.unit)).startsWith('lb'),
    );

    final group = cell(row, fmt.group);
    final key = group.isNotEmpty ? '${_dayId(date)}|$group' : _dayId(date);

    final session = sessions.putIfAbsent(key, () {
      final end = _parseDate(cell(row, fmt.endDate));
      final span = end == null ? 0 : end.difference(date).inSeconds;
      if (span > 0) return ParsedSession(date, span);
      final secs = int.tryParse(cell(row, fmt.durationSec)) ?? 0;
      return ParsedSession(date, secs > 0 ? secs : _parseDuration(cell(row, fmt.durationText)));
    });
    final exercises = exercisesOf.putIfAbsent(key, () => {});
    final exercise = exercises.putIfAbsent(name, () {
      final muscle = cell(row, fmt.muscle);
      final parsed = ParsedExercise(name, muscle.isEmpty ? null : muscle);
      session.exercises.add(parsed);
      return parsed;
    });
    exercise.sets.add(
        ParsedSet(math.max(0, reps), kg,
            rpe: _effort(cell(row, fmt.rpe), cell(row, fmt.rir), cell(row, fmt.effort)),
            note: _setNote(cell(row, fmt.note)),
            sec: sec > 0 ? sec : null,
            km: km > 0 ? double.parse(km.toStringAsFixed(3)) : null));
  }

  return ImportResult(format, sessions.values.toList());
}

double? _effort(String rpe, String rir, String either) {
  double? read(String v) => double.tryParse(v.replaceAll(',', '.'));
  final r = read(rpe);
  if (r != null && r >= 1 && r <= 10) return r;
  final left = read(rir);
  if (left != null && left >= 0 && left <= 9) return 10 - left;
  final mixed = read(either);
  if (mixed == null || mixed < 0 || mixed > 10) return null;
  return mixed >= 6 ? mixed : 10 - mixed;
}

Map<String, dynamic>? _backupOf(String text) {
  final head = text.trimLeft();
  if (!head.startsWith('{')) return null;
  Object? decoded;
  try {
    decoded = jsonDecode(head);
  } catch (_) {
    return null;
  }
  if (decoded is! Map) return null;
  final map = decoded.cast<String, dynamic>();
  return map['workouts'] is List && map['routines'] is List ? map : null;
}

ImportResult _parseOpenGym(Map<String, dynamic> backup) {
  final isLb = _norm((backup['unit'] as String?) ?? 'kg').startsWith('lb');
  final custom = <String, String>{};
  for (final entry in (backup['customEx'] as List?) ?? const []) {
    if (entry is! Map) continue;
    final id = entry['id'];
    final name = entry['n'];
    if (id is String && name is String && name.trim().isNotEmpty) custom[id] = name.trim();
  }

  final sessions = <ParsedSession>[];
  for (final raw in (backup['workouts'] as List?) ?? const []) {
    if (raw is! Map) continue;
    final workout = raw.cast<String, dynamic>();
    final date = _openGymDate(workout);
    if (date == null) continue;
    final session = ParsedSession(date, _openGymDuration(workout));
    for (final rawEntry in (workout['entries'] as List?) ?? const []) {
      if (rawEntry is! Map) continue;
      final sourceId = rawEntry['id'];
      if (sourceId is! String) continue;
      final localId = kOpenGymIds[sourceId];
      final name = custom[sourceId] ?? '';
      if (localId == null && name.isEmpty) continue;
      final exercise = ParsedExercise(name, null, id: localId);
      for (final rawSet in (rawEntry['sets'] as List?) ?? const []) {
        if (rawSet is! Map) continue;
        if (rawSet['done'] != true) continue;
        if (rawSet['phase'] == 'warmup' || rawSet['warmup'] == true) continue;
        final reps = (rawSet['r'] as num?)?.toInt() ?? 0;
        if (reps <= 0) continue;
        final weight = (rawSet['w'] as num?)?.toDouble() ?? 0;
        exercise.sets.add(ParsedSet(reps, isLb ? weight / _lbPerKg : weight));
      }
      if (exercise.sets.isNotEmpty) session.exercises.add(exercise);
    }
    if (session.exercises.isNotEmpty) sessions.add(session);
  }

  final weights = <ParsedWeight>[];
  for (final raw in (backup['bodyweight'] as List?) ?? const []) {
    if (raw is! Map) continue;
    final date = _parseDate((raw['d'] as String?) ?? '');
    final value = (raw['w'] as num?)?.toDouble() ?? 0;
    if (date == null || value <= 0) continue;
    weights.add(ParsedWeight(date, isLb ? value / _lbPerKg : value));
  }

  return ImportResult(ImportFormat.openGym, sessions, weights: weights);
}

DateTime? _openGymDate(Map<String, dynamic> workout) {
  final start = (workout['start'] as num?)?.toInt();
  final day = _parseDate((workout['d'] as String?) ?? '');
  if (start != null && start > 0) {
    final stamp = DateTime.fromMillisecondsSinceEpoch(start);
    if (day == null || _dayId(stamp) == _dayId(day)) return stamp;
  }
  return day;
}

int _openGymDuration(Map<String, dynamic> workout) {
  final start = (workout['start'] as num?)?.toInt() ?? 0;
  final end = (workout['end'] as num?)?.toInt() ?? 0;
  if (start <= 0 || end <= start) return 0;
  final seconds = (end - start) ~/ 1000;
  return seconds > 24 * 3600 ? 0 : seconds;
}

double _weightKg({
  required String kg,
  required String lb,
  required String plain,
  required bool plainIsLb,
}) {
  final inKg = _number(kg);
  if (inKg != null) return inKg;
  final inLb = _number(lb);
  if (inLb != null) return inLb / _lbPerKg;
  final raw = _number(plain) ?? 0;
  return plainIsLb ? raw / _lbPerKg : raw;
}

double? _number(String raw) => raw.isEmpty ? null : double.tryParse(raw.replaceAll(',', '.'));

String? _pick(List<String> cols, List<String> candidates) {
  for (final c in candidates) {
    if (cols.contains(c)) return c;
  }
  return null;
}

String _norm(String s) => s.trim().toLowerCase();

String _dayId(DateTime d) => '${d.year}-${d.month}-${d.day}';

List<String> _header(String csv) {
  final line = _firstLine(csv);
  if (line == null) return const [];
  return _splitLine(line, _delimiter(csv)).map(_norm).toList();
}

String _setNote(String raw) {
  final clean = raw.trim().replaceAll(RegExp(r'\s+'), ' ');
  return clean.length > 280 ? clean.substring(0, 280) : clean;
}

String _delimiter(String csv) => (_firstLine(csv) ?? '').contains(';') ? ';' : ',';

int _parseDuration(String s) {
  if (s.isEmpty) return 0;
  final clock = RegExp(r'^(\d+):(\d{2})(?::(\d{2}))?$').firstMatch(s.trim());
  if (clock != null) {
    final a = int.parse(clock.group(1)!), b = int.parse(clock.group(2)!);
    final c = clock.group(3);
    return c == null ? a * 60 + b : a * 3600 + b * 60 + int.parse(c);
  }
  var seconds = 0;
  final h = RegExp(r'(\d+)\s*h').firstMatch(s);
  final m = RegExp(r'(\d+)\s*m').firstMatch(s);
  if (h != null) seconds += int.parse(h.group(1)!) * 3600;
  if (m != null) seconds += int.parse(m.group(1)!) * 60;
  return seconds;
}

const _months = {
  'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
  'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
};

DateTime? _parseDate(String s) {
  if (s.isEmpty) return null;
  final iso = DateTime.tryParse(s.replaceFirst(' ', 'T'));
  if (iso != null) return iso;
  final m = RegExp(r'^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?')
      .firstMatch(s.trim());
  if (m == null) return null;
  final month = _months[m.group(2)!.toLowerCase()];
  if (month == null) return null;
  return DateTime(
    int.parse(m.group(3)!),
    month,
    int.parse(m.group(1)!),
    int.tryParse(m.group(4) ?? '') ?? 0,
    int.tryParse(m.group(5) ?? '') ?? 0,
  );
}

String? _firstLine(String csv) {
  for (final line in csv.split('\n')) {
    if (line.trim().isNotEmpty) return line;
  }
  return null;
}

List<String> _splitLine(String line, String delim) {
  final out = <String>[];
  final field = StringBuffer();
  var quoted = false;
  for (var i = 0; i < line.length; i++) {
    final c = line[i];
    if (quoted) {
      if (c == '"') {
        if (i + 1 < line.length && line[i + 1] == '"') {
          field.write('"');
          i++;
        } else {
          quoted = false;
        }
      } else {
        field.write(c);
      }
    } else if (c == '"') {
      quoted = true;
    } else if (c == delim) {
      out.add(field.toString());
      field.clear();
    } else {
      field.write(c);
    }
  }
  out.add(field.toString());
  return out;
}

List<List<String>> _rows(String text, String delim) {
  final rows = <List<String>>[];
  var row = <String>[];
  final field = StringBuffer();
  var quoted = false;
  var i = 0;
  final n = text.length;

  void endField() {
    row.add(field.toString());
    field.clear();
  }

  void endRow() {
    endField();
    if (row.length > 1 || row.first.trim().isNotEmpty) rows.add(row);
    row = <String>[];
  }

  while (i < n) {
    final c = text[i];
    if (quoted) {
      if (c == '"') {
        if (i + 1 < n && text[i + 1] == '"') {
          field.write('"');
          i += 2;
          continue;
        }
        quoted = false;
        i++;
        continue;
      }
      field.write(c);
      i++;
      continue;
    }
    if (c == '"') {
      quoted = true;
      i++;
      continue;
    }
    if (c == delim) {
      endField();
      i++;
      continue;
    }
    if (c == '\n' || c == '\r') {
      if (c == '\r' && i + 1 < n && text[i + 1] == '\n') i++;
      endRow();
      i++;
      continue;
    }
    field.write(c);
    i++;
  }
  if (field.isNotEmpty || row.isNotEmpty) endRow();
  return rows;
}