import 'package:duration/duration.dart';

String formatQuoteDuration(Duration duration) {
  final clampedDuration = duration.isNegative ? Duration.zero : duration;
  final pretty = prettyDuration(
    clampedDuration,
    tersity: DurationTersity.second,
    upperTersity: DurationTersity.hour,
    abbreviated: true,
    delimiter: ':',
    spacer: '',
  );
  final units = _extractHms(pretty);
  final hours = units['h'] ?? 0;
  final minutes = units['m'] ?? 0;
  final seconds = units['s'] ?? 0;

  if (hours > 0) {
    return '${hours.toString()}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
  return '${minutes.toString()}:${seconds.toString().padLeft(2, '0')}';
}

Map<String, int> _extractHms(String pretty) {
  final matches = RegExp(r'(\d+)([hms])').allMatches(pretty);
  final units = <String, int>{};
  for (final match in matches) {
    units[match.group(2)!] = int.parse(match.group(1)!);
  }
  return units;
}
