Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart
254 KB
Raw Blame
part of 'api_service.dart';

class _BoHttpError implements Exception {
  final int status;
  final String message;
  final String body;
  _BoHttpError(this.status, this.message, [String? body]) : body = body ?? message;
  @override
  String toString() => 'BookOrbit HTTP $status: $message';

  /// The reason in BookOrbit's error body, fit to show to the user.
  String? get serverMessage {
    try {
      final decoded = jsonDecode(body);
      if (decoded is! Map) return null;
      final m = decoded['message'];
      if (m is String && m.trim().isNotEmpty) return m.trim();
      if (m is List && m.isNotEmpty) return m.join('\n');
    } catch (_) {}
    return null;
  }

  /// The machine-readable reason some refusals carry ("KINDLE_ORIGINAL_UNAVAILABLE").
  String? get serverCode {
    try {
      final decoded = jsonDecode(body);
      if (decoded is Map && decoded['code'] is String) return decoded['code'] as String;
      if (decoded is Map && decoded['errorCode'] is String) return decoded['errorCode'] as String;
    } catch (_) {}
    return null;
  }
}

class _BoListenSession {
  final String bookId;
  final String sessionUuid;
  final DateTime startedAt;
  int? fileId;
  double listenedSeconds = 0;
  double? startPercent;
  double? lastPercent;
  bool deviceRemembered = false;

  _BoListenSession(this.bookId, this.sessionUuid, this.startedAt);
}

class _BoTicket {
  final String token;
  final DateTime expiresAt;
  final Set<String> fileIds;
  _BoTicket(this.token, this.expiresAt, this.fileIds);
}

/// ApiService for a BookOrbit server.
///
/// The rest of the app speaks Audiobookshelf, so this keeps every public
/// method and answers the Audiobookshelf routes they call from BookOrbit
/// instead: the authenticated request helpers are overridden and each
/// `/api/...` request is routed to a handler that calls `/api/v1/...` on the
/// BookOrbit server and returns an Audiobookshelf-shaped response. Routes
/// with no BookOrbit counterpart answer 404, which the callers already treat
/// as "not supported here".
class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {
  BookOrbitApiService({
    required super.baseUrl,
    required super.token,
    super.refreshToken,
    super.isLegacyToken,
    super.customHeaders,
    super.onTokensRefreshed,
    super.loadPersistedTokens,
    super.onAuthExpired,
    super.httpClient,
  }) {
    if (token.isNotEmpty && baseUrl.isNotEmpty) {
      BookOrbitMediaProxy.instance.attach(this);
      unawaited(BookOrbitMediaProxy.instance.ensureRunning());
    }
  }

  @override
  ServerBackend get backend => ServerBackend.bookorbit;

  String get _basePath => Uri.parse(_cleanBaseUrl).path;
  String get _v1 => '$_cleanBaseUrl/api/v1';

  static String? _platformSource() {
    if (kIsWeb) return null;
    return switch (defaultTargetPlatform) {
      TargetPlatform.android => 'android',
      TargetPlatform.iOS => 'ios',
      _ => null,
    };
  }

  static final math.Random _rng = math.Random.secure();

  static String _uuid() {
    final b = List<int>.generate(16, (_) => _rng.nextInt(256));
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    final h = b.map((x) => x.toRadixString(16).padLeft(2, '0')).join();
    return '${h.substring(0, 8)}-${h.substring(8, 12)}-${h.substring(12, 16)}-'
        '${h.substring(16, 20)}-${h.substring(20)}';
  }

  /// ISO-8601 in UTC to the millisecond, the precision the server keeps.
  static String _iso(DateTime t) {
    final u = t.toUtc();
    return DateTime.utc(u.year, u.month, u.day, u.hour, u.minute, u.second, u.millisecond)
        .toIso8601String();
  }

  static final Map<String, Map<String, dynamic>> _manifests = {};
  static final Map<String, DateTime> _manifestAt = {};
  static final Map<String, Map<String, dynamic>> _details = {};
  static final Map<String, DateTime> _detailAt = {};
  static final Map<String, int> _revisions = {};
  static final Map<String, _BoListenSession> _sessions = {};
  static final Map<String, String> _coverVersions = {};
  static final Map<String, String> _bookLibrary = {};
  static final Map<String, _BoTicket> _tickets = {};
  static final Map<String, String> _assetByFile = {};
  // Each asset's manifest etag, which changes with the file's size or time.
  // It goes on the stream URL so the player's cache, keyed by URL, starts
  // over when a file is replaced instead of asking for the old file's bytes.
  static final Map<String, String> _assetVersion = {};
  static final Map<String, String> _serverVersions = {};
  // What each server says it can do, from /app-info `features`.
  static final Map<String, Set<String>> _serverFeatures = {};
  static List<Map<String, dynamic>>? _librariesCache;
  static DateTime? _librariesAt;
  static final Map<String, ({DateTime at, Future<Object?> value})> _recent = {};

  /// One answer per [key] for [ttl], shared by concurrent callers. Failures
  /// are not kept.
  Future<T> _cached<T>(String key, Duration ttl, Future<T> Function() load) {
    final k = _key(key);
    final hit = _recent[k];
    if (hit != null && DateTime.now().difference(hit.at) < ttl) return hit.value.then((v) => v as T);
    final future = load();
    _recent[k] = (at: DateTime.now(), value: future);
    future.then<void>((_) {}, onError: (Object _) {
      if (identical(_recent[k]?.value, future)) _recent.remove(k);
    });
    return future;
  }

  static const _manifestTtl = Duration(minutes: 10);
  static const _detailTtl = Duration(minutes: 2);

  /// Keyed by book alone so the local and remote address of one server share
  /// them (cover URLs stay the same and image caches keep hitting). They are
  /// cleared whenever the signed-in account changes.
  String _key(String id) => id;

  /// Forget everything cached for the signed-in account.
  static void clearCaches() {
    _ebookReadCards.clear();
    _manifests.clear();
    _manifestAt.clear();
    _details.clear();
    _detailAt.clear();
    _revisions.clear();
    _sessions.clear();
    _coverVersions.clear();
    _bookLibrary.clear();
    _tickets.clear();
    _assetByFile.clear();
    _assetVersion.clear();
    _librariesCache = null;
    _librariesAt = null;
    _recent.clear();
    _serverVersions.clear();
    _serverFeatures.clear();
    _narrations.clear();
    _narrationLoads.clear();
    _readAlongTimings.clear();
    _placedSpots.clear();
  }

  /// Names Absorb on the highlights and sessions it saves, on servers that
  /// show it. Older ones refuse a field they don't know.
  Future<Map<String, String>> _clientName() async =>
      (await _features()).contains('client-name') ? const {'clientName': 'Absorb'} : const {};

  Future<Set<String>> _features() async {
    final origin = ApiService._originOf(_cleanBaseUrl) ?? _cleanBaseUrl;
    if (!_serverFeatures.containsKey(origin)) {
      _serverVersions.remove(origin);
      await _fetchVersion(_cleanBaseUrl, _accessToken, customHeaders, client: _httpClient);
    }
    return _serverFeatures[origin] ?? const {};
  }

  @override
  String get upstreamBaseUrl => _cleanBaseUrl;

  @override
  Map<String, String> get upstreamCustomHeaders => customHeaders;

  @override
  Future<String?> currentAccessToken() async {
    await _ensureFreshAccessToken();
    return _accessToken.isEmpty ? null : _accessToken;
  }

  @override
  Future<String?> tokenAfterRejection() async {
    final outcome = await _refreshAccessToken();
    if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
    return outcome == _RefreshOutcome.refreshed ? _accessToken : null;
  }

  @override
  Future<void> ensureMediaReady() async {
    BookOrbitMediaProxy.instance.attach(this);
    await BookOrbitMediaProxy.instance.ensureRunning();
    if (!_watchingCoverShape) {
      _watchingCoverShape = true;
      PlayerSettings.settingsChanged.addListener(() => unawaited(loadCoverShape()));
    }
    await loadCoverShape();
  }

  /// The cover shape picked in settings, globally and per library. With
  /// rectangle covers a book shows BookOrbit's portrait book cover, falling
  /// back to the square one when it has none. Kept here because cover URLs
  /// are built synchronously during layout.
  static bool _rectCovers = false;
  static final Map<String, bool> _rectCoversByLibrary = {};
  static bool _watchingCoverShape = false;

  static Future<void> loadCoverShape() async {
    final global = await PlayerSettings.getRectangleCovers();
    final byLibrary = <String, bool>{};
    for (final lib in _librariesCache ?? const <Map<String, dynamic>>[]) {
      final id = '${lib['id']}';
      final v = await PlayerSettings.getRectangleCoversOverride(id);
      if (v != null) byLibrary[id] = v == 'rect';
    }
    final changed = global != _rectCovers ||
        byLibrary.length != _rectCoversByLibrary.length ||
        byLibrary.entries.any((e) => _rectCoversByLibrary[e.key] != e.value);
    if (!changed) return;
    _rectCovers = global;
    _rectCoversByLibrary
      ..clear()
      ..addAll(byLibrary);
    // Screens rebuilt on the settings change before this finished; once
    // more so they pick up the other cover.
    PlayerSettings.notifySettingsChanged();
  }

  String _listCoverSlot(String itemId) {
    final lib = _bookLibrary[_key(itemId)];
    final rect = (lib == null ? null : _rectCoversByLibrary[lib]) ?? _rectCovers;
    return rect ? 'ebook' : 'audio';
  }

  /// A magic-link sign-in is a browser-style session: its refresh token only
  /// travels as the `refresh_token` cookie. Stored with this prefix so the
  /// refresh and sign-out calls know to send it that way.
  static const _webRefreshPrefix = 'web:';

  static String? _refreshCookie(http.Response r) {
    final raw = r.headers['set-cookie'];
    if (raw == null) return null;
    return RegExp(r'refresh_token=([^;,\s]+)').firstMatch(raw)?.group(1);
  }

  Map<String, String> _refreshHeaders(String refreshToken) => {
        ...customHeaders,
        'Content-Type': 'application/json',
        if (!kIsWeb) 'User-Agent': ApiService.userAgent,
        if (refreshToken.startsWith(_webRefreshPrefix))
          'Cookie': 'refresh_token=${refreshToken.substring(_webRefreshPrefix.length)}',
      };

  String _refreshBody(String refreshToken) => refreshToken.startsWith(_webRefreshPrefix)
      ? '{}'
      : jsonEncode({'refreshToken': refreshToken});

  @override
  Future<http.Response> _sendRefresh(String refreshToken) async {
    final r = await _post(
      Uri.parse('$_v1/auth/refresh'),
      headers: _refreshHeaders(refreshToken),
      body: _refreshBody(refreshToken),
    );
    if (r.statusCode != 200 || !refreshToken.startsWith(_webRefreshPrefix)) return r;
    final data = jsonDecode(r.body) as Map<String, dynamic>;
    final next = _refreshCookie(r);
    if (next != null) data['refreshToken'] = '$_webRefreshPrefix$next';
    return http.Response.bytes(
      utf8.encode(jsonEncode(data)),
      200,
      headers: {'content-type': 'application/json; charset=utf-8'},
    );
  }

  static String _deviceLabel() {
    final model = [ApiService.deviceManufacturer, ApiService.deviceModel]
        .where((s) => s.isNotEmpty)
        .join(' ');
    final label = model.isEmpty ? 'Absorb' : 'Absorb on $model';
    return label.length > 100 ? label.substring(0, 100) : label;
  }

  static String _v1Of(String serverUrl) => '${normalizeServerUrl(serverUrl)}/api/v1';

  /// A BookOrbit server answers its public login options with a JSON object
  /// carrying `passwordLoginEnabled`; nothing else does. Which sign-in
  /// methods are on doesn't matter here: a server with passwords off still
  /// takes magic links, and this also answers the app's reachability pings.
  static Future<({bool ok, String? detail})> probe(
    String serverUrl, {
    Map<String, String> customHeaders = const {},
    Duration timeout = const Duration(seconds: 10),
  }) async {
    try {
      final r = await http
          .get(Uri.parse('${_v1Of(serverUrl)}/auth/login-options'),
              headers: customHeaders.isNotEmpty ? customHeaders : null)
          .timeout(timeout);
      if (r.statusCode != 200) {
        return (ok: false, detail: 'Server returned HTTP ${r.statusCode} for the BookOrbit login options.');
      }
      final data = jsonDecode(r.body);
      if (data is Map && data.containsKey('passwordLoginEnabled')) {
        return (ok: true, detail: null);
      }
      return (ok: false, detail: 'The server answered, but it does not look like BookOrbit.');
    } on FormatException {
      return (ok: false, detail: 'The server answered, but it does not look like BookOrbit.');
    } catch (e) {
      return (ok: false, detail: ApiService._describePingError(e));
    }
  }

  /// Sign in and answer in the shape of an Audiobookshelf /login response.
  static Future<(Map<String, dynamic>?, int)> signIn({
    required String serverUrl,
    required String username,
    required String password,
    Map<String, String> customHeaders = const {},
  }) async {
    try {
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/login'),
            headers: {
              ...customHeaders,
              'Content-Type': 'application/json',
              if (!kIsWeb) 'User-Agent': ApiService.userAgent,
            },
            body: jsonEncode({
              'username': username,
              'password': password,
              'clientKind': 'native',
              'deviceLabel': _deviceLabel(),
            }),
          )
          .timeout(const Duration(seconds: 20));
      if (r.statusCode != 200 && r.statusCode != 201) {
        debugPrint('[BookOrbit] login failed: ${r.statusCode} ${r.body}');
        if (r.statusCode == 403 && r.body.contains('password_auth_disabled')) {
          return (<String, dynamic>{'bookOrbitPasswordOff': true}, 403);
        }
        return (null, r.statusCode);
      }
      final data = jsonDecode(r.body) as Map<String, dynamic>;
      final rawUser = data['user'] as Map<String, dynamic>? ?? const {};
      if (rawUser['isDefaultPassword'] == true) {
        return (<String, dynamic>{'bookOrbitDefaultPassword': true}, 403);
      }
      return (await _loginShape(serverUrl, data, customHeaders, data['refreshToken'] as String?), 200);
    } catch (e) {
      debugPrint('[BookOrbit] login error: $e');
      return (null, 0);
    }
  }

  /// A BookOrbit sign-in answer as an Audiobookshelf /login response, with
  /// the tokens inside `user` the way current Audiobookshelf servers put them.
  static Future<Map<String, dynamic>> _loginShape(
    String serverUrl,
    Map<String, dynamic> data,
    Map<String, String> customHeaders,
    String? refreshToken,
  ) async {
    final rawUser = data['user'] as Map<String, dynamic>? ?? const {};
    final access = data['accessToken'] as String?;
    final version = access == null ? null : await _fetchVersion(serverUrl, access, customHeaders);
    final user = BookOrbitMapper.user(rawUser)
      ..['accessToken'] = access
      ..['refreshToken'] = refreshToken;
    return {
      'user': user,
      'userDefaultLibraryId': null,
      'serverSettings': {'version': version ?? ''},
      'ereaderDevices': const [],
      'Source': 'bookorbit',
    };
  }

  /// What a BookOrbit server offers before anyone signs in: whether
  /// passwords work and which single sign-on providers it has. Null when the
  /// server can't be read or isn't BookOrbit.
  static Future<({bool passwordLogin, List<Map<String, dynamic>> oidcProviders})?> loginOptions(
    String serverUrl, {
    Map<String, String> customHeaders = const {},
  }) async {
    try {
      final r = await http
          .get(Uri.parse('${_v1Of(serverUrl)}/auth/login-options'),
              headers: customHeaders.isNotEmpty ? customHeaders : null)
          .timeout(const Duration(seconds: 10));
      if (r.statusCode != 200) return null;
      final data = jsonDecode(r.body);
      if (data is! Map || !data.containsKey('passwordLoginEnabled')) return null;
      return (
        passwordLogin: data['passwordLoginEnabled'] != false,
        oidcProviders: (data['oidcProviders'] as List<dynamic>? ?? const [])
            .whereType<Map<String, dynamic>>()
            .where((p) => p['enabled'] != false && p['slug'] is String && p['clientId'] is String)
            .toList(),
      );
    } catch (e) {
      debugPrint('[BookOrbit] login options failed: $e');
      return null;
    }
  }

  static Map<String, String> _publicHeaders(Map<String, String> customHeaders) => {
        ...customHeaders,
        'Content-Type': 'application/json',
        if (!kIsWeb) 'User-Agent': ApiService.userAgent,
      };

  static String _errorText(http.Response r) {
    try {
      final m = (jsonDecode(r.body) as Map)['message'];
      if (m != null) return '$m';
    } catch (_) {}
    return r.body.length > 200 ? r.body.substring(0, 200) : r.body;
  }

  /// The one-time state for an OIDC sign-in and the identity provider's
  /// sign-in page. The app sends the user there itself.
  static Future<({String state, String authorizationEndpoint})> oidcState(
    String serverUrl,
    String slug, {
    Map<String, String> customHeaders = const {},
  }) async {
    final r = await http
        .post(
          Uri.parse('${_v1Of(serverUrl)}/auth/oidc/${Uri.encodeComponent(slug)}/state'),
          headers: _publicHeaders(customHeaders),
          body: '{}',
        )
        .timeout(const Duration(seconds: 20));
    if (r.statusCode != 200 && r.statusCode != 201) {
      throw Exception('BookOrbit returned HTTP ${r.statusCode}: ${_errorText(r)}');
    }
    final data = jsonDecode(r.body) as Map<String, dynamic>;
    return (state: data['state'] as String, authorizationEndpoint: data['authorizationEndpoint'] as String);
  }

  /// Trade the identity provider's code for BookOrbit tokens and answer like
  /// [signIn], with the server's reason when it says no.
  static Future<(Map<String, dynamic>?, int, String?)> signInWithOidc({
    required String serverUrl,
    required String code,
    required String codeVerifier,
    required String redirectUri,
    required String nonce,
    required String state,
    Map<String, String> customHeaders = const {},
  }) async {
    try {
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/oidc/callback'),
            headers: _publicHeaders(customHeaders),
            body: jsonEncode({
              'code': code,
              'codeVerifier': codeVerifier,
              'redirectUri': redirectUri,
              'nonce': nonce,
              'state': state,
              'clientKind': 'native',
              'deviceLabel': _deviceLabel(),
            }),
          )
          .timeout(const Duration(seconds: 30));
      if (r.statusCode != 200 && r.statusCode != 201) {
        debugPrint('[BookOrbit] OIDC callback failed: ${r.statusCode} ${r.body}');
        return (null, r.statusCode, _errorText(r));
      }
      final data = jsonDecode(r.body) as Map<String, dynamic>;
      if (data['accessToken'] is! String) return (null, r.statusCode, 'No sign-in tokens in the reply');
      final cookie = _refreshCookie(r);
      final refresh = data['refreshToken'] as String? ?? (cookie == null ? null : '$_webRefreshPrefix$cookie');
      return (await _loginShape(serverUrl, data, customHeaders, refresh), 200, null);
    } catch (e) {
      debugPrint('[BookOrbit] OIDC callback error: $e');
      return (null, 0, '$e');
    }
  }

  /// The server and token in a BookOrbit password link
  /// (`https://host[/base]/reset-password?token=...`), or null when [input]
  /// isn't one.
  static ({Uri server, String token})? passwordLink(String input) {
    final uri = Uri.tryParse(input.trim());
    final token = uri?.queryParameters['token'] ?? '';
    if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https') || uri.host.isEmpty || token.isEmpty) {
      return null;
    }
    var path = uri.path;
    if (path.endsWith('/')) path = path.substring(0, path.length - 1);
    if (!path.endsWith('/reset-password')) return null;
    return (
      server: Uri(
        scheme: uri.scheme,
        host: uri.host,
        port: uri.hasPort ? uri.port : null,
        path: path.substring(0, path.length - '/reset-password'.length),
      ),
      token: token,
    );
  }

  /// BookOrbit's password rules: at least 8 characters, with a lowercase
  /// letter, an uppercase letter and a digit.
  static bool passwordAcceptable(String password) =>
      password.length >= 8 &&
      RegExp('[a-z]').hasMatch(password) &&
      RegExp('[A-Z]').hasMatch(password) &&
      RegExp(r'\d').hasMatch(password);

  /// Asks the server to email a password link. It answers the same whether or
  /// not the address has an account, so [BoPasswordResetResult.sent] only says
  /// the request was taken.
  static Future<BoPasswordResetResult> requestPasswordReset({
    required String serverUrl,
    required String email,
    Map<String, String> customHeaders = const {},
  }) async {
    try {
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/forgot-password'),
            headers: {
              ...customHeaders,
              'Content-Type': 'application/json',
              if (!kIsWeb) 'User-Agent': ApiService.userAgent,
            },
            body: jsonEncode({'email': email.trim()}),
          )
          .timeout(const Duration(seconds: 20));
      if (r.statusCode >= 200 && r.statusCode < 300) return BoPasswordResetResult.sent;
      if (r.statusCode == 503) return BoPasswordResetResult.notSetUp;
      if (r.statusCode == 429) return BoPasswordResetResult.tooManyTries;
      debugPrint('[BookOrbit] password reset request returned ${r.statusCode}');
      return BoPasswordResetResult.failed;
    } catch (e) {
      debugPrint('[BookOrbit] password reset request failed: $e');
      return BoPasswordResetResult.failed;
    }
  }

  /// Sets a password from a password link. [message] is BookOrbit's reason
  /// when it refused.
  static Future<({bool ok, int status, String? message})> setPasswordFromLink({
    required String serverUrl,
    required String token,
    required String newPassword,
    Map<String, String> customHeaders = const {},
  }) async {
    try {
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/reset-password'),
            headers: {
              ...customHeaders,
              'Content-Type': 'application/json',
              if (!kIsWeb) 'User-Agent': ApiService.userAgent,
            },
            body: jsonEncode({'token': token, 'newPassword': newPassword}),
          )
          .timeout(const Duration(seconds: 20));
      if (r.statusCode >= 200 && r.statusCode < 300) return (ok: true, status: r.statusCode, message: null);
      return (ok: false, status: r.statusCode, message: _BoHttpError(r.statusCode, r.body).serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] setting a password from a link failed: $e');
      return (ok: false, status: 0, message: null);
    }
  }

  /// Replaces an account's starting password: BookOrbit lets such an account
  /// sign in only to change it. [message] is BookOrbit's reason when it
  /// refused.
  static Future<({bool ok, int status, String? message})> replaceStartingPassword({
    required String serverUrl,
    required String username,
    required String currentPassword,
    required String newPassword,
    Map<String, String> customHeaders = const {},
  }) async {
    final headers = {
      ...customHeaders,
      'Content-Type': 'application/json',
      if (!kIsWeb) 'User-Agent': ApiService.userAgent,
    };
    try {
      final login = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/login'),
            headers: headers,
            body: jsonEncode({
              'username': username,
              'password': currentPassword,
              'clientKind': 'native',
              'deviceLabel': _deviceLabel(),
            }),
          )
          .timeout(const Duration(seconds: 20));
      if (login.statusCode != 200 && login.statusCode != 201) {
        return (ok: false, status: login.statusCode, message: _BoHttpError(login.statusCode, login.body).serverMessage);
      }
      final access = (jsonDecode(login.body) as Map<String, dynamic>)['accessToken'] as String?;
      if (access == null) return (ok: false, status: 0, message: null);
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/change-password'),
            headers: {...headers, 'Authorization': 'Bearer $access'},
            body: jsonEncode({'currentPassword': currentPassword, 'newPassword': newPassword}),
          )
          .timeout(const Duration(seconds: 20));
      if (r.statusCode >= 200 && r.statusCode < 300) return (ok: true, status: r.statusCode, message: null);
      return (ok: false, status: r.statusCode, message: _BoHttpError(r.statusCode, r.body).serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] replacing a starting password failed: $e');
      return (ok: false, status: 0, message: null);
    }
  }

  @override
  Future<PasswordChangeResult> changeMyPassword({
    required String currentPassword,
    required String newPassword,
  }) async {
    String username;
    try {
      username = '${(await _boGet('/auth/me') as Map<String, dynamic>)['username'] ?? ''}';
      await _boPost('/auth/change-password', {'currentPassword': currentPassword, 'newPassword': newPassword});
    } on _BoHttpError catch (e) {
      if (e.status == 401) return const PasswordChangeResult(PasswordChangeStatus.invalidPassword);
      return PasswordChangeResult(PasswordChangeStatus.failed, message: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] changeMyPassword error: $e');
      return const PasswordChangeResult(PasswordChangeStatus.failed);
    }
    // BookOrbit signs every session out when a password changes, this one
    // too, so sign straight back in with the new one.
    final (result, status) = await signIn(
      serverUrl: _cleanBaseUrl,
      username: username,
      password: newPassword,
      customHeaders: customHeaders,
    );
    final user = result?['user'];
    if (status == 200 && user is Map && user['accessToken'] is String) {
      _accessToken = user['accessToken'] as String;
      _refreshToken = user['refreshToken'] as String?;
      await onTokensRefreshed?.call(_accessToken, _refreshToken);
    } else {
      debugPrint('[BookOrbit] password changed, but signing back in failed: $status');
    }
    return const PasswordChangeResult(PasswordChangeStatus.success);
  }

  /// The token from a BookOrbit magic link (`https://host/magic?token=...`),
  /// or the token itself when that is what was pasted.
  static String? magicLinkToken(String input) {
    final text = input.trim();
    final fromUrl = Uri.tryParse(text)?.queryParameters['token'];
    if (fromUrl != null && fromUrl.isNotEmpty) return fromUrl;
    if (RegExp(r'^[A-Za-z0-9_-]{16,512}$').hasMatch(text)) return text;
    return null;
  }

  /// The server a magic link points at (`https://host[/base]/magic?token=...`),
  /// or null when [input] isn't such a link.
  static Uri? serverFromMagicLink(String input) {
    final uri = Uri.tryParse(input.trim());
    if (uri == null ||
        (uri.scheme != 'http' && uri.scheme != 'https') ||
        uri.host.isEmpty ||
        (uri.queryParameters['token'] ?? '').isEmpty) {
      return null;
    }
    var path = uri.path;
    if (path.endsWith('/')) path = path.substring(0, path.length - 1);
    if (!path.endsWith('/magic')) return null;
    return Uri(
      scheme: uri.scheme,
      host: uri.host,
      port: uri.hasPort ? uri.port : null,
      path: path.substring(0, path.length - '/magic'.length),
    );
  }

  /// Sign in with a magic link and answer like [signIn].
  static Future<(Map<String, dynamic>?, int)> signInWithMagicLink({
    required String serverUrl,
    required String link,
    Map<String, String> customHeaders = const {},
  }) async {
    final token = magicLinkToken(link);
    if (token == null) return (null, 400);
    try {
      final r = await http
          .post(
            Uri.parse('${_v1Of(serverUrl)}/auth/magic-links/login'),
            headers: {
              ...customHeaders,
              'Content-Type': 'application/json',
              if (!kIsWeb) 'User-Agent': ApiService.userAgent,
            },
            body: jsonEncode({'token': token}),
          )
          .timeout(const Duration(seconds: 20));
      if (r.statusCode != 200 && r.statusCode != 201) {
        debugPrint('[BookOrbit] magic link login failed: ${r.statusCode} ${r.body}');
        return (null, r.statusCode);
      }
      final data = jsonDecode(r.body) as Map<String, dynamic>;
      final cookie = _refreshCookie(r);
      return (
        await _loginShape(serverUrl, data, customHeaders, cookie == null ? null : '$_webRefreshPrefix$cookie'),
        200,
      );
    } catch (e) {
      debugPrint('[BookOrbit] magic link login error: $e');
      return (null, 0);
    }
  }

  static Future<String?> _fetchVersion(
    String serverUrl,
    String accessToken,
    Map<String, String> customHeaders, {
    http.Client? client,
  }) async {
    final origin = ApiService._originOf(serverUrl) ?? serverUrl;
    final cached = _serverVersions[origin];
    if (cached != null) return cached;
    try {
      final get = client?.get ?? http.get;
      final r = await get(
        Uri.parse('${_v1Of(serverUrl)}/app-info'),
        headers: {...customHeaders, 'Authorization': 'Bearer $accessToken'},
      ).timeout(const Duration(seconds: 10));
      if (r.statusCode == 200) {
        final info = jsonDecode(r.body) as Map<String, dynamic>;
        _serverFeatures[origin] = {
          for (final f in (info['features'] as List<dynamic>? ?? const [])) '$f',
        };
        final v = info['version'] as String?;
        if (v != null && v.isNotEmpty) {
          final label = 'BookOrbit ${v.startsWith('v') ? v.substring(1) : v}';
          _serverVersions[origin] = label;
          return label;
        }
      }
    } catch (_) {}
    return null;
  }

  @override
  Future<bool> revokeServerSession({bool allDevices = false}) async {
    final refresh = _refreshToken;
    if (refresh == null) return false;
    try {
      final r = await _post(
        Uri.parse('$_v1/auth/logout'),
        headers: _refreshHeaders(refresh),
        body: _refreshBody(refresh),
      ).timeout(const Duration(seconds: 10));
      return r.statusCode >= 200 && r.statusCode < 300;
    } catch (e) {
      debugPrint('[BookOrbit] logout error: $e');
      return false;
    }
  }

  @override
  Future<AuthSessionsResult> getAuthSessions({int page = 0, int itemsPerPage = 20}) async =>
      const AuthSessionsResult(AuthSessionsStatus.unsupported);

  Uri _boUri(String path, [Map<String, dynamic>? query]) {
    final q = <String, dynamic>{};
    query?.forEach((k, v) {
      if (v == null) return;
      q[k] = v is Iterable ? v.map((e) => '$e').toList() : '$v';
    });
    return Uri.parse('$_v1$path').replace(queryParameters: q.isEmpty ? null : q);
  }

  bool _isNative(Uri url) => url.path.startsWith('$_basePath/api/v1/');

  static const _timeout = Duration(seconds: 20);

  dynamic _decode(http.Response r) {
    if (r.statusCode < 200 || r.statusCode >= 300) {
      throw _BoHttpError(r.statusCode, r.body.length > 300 ? r.body.substring(0, 300) : r.body, r.body);
    }
    if (r.body.isEmpty) return null;
    return jsonDecode(r.body);
  }

  Future<dynamic> _boGet(String path, [Map<String, dynamic>? query, Duration timeout = _timeout]) async =>
      _decode(await super._authGet(_boUri(path, query), timeout: timeout));

  Future<dynamic> _boPost(String path, [Object? body, Duration timeout = _timeout]) async =>
      _decode(await super._authPost(
        _boUri(path),
        body: body == null ? null : jsonEncode(body),
        timeout: timeout,
      ));

  /// PUT, and DELETE with a body, which the shared helpers don't cover.
  Future<dynamic> _boSend(String method, String path, Object body) async {
    await _ensureFreshAccessToken();
    final payload = jsonEncode(body);
    Future<http.Response> send() async {
      final req = http.Request(method, _boUri(path))
        ..headers.addAll(_headers)
        ..body = payload;
      final client = _httpClient ?? http.Client();
      try {
        final streamed = await client.send(req).timeout(_timeout);
        return await http.Response.fromStream(streamed).timeout(_timeout);
      } finally {
        if (_httpClient == null) client.close();
      }
    }

    var r = await send();
    if (r.statusCode == 401) {
      final outcome = await _refreshAccessToken();
      if (outcome == _RefreshOutcome.refreshed) r = await send();
      if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
    }
    return _decode(r);
  }

  Future<dynamic> _boPut(String path, Object body) => _boSend('PUT', path, body);

  Future<dynamic> _boPatch(String path, Object body) async => _decode(await super._authPatch(
        _boUri(path),
        body: jsonEncode(body),
        timeout: _timeout,
      ));

  Future<dynamic> _boDelete(String path, {Object? body}) async {
    if (body != null) return _boSend('DELETE', path, body);
    return _decode(await super._authDelete(_boUri(path), timeout: _timeout));
  }

  static Future<List<T>> _pool<T>(List<Future<T> Function()> jobs, {int width = 6}) async {
    final results = List<T?>.filled(jobs.length, null);
    var next = 0;
    Future<void> worker() async {
      while (true) {
        final i = next++;
        if (i >= jobs.length) return;
        results[i] = await jobs[i]();
      }
    }

    await Future.wait(List.generate(math.min(width, jobs.length), (_) => worker()));
    return results.cast<T>();
  }

  @override
  Future<http.Response> _authGet(Uri url,
      {Map<String, String>? headers,
      bool sendRefreshTokenHeader = false,
      Duration timeout = const Duration(seconds: 15)}) {
    if (_isNative(url)) return super._authGet(url, headers: headers, timeout: timeout);
    return _route('GET', url, null);
  }

  @override
  Future<http.Response> _authPost(Uri url,
      {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) {
    if (_isNative(url)) return super._authPost(url, headers: headers, body: body, timeout: timeout);
    return _route('POST', url, body);
  }

  @override
  Future<http.Response> _authPatch(Uri url,
      {Map<String, String>? headers, Object? body, Duration timeout = const Duration(seconds: 15)}) {
    if (_isNative(url)) return super._authPatch(url, headers: headers, body: body, timeout: timeout);
    return _route('PATCH', url, body);
  }

  @override
  Future<http.Response> _authDelete(Uri url,
      {Map<String, String>? headers, Duration timeout = const Duration(seconds: 15)}) {
    if (_isNative(url)) return super._authDelete(url, headers: headers, timeout: timeout);
    return _route('DELETE', url, null);
  }

  static http.Response _json(Object? data, [int status = 200]) => http.Response.bytes(
        utf8.encode(jsonEncode(data)),
        status,
        headers: {'content-type': 'application/json; charset=utf-8'},
      );

  static http.Response _status(int status, [String message = '']) =>
      _json({'error': message}, status);

  Future<http.Response> _route(String method, Uri url, Object? body) async {
    var path = url.path;
    if (_basePath.isNotEmpty && path.startsWith(_basePath)) {
      path = path.substring(_basePath.length);
    }
    final seg = path.split('/').where((s) => s.isNotEmpty).map(Uri.decodeComponent).toList();
    final q = url.queryParameters;
    Map<String, dynamic> json = const {};
    if (body is String && body.isNotEmpty) {
      try {
        final decoded = jsonDecode(body);
        if (decoded is Map<String, dynamic>) json = decoded;
      } catch (_) {}
    }
    try {
      final result = await _dispatch(method, seg, q, json);
      if (result == null) {
        debugPrint('[BookOrbit] No BookOrbit route for $method $path');
        return _status(404, 'Not available on BookOrbit');
      }
      return result;
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] $method $path -> ${e.status} ${e.message}');
      return _status(e.status, e.message);
    } on http.ClientException {
      rethrow;
    } on TimeoutException {
      rethrow;
    } catch (e, st) {
      debugPrint('[BookOrbit] $method $path failed: $e\n$st');
      return _status(500, '$e');
    }
  }

  Future<http.Response?> _dispatch(
    String method,
    List<String> s,
    Map<String, String> q,
    Map<String, dynamic> body,
  ) async {
    if (s.isEmpty || s[0] != 'api') return null;
    final n = s.length;
    String at(int i) => i < n ? s[i] : '';

    switch (at(1)) {
      case 'authorize':
        if (method == 'POST') return _json(await _authorizePayload());
      case 'me':
        return _routeMe(method, s, q, body);
      case 'libraries':
        if (method == 'POST' && n == 4 && at(3) == 'scan') return _json(await _scanLibrary(at(2)));
        if (method != 'GET') return null;
        if (n == 2) {
          final dock = await _dockLibrary();
          return _json({'libraries': [...await _libraries(), if (dock != null) dock]});
        }
        final libId = at(2);
        if (libId == ApiService.bookDockLibraryId) return _routeDockLibrary(n, at(3), q);
        if (n == 3) {
          final lib = (await _libraries()).firstWhere((l) => l['id'] == libId,
              orElse: () => const <String, dynamic>{});
          if (lib.isEmpty) return null;
          final out = Map<String, dynamic>.from(lib);
          if ((q['include'] ?? '').contains('filterdata')) {
            out['filterdata'] = await _filterData(libId);
          }
          return _json(out);
        }
        switch (at(3)) {
          case 'items':
            return _json(await _libraryItems(libId, q));
          case 'personalized':
            return _json(await _cached('personalized:$libId:${q['shelves'] ?? ''}:${q['limit'] ?? ''}',
                const Duration(seconds: 20), () => _personalized(libId, q)));
          case 'series':
            if (n == 4) return _json(await _librarySeries(libId, q));
            return _json(await _seriesMeta(at(4), libId));
          case 'authors':
            return _json(await _libraryAuthors(libId, q));
          case 'search':
            return _json(await _search(libId, q['q'] ?? '', int.tryParse(q['limit'] ?? '') ?? 25));
          case 'filterdata':
            return _json(await _filterData(libId));
          case 'narrators':
            final narrators = await _entityCounts('narrator', pages: 20);
            return _json({
              'narrators': [for (final n in narrators) {'name': n.name, 'numBooks': n.books}],
            });
          case 'collections':
            return _json(await _libraryCollections(libId, q));
          case 'playlists':
            return _json({'results': const [], 'total': 0});
          case 'stats':
            return _json(await _libraryStats(libId));
        }
        return null;
      case 'series':
        if (method == 'GET' && n == 3) return _json(await _seriesMeta(at(2), null));
        return null;
      case 'authors':
        if (method == 'GET' && n == 3) {
          final author = await _authorDetail(at(2), q);
          return author == null ? _status(404, 'Author not found') : _json(author);
        }
        if (n < 3) return null;
        final authorId = await _resolveAuthorId(at(2));
        if (authorId == null) return _status(404, 'Author not found');
        if (n == 3 && method == 'PATCH') return _json(await _updateAuthor(authorId, body));
        if (n == 4 && at(3) == 'image' && method == 'POST') return _authorImageFromUrl(authorId, '${body['url'] ?? ''}');
        if (n == 4 && at(3) == 'image' && method == 'DELETE') {
          await _boDelete('/authors/$authorId/image');
          return _json({'success': true});
        }
        if (n == 4 && at(3) == 'match' && method == 'POST') return _json(await _matchAuthor(authorId));
        return null;
      case 'search':
        if (method != 'GET') return null;
        switch (at(2)) {
          case 'covers':
            return _json({'results': await _searchCovers(q)});
          case 'books':
            return _json(await _searchBooks(q));
          case 'chapters':
            return _json(await _searchChapters(q['asin'] ?? '', q['region'] ?? 'us', bookId: q['id']));
        }
        return null;
      case 'items':
        if (n >= 3 && ApiService.isBookDockItem(at(2))) {
          return _routeDockItem(method, at(2), n == 4 ? at(3) : '', n, body);
        }
        if (at(2) == 'batch' && at(3) == 'get' && method == 'POST') {
          final ids = (body['libraryItemIds'] as List<dynamic>? ?? const []).map((e) => '$e').toList();
          return _json({'libraryItems': await _itemsBatch(ids)});
        }
        if (at(2) == 'batch' && at(3) == 'delete' && method == 'POST') {
          final ids = (body['libraryItemIds'] as List<dynamic>? ?? const []).map((e) => '$e').toList();
          return _deleteBooks(ids, hard: q['hard'] == '1');
        }
        if (n == 3 && method == 'GET') {
          final include = q['include'] ?? '';
          return _json(await _item(at(2), withProgress: include.contains('progress')));
        }
        if (n == 3 && method == 'DELETE') return _deleteBooks([at(2)], hard: q['hard'] == '1');
        if (n == 4 && at(3) == 'media' && method == 'PATCH') return _json(await _updateMedia(at(2), body));
        if (n == 4 && at(3) == 'cover' && method == 'POST') return _coverFromUrl(at(2), '${body['url'] ?? ''}');
        if (n == 4 && at(3) == 'cover' && method == 'DELETE') {
          await _boDelete('/books/${at(2)}/cover?medium=${await _coverMedium(at(2))}');
          await _afterEdit(at(2));
          return _json({'success': true});
        }
        if (n == 4 && at(3) == 'match' && method == 'POST') return _json(await _quickMatch(at(2)));
        if (n == 5 && at(3) == 'file' && method == 'DELETE') return _deleteFile(at(2), at(4));
        if (n == 4 && at(3) == 'chapters' && method == 'POST') {
          final chapters = BookOrbitMapper.chapters(body['chapters'] as List<dynamic>? ?? const []);
          await _boPatch('/books/${at(2)}/metadata', {
            'audioMetadata': {'chapters': chapters},
          });
          debugPrint('[BookOrbit] chapters for ${at(2)} saved: ${chapters?.length ?? 0}');
          await _afterEdit(at(2), chaptersChanged: true);
          return _json({'success': true, 'updated': true});
        }
        if (n >= 4 && at(3) == 'play' && method == 'POST') {
          if (n > 4) return null;
          return _json(await _startSession(at(2), body));
        }
        return null;
      case 'session':
        if (method != 'POST') return null;
        if (at(2) == 'local') return _json(await _localSession(body));
        if (at(2) == 'local-all') {
          final sessions = (body['sessions'] as List<dynamic>? ?? const [])
              .whereType<Map<String, dynamic>>()
              .toList();
          // One session BookOrbit turns away used to fail the whole batch, so
          // the app kept every session behind it and none ever arrived. A
          // refusal drops just that session; an unreachable server still
          // fails the batch so the queue waits for the next try.
          final results = <Map<String, dynamic>>[];
          for (final session in sessions) {
            var success = true;
            try {
              await _localSession(session);
            } on _BoHttpError catch (e) {
              if (e.status != 400 && e.status != 404) rethrow;
              debugPrint('[BookOrbit] Dropped a session for ${session['libraryItemId']}: ${e.status} ${e.serverMessage ?? ''}');
              success = false;
            }
            results.add({'id': session['id'], 'success': success});
          }
          return _json({'results': results});
        }
        if (n == 4 && at(3) == 'sync') return _syncSession(at(2), body);
        if (n == 4 && at(3) == 'close') {
          await _closeSession(at(2), body);
          return _json(const <String, dynamic>{});
        }
        return null;
      case 'collections':
        return _routeCollections(method, s, body);
    }
    return null;
  }

  Future<http.Response?> _routeMe(
    String method,
    List<String> s,
    Map<String, String> q,
    Map<String, dynamic> body,
  ) async {
    final n = s.length;
    String at(int i) => i < n ? s[i] : '';
    if (n == 2 && method == 'GET') {
      final me = Map<String, dynamic>.from(BookOrbitMapper.user(
          await _boGet('/auth/me') as Map<String, dynamic>));
      return _json(me);
    }
    switch (at(2)) {
      case 'progress':
        if (n == 3 && method == 'GET') {
          return _json({
            'mediaProgress': await _cached('progress', const Duration(seconds: 30), _allProgress),
          });
        }
        if (n == 4 && method == 'GET') {
          final p = await _itemProgress(at(3));
          return p == null ? _status(404, 'No progress') : _json(p);
        }
        if (n == 4 && method == 'PATCH') {
          await _patchProgress(at(3), body);
          return _json(const <String, dynamic>{});
        }
        if (n == 4 && method == 'DELETE') {
          await _deleteProgress(at(3));
          return _json(const <String, dynamic>{});
        }
        if (n == 5 && at(4) == 'remove-from-continue-listening' && method == 'GET') {
          final id = at(3);
          await _hideFromContinue(_hiddenBooksKey, id.startsWith('bo-') ? id.substring(3) : id);
          return _json(const <String, dynamic>{});
        }
        return null;
      case 'series':
        if (n == 5 && at(4) == 'remove-from-continue-listening' && method == 'GET') {
          await _hideFromContinue(_hiddenSeriesKey, at(3));
          return _json(const <String, dynamic>{});
        }
        return null;
      case 'bookmarks':
        if (method != 'GET') return null;
        if (n == 4) return _json({'bookmarks': await _bookmarksFor(at(3))});
        return _json({'bookmarks': await _recentBookmarks()});
      case 'item':
        if (at(3) == 'listening-sessions' && n >= 5 && method == 'GET') {
          if (n > 5) return _json({'sessions': const [], 'total': 0, 'numPages': 1, 'page': 0});
          return _json(await _itemListeningSessions(at(4), q));
        }
        if (n >= 5 && at(4) == 'bookmark') {
          final itemId = at(3);
          if (method == 'POST') {
            final b = await _createBookmark(itemId, body);
            return _json(b);
          }
          if (method == 'PATCH') {
            final ok = await _updateBookmark(itemId, body);
            return ok ? _json(const <String, dynamic>{}) : _status(404, 'Bookmark not found');
          }
          if (method == 'DELETE' && n == 6) {
            final ok = await _deleteBookmark(itemId, double.tryParse(at(5)) ?? -1);
            return ok ? _json(const <String, dynamic>{}) : _status(404, 'Bookmark not found');
          }
        }
        return null;
      case 'listening-stats':
        if (method == 'GET') {
          return _json(await _cached('listening-stats', const Duration(minutes: 5), _listeningStats));
        }
        return null;
      case 'listening-sessions':
        if (method == 'GET') {
          final perPage = (int.tryParse(q['itemsPerPage'] ?? '') ?? 20).clamp(1, 100);
          return _json(await _recentSessions(int.tryParse(q['page'] ?? '') ?? 0, perPage));
        }
        return null;
      case 'stats':
        final year = int.tryParse(at(4));
        if (method == 'GET' && n == 5 && at(3) == 'year' && year != null) {
          return _json(await _cached('year-stats-$year', const Duration(minutes: 5), () => _yearStats(year)));
        }
        return null;
      case 'items-in-progress':
        if (method == 'GET') {
          final cards = await _shelfCards('continue-listening', 50);
          return _json({'libraryItems': cards.map((c) => _cardItem(c)).toList()});
        }
        return null;
    }
    return null;
  }

  // The signed-in account's BookOrbit permissions, read with /auth/me.
  Set<String>? _permissions;
  bool _superuser = false;

  // Off when the user hid book requests in BookOrbit's settings.
  bool _showBookRequests = true;

  void _readPermissions(Map<String, dynamic> me) {
    _permissions = {for (final p in (me['permissions'] as List<dynamic>? ?? const [])) '$p'};
    _superuser = me['isSuperuser'] == true;
    _showBookRequests = (me['settings'] as Map?)?['showBookRequests'] != false;
  }

  bool _hasPermission(String permission) {
    final perms = _permissions;
    if (perms == null) return false;
    return _superuser || perms.contains('*') || perms.contains(permission);
  }

  Future<bool> _can(String permission) async {
    if (_permissions == null) {
      try {
        _readPermissions(await _boGet('/auth/me') as Map<String, dynamic>);
      } catch (e) {
        debugPrint('[BookOrbit] Could not read permissions: $e');
        return false;
      }
    }
    return _hasPermission(permission);
  }

  Future<Map<String, dynamic>> _authorizePayload() async {
    final raw = await _boGet('/auth/me') as Map<String, dynamic>;
    _readPermissions(raw);
    final version = await _fetchVersion(_cleanBaseUrl, _accessToken, customHeaders);
    return {
      'user': BookOrbitMapper.user(raw),
      'userDefaultLibraryId': null,
      'serverSettings': {'version': version ?? ''},
      'ereaderDevices': const [],
      'Source': 'bookorbit',
    };
  }

  Future<List<Map<String, dynamic>>> _libraries() async {
    final cached = _librariesCache;
    final at = _librariesAt;
    if (cached != null && at != null && DateTime.now().difference(at) < const Duration(minutes: 5)) {
      return cached;
    }
    final raw = await _boGet('/libraries') as List<dynamic>;
    final libs = raw
        .whereType<Map<String, dynamic>>()
        .where((l) => l['type'] != 'podcasts')
        .map(BookOrbitMapper.library)
        .toList();
    _librariesCache = libs;
    _librariesAt = DateTime.now();
    unawaited(loadCoverShape());
    return libs;
  }

  Future<Map<String, dynamic>?> _libraryStats(String libId) async {
    final s = await _boGet('/libraries/$libId/stats') as Map<String, dynamic>;
    final formats = (s['formatCounts'] as Map?)?.cast<String, dynamic>() ?? const {};
    final audio = formats.entries
        .where((e) => BookOrbitMapper.isAudioFormat(e.key))
        .fold<num>(0, (sum, e) => sum + ((e.value as num?) ?? 0));
    return {
      'totalItems': s['totalBooks'] ?? 0,
      'totalSize': s['totalSizeBytes'] ?? 0,
      'totalDuration': 0,
      'numAudioFiles': audio,
      'numAudioTracks': audio,
      'totalAuthors': 0,
      'totalGenres': 0,
    };
  }

  Map<String, dynamic> _cardItem(Map<String, dynamic> card, {String? libraryId}) {
    final id = '${card['id']}';
    final cv = card['coverVersion'] as String?;
    if (cv != null) _coverVersions[_key(id)] = cv;
    if (libraryId != null) _bookLibrary[_key(id)] = libraryId;
    final manifest = _manifests[_key(id)];
    return BookOrbitMapper.item(
      card: card,
      manifest: manifest,
      libraryId: libraryId ?? _bookLibrary[_key(id)],
    );
  }

  Future<Map<String, dynamic>> _detail(String bookId, {bool fresh = false}) async {
    final k = _key(bookId);
    final at = _detailAt[k];
    if (!fresh && at != null && DateTime.now().difference(at) < _detailTtl) {
      return _details[k]!;
    }
    final d = await _boGet('/books/$bookId') as Map<String, dynamic>;
    _keepDetail(k, d);
    return d;
  }

  void _keepDetail(String k, Map<String, dynamic> d) {
    _details[k] = d;
    _detailAt[k] = DateTime.now();
    final cv = d['coverVersion'] as String?;
    if (cv != null) _coverVersions[k] = cv;
    final lib = d['libraryId'];
    if (lib != null) _bookLibrary[k] = '$lib';
  }

  static bool _detailHasAudio(Map<String, dynamic> detail) =>
      (detail['files'] as List<dynamic>? ?? const [])
          .whereType<Map<String, dynamic>>()
          .where((f) => f['role'] == 'primary' || f['role'] == 'content')
          .any((f) => BookOrbitMapper.isAudioFormat(f['format'] as String?));

  Future<Map<String, dynamic>?> _manifest(String bookId, {bool fresh = false}) async {
    final k = _key(bookId);
    final at = _manifestAt[k];
    if (!fresh && at != null && DateTime.now().difference(at) < _manifestTtl) {
      return _manifests[k];
    }
    try {
      final m = await _boGet('/audiobooks/$bookId/manifest') as Map<String, dynamic>;
      _manifests[k] = m;
      _manifestAt[k] = DateTime.now();
      for (final a in (m['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
        _assetByFile[_key('${a['fileId']}')] = '${a['assetId']}';
        final etag = a['etag'];
        if (etag is String && etag.isNotEmpty) {
          _assetVersion['${a['assetId']}'] = etag.length > 16 ? etag.substring(0, 16) : etag;
        }
      }
      return m;
    } on _BoHttpError catch (e) {
      if (e.status == 404) return null;
      rethrow;
    }
  }

  Future<Map<String, dynamic>> _item(String bookId, {bool withProgress = false}) async {
    final detail = await _detail(bookId, fresh: true);
    final manifest = _detailHasAudio(detail) ? await _manifest(bookId) : null;
    final item = BookOrbitMapper.item(detail: detail, manifest: manifest);
    if (withProgress) {
      final p = await _itemProgress(bookId, detail: detail, manifest: manifest);
      if (p != null) item['userMediaProgress'] = p;
    }
    return item;
  }

  Future<List<Map<String, dynamic>>> _itemsBatch(List<String> ids) async {
    final jobs = ids.map((id) => () async {
          try {
            if (ApiService.isBookDockItem(id)) {
              return BookOrbitMapper.dockItem(await _dockFile(_dockFileId(id)));
            }
            final detail = await _detail(id);
            return BookOrbitMapper.item(detail: detail, manifest: _manifests[_key(id)]);
          } catch (_) {
            return null;
          }
        }).toList();
    final items = await _pool(jobs);
    return items.whereType<Map<String, dynamic>>().toList();
  }

  static const _audioFormatList = ['m4b', 'mp3', 'm4a', 'opus', 'ogg', 'flac'];
  static const _ebookFormatList = ['epub', 'kepub', 'pdf', 'mobi', 'azw3', 'azw', 'fb2', 'cbz', 'cbr', 'cb7'];

  Map<String, dynamic> _rule(String field, String op, [Object? value, Object? valueTo]) => {
        'type': 'rule',
        'field': field,
        'operator': op,
        if (value != null) 'value': value,
        if (valueTo != null) 'valueTo': valueTo,
      };

  /// Turns an Audiobookshelf `group.base64value` filter into BookOrbit rules.
  /// Returns (rules, q, unsupported).
  Future<({List<Map<String, dynamic>> rules, String? q, bool unsupported, String? seriesId})>
      _translateFilter(String? filter) async {
    final rules = <Map<String, dynamic>>[];
    if (filter == null || filter.isEmpty) {
      return (rules: rules, q: null, unsupported: false, seriesId: null);
    }
    final dot = filter.indexOf('.');
    final group = dot < 0 ? filter : filter.substring(0, dot);
    var value = '';
    if (dot >= 0) {
      final raw = undoPercentEscapes(filter.substring(dot + 1));
      try {
        value = utf8.decode(base64Decode(base64.normalize(raw)));
      } catch (_) {
        value = raw;
      }
    }
    String? q;
    switch (group) {
      case 'progress':
        switch (value) {
          case 'finished':
            rules.add(_rule('readStatus', 'includesAny', ['read', 'skimmed']));
          case 'in-progress':
            rules.add(_rule('readStatus', 'includesAny', ['reading', 'rereading', 'on_hold']));
          case 'not-started':
            rules.add(_rule('readStatus', 'includesAny', ['unread', 'want_to_read']));
          case 'not-finished':
            rules.add(_rule('readStatus', 'excludesAll', ['read', 'skimmed']));
        }
      case 'readStatus':
        rules.add(_rule('readStatus', 'includesAny', [value]));
      case 'series':
        if (int.tryParse(value) != null) {
          return (rules: rules, q: null, unsupported: false, seriesId: value);
        }
        final name = value.startsWith('name:') ? value.substring(5) : value;
        rules.add(_rule('series', 'eq', name));
      case 'authors':
        final name = await _authorName(value);
        if (name == null) return (rules: rules, q: null, unsupported: true, seriesId: null);
        rules.add(_rule('author', 'includesAny', [name]));
      case 'narrators':
        q = value;
      case 'genres':
        rules.add(_rule('genre', 'includesAny', [value]));
      case 'tags':
        rules.add(_rule('tag', 'includesAny', [value]));
      case 'languages':
        rules.add(_rule('language', 'eq', value));
      case 'publishers':
        rules.add(_rule('publisher', 'eq', value));
      case 'publishedDecades':
        final decade = int.tryParse(value);
        if (decade != null) rules.add(_rule('publishedYear', 'between', decade, decade + 9));
      case 'ebooks':
        if (value == 'ebook' || value == 'supplementary') {
          rules.add(_rule('format', 'includesAny', _ebookFormatList));
        } else {
          rules.add(_rule('format', 'excludesAll', _ebookFormatList));
        }
      case 'tracks':
        if (value == 'none') {
          rules.add(_rule('format', 'excludesAll', _audioFormatList));
        } else {
          rules.add(_rule('format', 'includesAny', _audioFormatList));
        }
      case 'issues':
        rules.add(_rule('fileAvailability', 'isMissing'));
      case 'missing':
        final field = switch (value) {
          'isbn' => 'isbn',
          'description' => 'description',
          'series' => 'series',
          'authors' => 'author',
          'publishedYear' => 'publishedYear',
          'publisher' => 'publisher',
          'genres' => 'genre',
          'tags' => 'tag',
          'language' => 'language',
          'cover' => 'cover',
          _ => null,
        };
        if (field == null) return (rules: rules, q: null, unsupported: true, seriesId: null);
        rules.add(field == 'cover' ? _rule('cover', 'isMissing') : _rule(field, 'isEmpty'));
      default:
        return (rules: rules, q: null, unsupported: true, seriesId: null);
    }
    return (rules: rules, q: q, unsupported: false, seriesId: null);
  }

  List<Map<String, dynamic>> _translateSort(String? sort, bool desc) {
    final dir = desc ? 'desc' : 'asc';
    final field = switch (sort) {
      'addedAt' || 'birthtimeMs' || 'mtimeMs' => 'addedAt',
      'updatedAt' => 'updatedAt',
      'media.metadata.title' || 'media.metadata.titleIgnorePrefix' => 'title',
      'media.metadata.authorName' ||
      'media.metadata.authorNameLF' ||
      'media.metadata.author' =>
        'author',
      'media.metadata.publishedYear' => 'publishedYear',
      'size' => 'fileSize',
      'progress' => 'lastReadAt',
      'progress.createdAt' => 'startedAt',
      'progress.finishedAt' => 'finishedAt',
      'sequence' || 'media.metadata.series.sequence' => 'seriesIndex',
      'random' => 'random',
      _ => 'title',
    };
    return [
      {'field': field, 'dir': dir},
      if (field != 'title') {'field': 'title', 'dir': 'asc'},
    ];
  }

  Future<String?> _authorName(String authorId) async {
    if (authorId.startsWith(BookOrbitMapper.authorNamePrefix)) {
      return authorId.substring(BookOrbitMapper.authorNamePrefix.length);
    }
    if (int.tryParse(authorId) == null) return authorId;
    try {
      final a = await _boGet('/authors/$authorId') as Map<String, dynamic>;
      return a['name'] as String?;
    } catch (_) {
      return null;
    }
  }

  Future<Map<String, dynamic>> _libraryItems(String libId, Map<String, String> q) async {
    var page = int.tryParse(q['page'] ?? '') ?? 0;
    var limit = int.tryParse(q['limit'] ?? '') ?? 20;
    final desc = q['desc'] == '1';
    final sort = q['sort'];
    final collapse = q['collapseseries'] == '1';
    final filter = q['filter'];
    final t = await _translateFilter(filter);

    Map<String, dynamic> envelope(List<Map<String, dynamic>> results, int total) => {
          'results': results,
          'total': total,
          'limit': limit,
          'page': page,
          'sortBy': sort,
          'sortDesc': desc,
          'filterBy': filter,
          'mediaType': 'book',
          'minified': q['minified'] != '0',
          'collapseseries': collapse,
          'include': '',
        };

    if (t.unsupported) {
      debugPrint('[BookOrbit] Filter $filter has no BookOrbit equivalent');
      return envelope(const [], 0);
    }
    // BookOrbit has no narrator rule, so a narrator is a text search narrowed
    // to exact names here. Paging happens after the narrowing.
    final narrator = filter != null && filter.startsWith('narrators.') ? t.q?.toLowerCase() : null;
    final wantPage = page;
    final wantLimit = limit;
    if (narrator != null) {
      page = 0;
      limit = 0;
    }
    if (t.seriesId != null) {
      final books = await _seriesBooks(t.seriesId!, libId, sort: sort, desc: desc);
      final start = limit <= 0 ? 0 : page * limit;
      final slice = limit <= 0
          ? books
          : books.skip(start).take(limit).toList();
      return envelope(slice, books.length);
    }

    final rules = t.rules;
    Map<String, dynamic> query(int p, int size) => {
          if (rules.isNotEmpty) 'filter': {'type': 'group', 'join': 'AND', 'rules': rules},
          'sort': _translateSort(sort, desc),
          'pagination': {'page': p, 'size': size},
          if (collapse) 'collapseSeries': true,
          if (t.q != null) 'q': t.q,
        };

    final cards = <Map<String, dynamic>>[];
    var total = 0;
    if (limit > 0 && limit <= 200) {
      final res = await _boPost('/libraries/$libId/books', query(page, limit)) as Map<String, dynamic>;
      cards.addAll((res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>());
      total = (res['total'] as num?)?.toInt() ?? cards.length;
    } else {
      // limit 0 means everything; bigger pages are stitched from 200s.
      final start = limit <= 0 ? 0 : page * limit;
      final want = limit <= 0 ? 1 << 30 : limit;
      var serverPage = start ~/ 200;
      var skip = start % 200;
      for (var guard = 0; guard < 100 && cards.length < want; guard++) {
        final res = await _boPost('/libraries/$libId/books', query(serverPage, 200)) as Map<String, dynamic>;
        final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
        total = (res['total'] as num?)?.toInt() ?? total;
        cards.addAll(items.skip(skip).take(want - cards.length));
        skip = 0;
        serverPage++;
        if (items.length < 200 || serverPage * 200 >= total) break;
      }
      if (limit <= 0) limit = cards.length;
    }

    var results = cards.map((c) => _cardItem(c, libraryId: libId)).toList();
    if (narrator != null) {
      results = results.where((item) {
        final names = ((item['media'] as Map)['metadata'] as Map)['narrators'] as List;
        return names.any((n) => '$n'.toLowerCase() == narrator);
      }).toList();
      total = results.length;
      page = wantPage;
      limit = wantLimit;
      if (limit > 0) results = results.skip(page * limit).take(limit).toList();
    }
    return envelope(results, total);
  }

  Future<List<Map<String, dynamic>>> _seriesBooks(
    String seriesId,
    String? libId, {
    String? sort,
    bool desc = false,
  }) async {
    final bySort = switch (sort) {
      'addedAt' => 'addedAt',
      'media.metadata.title' => 'title',
      _ => 'seriesIndex',
    };
    final out = <Map<String, dynamic>>[];
    for (var page = 0; page < 20; page++) {
      final res = await _boGet('/series/$seriesId/books', {
        'page': page,
        'size': 100,
        'sort': bySort,
        'order': desc ? 'desc' : 'asc',
        if (libId != null) 'libraryId': libId,
      }) as Map<String, dynamic>;
      final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
      for (final c in items) {
        final item = _cardItem(c, libraryId: libId);
        // A series listing names this series' number in the single-map form
        // the series sheets read.
        final meta = (item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>;
        meta['series'] = {
          'id': seriesId,
          'name': c['seriesName'],
          'sequence': c['seriesIndex'],
        };
        out.add(item);
      }
      final total = (res['total'] as num?)?.toInt() ?? out.length;
      if (items.length < 100 || out.length >= total) break;
    }
    return out;
  }

  Future<List<Map<String, dynamic>>> _shelfCards(String type, int limit) async {
    final res = await _boGet('/dashboard/scrollers/$type', {'limit': limit.clamp(1, 50)}) as Map<String, dynamic>;
    return (res['books'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
  }

  Future<bool> _hasOneLibrary() async => (await _libraries()).length <= 1;

  /// Dashboard shelves span every library. With more than one, keep the
  /// cards this library's in-progress books (one query) say belong here.
  Future<List<Map<String, dynamic>>> _inProgressHere(List<Map<String, dynamic>> cards, String libId) async {
    if (await _hasOneLibrary()) return cards;
    final here = await _libraryQueryCards(
      libId,
      rules: [_rule('readStatus', 'includesAny', ['reading', 'rereading', 'on_hold'])],
      sort: [{'field': 'lastReadAt', 'dir': 'desc'}],
      size: 200,
    );
    final ids = {for (final c in here) '${c['id']}'};
    for (final c in here) {
      _bookLibrary[_key('${c['id']}')] = libId;
    }
    final kept = cards.where((c) => ids.contains('${c['id']}')).toList();
    final keptIds = {for (final c in kept) '${c['id']}'};
    return [...kept, ...here.where((c) => !keptIds.contains('${c['id']}'))];
  }

  Future<List<Map<String, dynamic>>> _libraryQueryCards(
    String libId, {
    List<Map<String, dynamic>> rules = const [],
    required List<Map<String, dynamic>> sort,
    int size = 20,
  }) async {
    final res = await _boPost('/libraries/$libId/books', {
      if (rules.isNotEmpty) 'filter': {'type': 'group', 'join': 'AND', 'rules': rules},
      'sort': sort,
      'pagination': {'page': 0, 'size': size.clamp(1, 200)},
    }) as Map<String, dynamic>;
    return (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
  }

  Future<List<Map<String, dynamic>>> _personalized(String libId, Map<String, String> q) async {
    final limit = (int.tryParse(q['limit'] ?? '') ?? 15).clamp(1, 50);
    final wanted = (q['shelves'] ?? '').split(',').where((s) => s.isNotEmpty).toSet();
    bool want(String id) => wanted.isEmpty || wanted.contains(id);
    final hiddenBooks = (await ScopedPrefs.getStringList(_hiddenBooksKey)).toSet();
    final hiddenSeries = (await ScopedPrefs.getStringList(_hiddenSeriesKey)).toSet();
    bool hidden(String shelfId, Map<String, dynamic> c) => switch (shelfId) {
          'continue-listening' || 'continue-reading' => hiddenBooks.contains('${c['id']}'),
          'continue-series' => hiddenSeries.contains('${c['seriesId'] ?? 'name:${c['seriesName']}'}'),
          _ => false,
        };

    Map<String, dynamic> shelf(String id, String label, List<Map<String, dynamic>> cards, {bool seriesEntity = false}) {
      final entities = cards.where((c) => !hidden(id, c)).map((c) {
        final item = _cardItem(c, libraryId: libId);
        if (seriesEntity && c['seriesName'] != null) {
          ((item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>)['series'] = {
            'id': '${c['seriesId'] ?? 'name:${c['seriesName']}'}',
            'name': c['seriesName'],
            'sequence': c['seriesIndex'],
          };
        }
        return item;
      }).toList();
      return {
        'id': id,
        'label': label,
        'labelStringKey': label,
        'type': 'book',
        'entities': entities,
        'total': entities.length,
      };
    }

    final shelves = <Map<String, dynamic>>[];
    Future<void> add(String id, Future<Map<String, dynamic>> Function() build) async {
      if (!want(id)) return;
      try {
        final s = await build();
        if ((s['entities'] as List).isNotEmpty) shelves.add(s);
      } catch (e) {
        debugPrint('[BookOrbit] Shelf $id failed: $e');
      }
    }

    // BookOrbit's dashboard keeps listening and reading apart, and so do the
    // shelves here, the way Audiobookshelf has them. A narrated EPUB goes
    // with the audiobooks once its narration has been played, and stays
    // with the reading while it has only been read; a book only the
    // library's own in-progress query found goes by whether it has audio.
    List<Map<String, dynamic>>? inProgress;
    var listenIds = <String>{}, readIds = <String>{};
    final narrationPlayed = <String>{};
    Map media(Map<String, dynamic> c) => _cardItem(c, libraryId: libId)['media'] as Map? ?? const {};
    Future<List<Map<String, dynamic>>> progressCards() async {
      final had = inProgress;
      if (had != null) return had;
      final listening = await _shelfCards('continue-listening', 50);
      final reading = await _shelfCards('continue-reading', 50);
      listenIds = {for (final c in listening) '${c['id']}'};
      readIds = {for (final c in reading) '${c['id']}'};
      // Audiobooks being read as ebooks, which BookOrbit's reading list
      // leaves out, go with the reading unless they're being listened to.
      try {
        await _cached('progress', const Duration(seconds: 30), _allProgress);
      } catch (e) {
        debugPrint('[BookOrbit] Reading progress for Continue Reading failed: $e');
      }
      final ebookRead = _ebookReadCards.entries
          .where((e) => !listenIds.contains(e.key) && !readIds.contains(e.key))
          .map((e) => e.value)
          .toList();
      readIds.addAll(ebookRead.map((c) => '${c['id']}'));
      final seen = <String>{};
      final merged = [...listening, ...reading, ...ebookRead].where((c) => seen.add('${c['id']}')).toList();
      final cards = await _inProgressHere(merged, libId);
      // BookOrbit 3.5.0 lists a narrated EPUB under listening once it has
      // been played; an older server never does, and there a listening spot
      // on the book's progress tells.
      final narrated = cards
          .map((c) => '${c['id']}')
          .where((id) => !listenIds.contains(id))
          .where((id) => media(cards.firstWhere((c) => '${c['id']}' == id))['narration'] != null)
          .toList();
      final played = await _pool(narrated.map((id) => () => _narrationPlayed(id)).toList());
      narrationPlayed
        ..addAll(listenIds)
        ..addAll([for (var i = 0; i < narrated.length; i++) if (played[i]) narrated[i]]);
      return inProgress = cards;
    }

    bool hasAudio(Map m) => m['narration'] != null || ((m['duration'] as num?) ?? 0) > 0;
    bool listened(Map<String, dynamic> c) {
      final id = '${c['id']}';
      final m = media(c);
      if (m['narration'] != null) return narrationPlayed.contains(id);
      if (listenIds.contains(id)) return true;
      return !readIds.contains(id) && hasAudio(m);
    }

    bool read(Map<String, dynamic> c) {
      final id = '${c['id']}';
      final m = media(c);
      if (m['narration'] != null) return !narrationPlayed.contains(id);
      if (readIds.contains(id)) return true;
      return !listenIds.contains(id) && !hasAudio(m);
    }

    // Continue Listening draws from both of BookOrbit's shelves (narrated
    // EPUBs come from the reading one), each newest first on its own. Put
    // the two in one order by when each book was last touched, or every
    // audiobook would sit ahead of a narrated book just listened to.
    Future<List<Map<String, dynamic>>> newestFirst(List<Map<String, dynamic>> cards) async {
      final audio = cards.where((c) => listenIds.contains('${c['id']}')).toList();
      final rest = cards.where((c) => !listenIds.contains('${c['id']}')).toList();
      if (audio.isEmpty || rest.isEmpty) return cards;
      final heads = [...audio.take(limit), ...rest.take(limit)];
      final times = await _pool(heads
          .map((c) => () => _lastTouched('${c['id']}', narrated: media(c)['narration'] != null))
          .toList());
      final at = {for (var i = 0; i < heads.length; i++) '${heads[i]['id']}': times[i] ?? 0};
      int when(Map<String, dynamic> c) => at['${c['id']}'] ?? 0;
      final out = <Map<String, dynamic>>[];
      var a = 0, r = 0;
      while (a < audio.length && r < rest.length) {
        out.add(when(audio[a]) >= when(rest[r]) ? audio[a++] : rest[r++]);
      }
      return [...out, ...audio.skip(a), ...rest.skip(r)];
    }

    await add('continue-listening', () async {
      final cards = (await newestFirst((await progressCards()).where(listened).toList())).take(limit).toList();
      // A play checks the server's spot for a moment only, and placing a
      // narrated book's spot needs its timings: read them now, not then.
      for (final c in cards) {
        if (media(c)['narration'] == null) continue;
        unawaited(_narration('${c['id']}').then((_) {}, onError: (Object _) {}));
      }
      return shelf('continue-listening', 'Continue Listening', cards);
    });
    await add('continue-reading', () async {
      final cards = (await progressCards()).where(read).take(limit).toList();
      debugPrint('[BookOrbit] Continue Reading: ${cards.length} of ${readIds.length} reading cards');
      return shelf('continue-reading', 'Continue Reading', cards);
    });
    await add('continue-series', () async {
      final cards = await _hasOneLibrary()
          ? await _shelfCards('up-next-in-series', limit)
          : await _libraryQueryCards(
              libId,
              rules: [_rule('seriesStatus', 'isUpNext')],
              sort: [{'field': 'series', 'dir': 'asc'}],
              size: limit,
            );
      return shelf('continue-series', 'Continue Series', cards.take(limit).toList(), seriesEntity: true);
    });
    await add('recently-added', () async {
      final cards = await _libraryQueryCards(libId, sort: [{'field': 'addedAt', 'dir': 'desc'}], size: limit);
      return shelf('recently-added', 'Recently Added', cards);
    });
    await add('listen-again', () async {
      final cards = await _libraryQueryCards(
        libId,
        // Skimmed counts as finished everywhere else, here too.
        rules: [_rule('readStatus', 'includesAny', ['read', 'skimmed'])],
        sort: [{'field': 'finishedAt', 'dir': 'desc'}],
        size: limit,
      );
      return shelf('listen-again', 'Listen Again', cards);
    });
    await add('discover', () async {
      final cards = await _libraryQueryCards(
        libId,
        rules: [_rule('readStatus', 'includesAny', ['unread'])],
        sort: [{'field': 'random', 'dir': 'asc'}],
        size: limit,
      );
      return shelf('discover', 'Discover', cards);
    });
    return shelves;
  }

  /// When a book was last listened to or read, on any device. A narrated
  /// EPUB keeps its place on its files' progress; an audiobook on its
  /// playback state. Null when it can't be told.
  /// Whether a narrated EPUB's narration has been played: a listening spot
  /// on its progress. Taken as played when that can't be read, where it
  /// always went before.
  Future<bool> _narrationPlayed(String bookId) async {
    try {
      final rows = await _boGet('/books/$bookId/progress') as List<dynamic>;
      return rows.whereType<Map<String, dynamic>>().any((r) => r['positionSeconds'] != null);
    } catch (_) {
      return true;
    }
  }

  Future<int?> _lastTouched(String bookId, {required bool narrated}) async {
    try {
      if (!narrated) return BookOrbitMapper.ms((await _playbackState(bookId))?['capturedAt']);
      final rows = await _boGet('/books/$bookId/progress') as List<dynamic>;
      int? newest;
      for (final r in rows.whereType<Map<String, dynamic>>()) {
        final at = BookOrbitMapper.ms(r['updatedAt']);
        if (at != null && (newest == null || at > newest)) newest = at;
      }
      return newest;
    } catch (_) {
      return null;
    }
  }

  Map<String, dynamic> _stubItem(String bookId, {String? title, String? seriesId, String? seriesName, Object? sequence}) => {
        'id': bookId,
        'mediaType': 'book',
        'libraryId': _bookLibrary[_key(bookId)] ?? '',
        'media': {
          'coverPath': '/bookorbit/books/$bookId/cover',
          'metadata': {
            'title': title ?? '',
            'authorName': '',
            if (seriesId != null) 'series': {'id': seriesId, 'name': seriesName, 'sequence': sequence?.toString()},
          },
        },
      };

  Map<String, dynamic> _seriesSummary(Map<String, dynamic> s, String? libId) {
    final id = '${s['id']}';
    final books = <Map<String, dynamic>>[];
    for (final v in (s['volumes'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      final bookId = v['bookId'];
      if (bookId == null) continue;
      books.add(_stubItem('$bookId', title: v['title'] as String?, seriesId: id, seriesName: s['name'] as String?, sequence: v['index']));
    }
    if (books.isEmpty) {
      for (final bookId in (s['coverBookIds'] as List<dynamic>? ?? const [])) {
        books.add(_stubItem('$bookId', seriesId: id, seriesName: s['name'] as String?));
      }
    }
    return BookOrbitMapper.series(s, books: books)..['libraryId'] = libId ?? '';
  }

  Future<Map<String, dynamic>> _librarySeries(String libId, Map<String, String> q) async {
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final limit = (int.tryParse(q['limit'] ?? '') ?? 50).clamp(1, 1000);
    final desc = q['desc'] == '1';
    final sort = switch (q['sort']) {
      'numBooks' || 'totalDuration' => 'bookCount',
      'addedAt' || 'lastBookAdded' || 'lastBookUpdated' || 'updatedAt' => 'lastAddedAt',
      _ => 'name',
    };
    final results = <Map<String, dynamic>>[];
    var total = 0;
    final start = page * limit;
    var serverPage = start ~/ 100;
    var skip = start % 100;
    for (var guard = 0; guard < 50 && results.length < limit; guard++) {
      final res = await _boGet('/series', {
        'page': serverPage,
        'size': 100,
        'sort': sort,
        'order': desc ? 'desc' : 'asc',
        'libraryId': libId,
      }) as Map<String, dynamic>;
      final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
      total = (res['total'] as num?)?.toInt() ?? total;
      results.addAll(items.skip(skip).take(limit - results.length).map((s) => _seriesSummary(s, libId)));
      skip = 0;
      serverPage++;
      if (items.length < 100 || serverPage * 100 >= total) break;
    }
    return {'results': results, 'total': total, 'limit': limit, 'page': page};
  }

  Future<Map<String, dynamic>?> _seriesMeta(String seriesId, String? libId) async {
    if (int.tryParse(seriesId) == null) return null;
    final res = await _boGet('/series/$seriesId/books', {
      'page': 0,
      'size': 1,
      if (libId != null) 'libraryId': libId,
    }) as Map<String, dynamic>;
    final info = res['seriesInfo'] as Map<String, dynamic>? ?? const {};
    return {
      'id': seriesId,
      'name': info['name'] ?? '',
      'nameIgnorePrefix': info['name'] ?? '',
      'numBooks': info['bookCount'] ?? res['total'] ?? 0,
      'libraryId': libId ?? '',
      'authors': info['authors'] ?? const [],
    };
  }

  Future<Map<String, dynamic>> _libraryAuthors(String libId, Map<String, String> q) async {
    final paged = q.containsKey('page');
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final limit = (int.tryParse(q['limit'] ?? '') ?? 100).clamp(1, 1000);
    final desc = q['desc'] == '1';
    final sort = switch (q['sort']) {
      'lastFirst' => 'sortName',
      'numBooks' => 'bookCount',
      'addedAt' || 'updatedAt' => 'lastAddedAt',
      _ => 'name',
    };
    final authors = <Map<String, dynamic>>[];
    var total = 0;
    final start = paged ? page * limit : 0;
    final want = paged ? limit : 5000;
    var serverPage = start ~/ 100;
    var skip = start % 100;
    for (var guard = 0; guard < 60 && authors.length < want; guard++) {
      final res = await _boGet('/authors', {
        'page': serverPage,
        'size': 100,
        'sort': sort,
        'order': desc ? 'desc' : 'asc',
        'libraryId': libId,
      }) as Map<String, dynamic>;
      final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
      total = (res['total'] as num?)?.toInt() ?? total;
      authors.addAll(items.skip(skip).take(want - authors.length).map(BookOrbitMapper.author));
      skip = 0;
      serverPage++;
      if (items.length < 100 || serverPage * 100 >= total) break;
    }
    if (!paged) return {'authors': authors};
    return {'results': authors, 'total': total, 'limit': limit, 'page': page};
  }

  Future<String?> _resolveAuthorId(String authorId) async {
    if (int.tryParse(authorId) != null) return authorId;
    final name = authorId.startsWith(BookOrbitMapper.authorNamePrefix)
        ? authorId.substring(BookOrbitMapper.authorNamePrefix.length)
        : authorId;
    final res = await _boGet('/authors', {'q': name, 'size': 25}) as Map<String, dynamic>;
    for (final a in (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      if ('${a['name']}'.toLowerCase() == name.toLowerCase()) return '${a['id']}';
    }
    return null;
  }

  Future<Map<String, dynamic>?> _authorDetail(String authorId, Map<String, String> q) async {
    final id = await _resolveAuthorId(authorId);
    if (id == null) return null;
    final raw = await _boGet('/authors/$id') as Map<String, dynamic>;
    final author = BookOrbitMapper.author(raw);
    final include = q['include'] ?? '';
    if (include.contains('items') || include.contains('series')) {
      final libId = q['library'];
      final items = <Map<String, dynamic>>[];
      for (var page = 0; page < 20; page++) {
        final res = await _boGet('/authors/$id/books', {
          'page': page,
          'size': 100,
          'sort': 'title',
          'order': 'asc',
          if (libId != null) 'libraryId': libId,
        }) as Map<String, dynamic>;
        final cards = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
        items.addAll(cards.map((c) => _cardItem(c, libraryId: libId)));
        final total = (res['total'] as num?)?.toInt() ?? items.length;
        if (cards.length < 100 || items.length >= total) break;
      }
      author['libraryItems'] = items;
      final bySeries = <String, Map<String, dynamic>>{};
      for (final item in items) {
        final meta = (item['media'] as Map<String, dynamic>)['metadata'] as Map<String, dynamic>;
        for (final s in (meta['series'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
          final entry = bySeries.putIfAbsent('${s['id']}', () => {'id': s['id'], 'name': s['name'], 'items': <Map<String, dynamic>>[]});
          (entry['items'] as List<Map<String, dynamic>>).add(item);
        }
      }
      author['series'] = bySeries.values.toList();
    }
    return author;
  }

  Future<Map<String, dynamic>> _search(String libId, String text, int limit) async {
    final query = text.trim();
    final empty = {
      'book': const [],
      'podcast': const [],
      'series': const [],
      'authors': const [],
      'narrators': const [],
      'tags': const [],
      'genres': const [],
    };
    if (query.isEmpty) return empty;
    final booksFuture = _boPost('/libraries/$libId/books', {
      'q': query.length > 200 ? query.substring(0, 200) : query,
      'sort': [{'field': 'relevance', 'dir': 'desc'}],
      'pagination': {'page': 0, 'size': limit.clamp(1, 200)},
    });
    Future<dynamic>? globalFuture;
    if (query.length >= 2) {
      globalFuture = _boGet('/search', {
        'q': query.length > 200 ? query.substring(0, 200) : query,
        'limit': 10,
        'libraryId': libId,
      }).catchError((_) => null);
    }
    final books = await booksFuture as Map<String, dynamic>;
    final global = await globalFuture as Map<String, dynamic>?;

    final bookHits = (books['items'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        .map((c) => {'libraryItem': _cardItem(c, libraryId: libId), 'matchKey': 'title', 'matchText': c['title']})
        .toList();
    final series = ((global?['series'] as Map?)?['items'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        .map((hit) {
      final summary = _seriesSummary(hit['item'] as Map<String, dynamic>, libId);
      return {'series': summary, 'books': summary['books']};
    }).toList();
    final authors = ((global?['authors'] as Map?)?['items'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        .map((hit) => BookOrbitMapper.author(hit['item'] as Map<String, dynamic>))
        .toList();
    final narratorCounts = <String, int>{};
    final lower = query.toLowerCase();
    for (final hit in bookHits) {
      final meta = ((hit['libraryItem'] as Map)['media'] as Map)['metadata'] as Map;
      for (final name in (meta['narrators'] as List? ?? const [])) {
        if ('$name'.toLowerCase().contains(lower)) {
          narratorCounts['$name'] = (narratorCounts['$name'] ?? 0) + 1;
        }
      }
    }
    return {
      ...empty,
      'book': bookHits,
      'series': series,
      'authors': authors,
      'narrators': narratorCounts.entries.map((e) => {'name': e.key, 'numBooks': e.value}).toList(),
    };
  }

  /// Names and book counts of a genre, tag, narrator, publisher or language,
  /// most used first, [pages] of 100 at most. BookOrbit only lists them for
  /// accounts that can edit metadata; others get none.
  Future<List<({String name, int books})>> _entityCounts(String type, {int pages = 1}) async {
    final out = <({String name, int books})>[];
    try {
      for (var page = 1; page <= pages; page++) {
        final res = await _boGet('/entity-manager/$type/browse', {
          'page': page,
          'pageSize': 100,
          'sortBy': 'bookCount',
          'sortOrder': 'desc',
        }) as Map<String, dynamic>;
        final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
        for (final e in items) {
          final name = '${e['name'] ?? ''}';
          final books = (e['bookCount'] as num?)?.toInt() ?? 1;
          if (name.isNotEmpty && books > 0) out.add((name: name, books: books));
        }
        final total = (res['total'] as num?)?.toInt() ?? 0;
        if (items.length < 100 || page * 100 >= total) break;
      }
    } on _BoHttpError catch (e) {
      if (e.status != 403) debugPrint('[BookOrbit] No $type list: ${e.status}');
    }
    return out;
  }

  Future<List<String>> _entityNames(String type, {int pages = 1}) async =>
      (await _entityCounts(type, pages: pages)).map((e) => e.name).toList()
        ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));

  /// The decades that have books in the library, newest last.
  Future<List<String>> _publishedDecades(String libId) async {
    Future<Map<String, dynamic>> books(List<Map<String, dynamic>> rules, String dir) async =>
        await _boPost('/libraries/$libId/books', {
          'filter': {'type': 'group', 'join': 'AND', 'rules': rules},
          'sort': [{'field': 'publishedYear', 'dir': dir}],
          'pagination': {'page': 0, 'size': 1},
        }) as Map<String, dynamic>;
    int? year(Map<String, dynamic> res) {
      final items = res['items'] as List<dynamic>? ?? const [];
      return items.isEmpty ? null : ((items.first as Map)['publishedYear'] as num?)?.toInt();
    }

    try {
      final known = [_rule('publishedYear', 'isNotEmpty')];
      final ends = await Future.wait([books(known, 'asc'), books(known, 'desc')]);
      final first = year(ends[0]);
      final last = year(ends[1]);
      if (first == null || last == null) return const [];
      final decades = [for (var d = last - last % 10; d >= first - first % 10 && d > 0; d -= 10) d].take(30).toList();
      final counts = await Future.wait(decades.map((d) async =>
          ((await books([_rule('publishedYear', 'between', d, d + 9)], 'asc'))['total'] as num?)?.toInt() ?? 0));
      return [for (var i = decades.length - 1; i >= 0; i--) if (counts[i] > 0) '${decades[i]}'];
    } catch (e) {
      debugPrint('[BookOrbit] No decade list: $e');
      return const [];
    }
  }

  Future<Map<String, dynamic>> _filterData(String libId) =>
      _cached('filterdata:$libId', const Duration(minutes: 5), () => _loadFilterData(libId));

  Future<Map<String, dynamic>> _loadFilterData(String libId) async {
    final authors = (await _libraryAuthors(libId, const {}))['authors'] as List<dynamic>;
    final series = <Map<String, dynamic>>[];
    for (var page = 0; page < 30; page++) {
      final res = await _boGet('/series', {'page': page, 'size': 100, 'sort': 'name', 'order': 'asc', 'libraryId': libId}) as Map<String, dynamic>;
      final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
      series.addAll(items.map((s) => {'id': '${s['id']}', 'name': s['name'] ?? ''}));
      final total = (res['total'] as num?)?.toInt() ?? series.length;
      if (items.length < 100 || series.length >= total) break;
    }
    final lists = await Future.wait([
      _entityNames('genre'),
      _entityNames('tag'),
      _entityNames('narrator', pages: 20),
      _entityNames('language'),
      _entityNames('publisher', pages: 5),
      _publishedDecades(libId),
    ]);
    return {
      'authors': authors.map((a) => {'id': (a as Map)['id'], 'name': a['name']}).toList(),
      'series': series,
      'genres': lists[0],
      'tags': lists[1],
      'narrators': lists[2],
      'languages': lists[3],
      'publishers': lists[4],
      'publishedDecades': lists[5],
    };
  }

  /// Up to [maxBooks] of a collection's or scope's books, plus how many it
  /// holds in all.
  Future<({List<Map<String, dynamic>> books, int total})> _pagedBooks(String path, int maxBooks) async {
    final books = <Map<String, dynamic>>[];
    var total = 0;
    for (var page = 0; page < 40 && books.length < maxBooks; page++) {
      final res = await _boGet(path, {'page': page, 'size': 100}) as Map<String, dynamic>;
      final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
      books.addAll(items.map((card) => _cardItem(card)));
      total = (res['total'] as num?)?.toInt() ?? books.length;
      if (items.length < 100 || books.length >= total) break;
    }
    return (books: books, total: math.max(total, books.length));
  }

  @override
  Future<List<Map<String, dynamic>>?> collectionBooksPage(String collectionId,
      {required int page, int size = 100}) async {
    final path = collectionId.startsWith(_scopeIdPrefix)
        ? '/smart-scopes/${collectionId.substring(_scopeIdPrefix.length)}/books'
        : '/collections/$collectionId/books';
    try {
      final res = await _boGet(path, {'page': page, 'size': size}) as Map<String, dynamic>;
      return (res['items'] as List<dynamic>? ?? const [])
          .whereType<Map<String, dynamic>>()
          .map((card) => _cardItem(card))
          .toList();
    } catch (e) {
      debugPrint('[BookOrbit] $path page $page failed: $e');
      return null;
    }
  }

  Future<Map<String, dynamic>> _collection(Map<String, dynamic> c, {bool withBooks = true, int maxBooks = 2000}) async {
    final id = '${c['id']}';
    final paged = withBooks ? await _pagedBooks('/collections/$id/books', maxBooks) : null;
    final books = paged?.books ?? <Map<String, dynamic>>[];
    return {
      'id': id,
      'name': c['name'] ?? '',
      'description': c['description'],
      'libraryId': '',
      'userId': '${c['userId'] ?? ''}',
      'books': books,
      'lastUpdate': BookOrbitMapper.ms(c['updatedAt']),
      'createdAt': BookOrbitMapper.ms(c['createdAt']),
      'bookOrbit': {
        'isOwner': c['isOwner'],
        'isPublic': c['isPublic'],
        'bookCount': c['bookCount'],
        'total': ?paged?.total,
      },
    };
  }

  static const _scopeIdPrefix = 'scope-';

  /// The user's book Smart Scopes, listed after the collections as read-only
  /// ones. A server from before Smart Scopes has none.
  Future<List<Map<String, dynamic>>> _bookScopes() async {
    try {
      final raw = await _boGet('/smart-scopes');
      final list = raw is List ? raw : ((raw as Map?)?['items'] as List<dynamic>? ?? const []);
      return list
          .whereType<Map<String, dynamic>>()
          .where((s) => (s['mediaType'] ?? 'books') == 'books')
          .toList();
    } on _BoHttpError catch (e) {
      if (e.status == 404) return const [];
      rethrow;
    }
  }

  /// A Smart Scope in collection shape. Its books are whatever its rules
  /// match right now; a scope whose rules the server can't run has none.
  Future<Map<String, dynamic>> _scopeCollection(Map<String, dynamic> s, {int maxBooks = 2000}) async {
    final id = '${s['id']}';
    var books = <Map<String, dynamic>>[];
    int? total;
    try {
      final paged = await _pagedBooks('/smart-scopes/$id/books', maxBooks);
      books = paged.books;
      total = paged.total;
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] smart scope $id books failed: ${e.status}');
    }
    return {
      'id': '$_scopeIdPrefix$id',
      'name': s['name'] ?? '',
      'description': null,
      'libraryId': '',
      'userId': '${s['userId'] ?? ''}',
      'books': books,
      'lastUpdate': BookOrbitMapper.ms(s['updatedAt']),
      'createdAt': BookOrbitMapper.ms(s['createdAt']),
      'bookOrbit': {
        'smartScope': true,
        'scopeId': id,
        'isOwner': s['isOwner'] == true,
        'isPublic': s['isPublic'],
        'bookCount': s['bookCount'],
        'total': ?total,
        'icon': s['icon'],
      },
    };
  }

  /// A Smart Scope as BookOrbit keeps it, rules and sort included.
  Future<Map<String, dynamic>> smartScope(String id) async =>
      await _boGet('/smart-scopes/$id') as Map<String, dynamic>;

  Future<Map<String, dynamic>> createSmartScope(Map<String, dynamic> body) async =>
      await _boPost('/smart-scopes', body) as Map<String, dynamic>;

  Future<Map<String, dynamic>> updateSmartScope(String id, Map<String, dynamic> body) async =>
      await _boPatch('/smart-scopes/$id', body) as Map<String, dynamic>;

  Future<void> deleteSmartScope(String id) => _boDelete('/smart-scopes/$id');

  /// How many books [filter] matches right now, the count the web shows
  /// while a scope is edited. Null when the server can't say.
  Future<int?> smartScopeMatchCount(Map<String, dynamic>? filter, List<Map<String, dynamic>> sort) async {
    try {
      final res = await _boPost('/books/query', {
        if (sort.isNotEmpty) 'sort': sort.take(5).toList(),
        'pagination': {'page': 0, 'size': 1},
        if (filter != null) 'filter': filter,
      }) as Map<String, dynamic>;
      return (res['total'] as num?)?.toInt();
    } catch (e) {
      debugPrint('[BookOrbit] smart scope count: $e');
      return null;
    }
  }

  /// Names starting or containing [q] for a rule value: [source] is one of
  /// authors, genres, tags, series, publishers, languages, collections.
  Future<List<String>> metadataSuggestions(String source, String q) async {
    final text = q.trim();
    if (text.isEmpty) return const [];
    try {
      final list = await _boGet('/metadata/$source', {'q': text}) as List<dynamic>;
      return [
        for (final e in list.whereType<Map<String, dynamic>>())
          if ('${e['name'] ?? ''}'.isNotEmpty) '${e['name']}',
      ];
    } catch (e) {
      debugPrint('[BookOrbit] $source suggestions: $e');
      return const [];
    }
  }

  /// The user's custom metadata fields a rule can test: {key, label, type}
  /// with key `custom:<id>` and type text, url, number, date or boolean.
  Future<List<Map<String, String>>> customMetadataFields() async {
    try {
      final list = (await _boGet('/custom-metadata/fields/active') as List<dynamic>)
          .whereType<Map<String, dynamic>>()
          .where((f) => f['archivedAt'] == null && f['id'] != null)
          .toList()
        ..sort((a, b) {
          final byOrder = ((a['displayOrder'] as num?) ?? 0).compareTo((b['displayOrder'] as num?) ?? 0);
          return byOrder != 0 ? byOrder : '${a['label']}'.compareTo('${b['label']}');
        });
      return [
        for (final f in list) {'key': 'custom:${f['id']}', 'label': '${f['label'] ?? ''}', 'type': '${f['type'] ?? 'text'}'},
      ];
    } catch (e) {
      debugPrint('[BookOrbit] custom fields: $e');
      return const [];
    }
  }

  /// Library names, which is what a library rule matches on.
  Future<List<String>> libraryNames() async {
    try {
      final list = await _boGet('/libraries') as List<dynamic>;
      return [
        for (final l in list.whereType<Map<String, dynamic>>())
          if ('${l['name'] ?? ''}'.isNotEmpty) '${l['name']}',
      ];
    } catch (e) {
      debugPrint('[BookOrbit] library names: $e');
      return const [];
    }
  }

  Future<Map<String, dynamic>> _libraryCollections(String libId, Map<String, String> q) async {
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final limit = (int.tryParse(q['limit'] ?? '') ?? 25).clamp(1, 200);
    final collections = (await _boGet('/collections') as List<dynamic>)
        .whereType<Map<String, dynamic>>()
        .where((c) => (c['mediaType'] ?? 'books') == 'books');
    final all = [
      for (final c in collections) (entry: c, scope: false),
      for (final s in await _bookScopes()) (entry: s, scope: true),
    ];
    final slice = all.skip(page * limit).take(limit).toList();
    final results = await _pool(
        slice
            .map((e) => () => e.scope
                ? _scopeCollection(e.entry, maxBooks: 500)
                : _collection(e.entry, maxBooks: 500))
            .toList(),
        width: 4);
    for (final r in results) {
      r['libraryId'] = libId;
    }
    return {'results': results, 'total': all.length, 'limit': limit, 'page': page};
  }

  Future<http.Response?> _routeCollections(String method, List<String> s, Map<String, dynamic> body) async {
    final n = s.length;
    String at(int i) => i < n ? s[i] : '';
    if (n == 2 && method == 'POST') {
      final created = await _boPost('/collections', {
        'name': body['name'] ?? 'Collection',
        'icon': 'pi pi-book',
        if ((body['description'] as String?)?.isNotEmpty == true) 'description': body['description'],
      }) as Map<String, dynamic>;
      final books = (body['books'] as List<dynamic>? ?? const []).map((e) => int.tryParse('$e')).whereType<int>().toList();
      if (books.isNotEmpty) await _boPost('/collections/${created['id']}/books', {'bookIds': books});
      return _json(await _collection(created)..['libraryId'] = body['libraryId'] ?? '');
    }
    final id = at(2);
    if (id.startsWith(_scopeIdPrefix)) {
      final scopeId = id.substring(_scopeIdPrefix.length);
      if (n == 3 && method == 'GET') {
        return _json(await _scopeCollection(await _boGet('/smart-scopes/$scopeId') as Map<String, dynamic>));
      }
      return _status(403, 'Smart Scopes are read-only');
    }
    if (n == 3) {
      switch (method) {
        case 'GET':
          return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));
        case 'DELETE':
          await _boDelete('/collections/$id');
          return _json(const <String, dynamic>{});
        case 'PATCH':
          final patch = <String, dynamic>{
            if (body['name'] != null) 'name': body['name'],
            if (body['description'] != null) 'description': body['description'],
          };
          if (patch.isNotEmpty) await _boPatch('/collections/$id', patch);
          final wanted = body['books'] as List<dynamic>?;
          if (wanted != null) {
            final current = await _collection(await _boGet('/collections/$id') as Map<String, dynamic>);
            final have = (current['books'] as List).map((b) => '${(b as Map)['id']}').toList();
            final want = wanted.map((e) => '$e').where((e) => int.tryParse(e) != null).toList();
            if (have.join(',') != want.join(',')) {
              // BookOrbit has no reorder call and keeps books in the order
              // they were added, so the new list is added back in sequence.
              if (have.isNotEmpty) {
                await _boDelete('/collections/$id/books', body: {'bookIds': have.map(int.parse).toList()});
              }
              if (want.isNotEmpty) {
                await _boPost('/collections/$id/books', {'bookIds': want.map(int.parse).toList()});
              }
            }
          }
          return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));
      }
    }
    if (at(3) == 'book' || at(3) == 'books') {
      if (method == 'POST') {
        final bookId = int.tryParse('${body['id']}');
        if (bookId == null) return _status(400, 'Missing book id');
        await _boPost('/collections/$id/books', {'bookIds': [bookId]});
      } else if (method == 'DELETE' && n == 5) {
        final bookId = int.tryParse(at(4));
        if (bookId == null) return _status(400, 'Bad book id');
        await _boDelete('/collections/$id/books', body: {'bookIds': [bookId]});
      } else {
        return null;
      }
      return _json(await _collection(await _boGet('/collections/$id') as Map<String, dynamic>));
    }
    return null;
  }

  /// With [coverSlot] the URL shows that slot only (no fallback to the other
  /// one), which is what the cover editor wants.
  @override
  String getCoverUrl(String itemId, {int? width = 400, int? updatedAt, String? coverSlot}) {
    if (ApiService.isBookDockItem(itemId)) return _dockCoverUrl(_dockFileId(itemId));
    final kind = coverSlot == null && width != null && width <= 400 ? 'thumbnail' : 'cover';
    final cv = _coverVersions[_key(itemId)];
    final t = cv == null ? '' : '&t=${Uri.encodeQueryComponent(cv)}';
    final slot = coverSlot == null ? _listCoverSlot(itemId) : '$coverSlot&strict=true';
    return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/$itemId/$kind?medium=$slot$t');
  }

  @override
  Future<List<Map<String, dynamic>>?> ebookBookmarks(String itemId) async {
    try {
      final list = await _boGet('/books/$itemId/bookmarks') as List<dynamic>;
      return [
        for (final b in list.whereType<Map<String, dynamic>>())
          if (b['cfi'] is String && (b['cfi'] as String).isNotEmpty)
            {'id': '${b['id']}', 'cfi': b['cfi'], 'title': b['title'], 'note': b['note']},
      ];
    } catch (e) {
      debugPrint('[BookOrbit] ebook bookmarks for $itemId: $e');
      return null;
    }
  }

  @override
  Future<String?> addEbookBookmark(String itemId, {required String cfi, required String title}) async {
    try {
      final created = await _boPost('/books/$itemId/bookmarks', {'cfi': cfi, 'title': title}) as Map<String, dynamic>;
      return created['id'] == null ? null : '${created['id']}';
    } catch (e) {
      debugPrint('[BookOrbit] add ebook bookmark for $itemId: $e');
      return null;
    }
  }

  @override
  bool get keepsEbookHighlights => true;

  @override
  Future<List<Map<String, dynamic>>?> ebookHighlights(String itemId, {String? fileId}) async {
    try {
      // Older servers refuse a query they don't know.
      final reader = fileId != null && int.tryParse(fileId) != null && (await _features()).contains('reader-file-positions');
      final list = await _boGet('/books/$itemId/annotations', reader ? {'readerFileId': fileId} : null) as List<dynamic>;
      return [
        for (final a in list.whereType<Map<String, dynamic>>())
          {
            'id': '${a['id']}',
            'cfi': a['cfi'],
            'fileId': a['jumpFileId'] == null ? null : '${a['jumpFileId']}',
            'text': a['text'],
            'color': a['color'],
            'note': a['note'],
            'chapter': a['chapterTitle'],
            'at': a['highlightedAt'] ?? a['createdAt'],
          },
      ];
    } catch (e) {
      debugPrint('[BookOrbit] highlights for $itemId: $e');
      return null;
    }
  }

  @override
  Future<String?> addEbookHighlight(String itemId, String fileId,
      {required String cfi, required String text, required String color, String? note, String? chapter}) async {
    try {
      final created = await _boPost('/books/$itemId/annotations', {
        'cfi': cfi,
        if (int.tryParse(fileId) != null) 'bookFileId': int.parse(fileId),
        'text': text,
        'color': color,
        'style': 'highlight',
        if (note != null && note.isNotEmpty) 'note': note,
        if (chapter != null && chapter.isNotEmpty)
          'chapterTitle': chapter.length > 500 ? chapter.substring(0, 500) : chapter,
        ...await _clientName(),
      }) as Map<String, dynamic>;
      return created['id'] == null ? null : '${created['id']}';
    } catch (e) {
      debugPrint('[BookOrbit] add highlight for $itemId: $e');
      return null;
    }
  }

  @override
  Future<bool> updateEbookHighlight(String itemId, String highlightId, {required String color, String? note}) async {
    try {
      await _boPatch('/books/$itemId/annotations/$highlightId', {'color': color, 'note': note});
      return true;
    } on _BoHttpError catch (e) {
      return e.status == 404;
    } catch (e) {
      debugPrint('[BookOrbit] update highlight $highlightId: $e');
      return false;
    }
  }

  @override
  Future<bool> deleteEbookHighlight(String itemId, String highlightId) async {
    try {
      await _boDelete('/books/$itemId/annotations/$highlightId');
      return true;
    } on _BoHttpError catch (e) {
      return e.status == 404;
    } catch (e) {
      debugPrint('[BookOrbit] delete highlight $highlightId: $e');
      return false;
    }
  }

  @override
  Future<bool> deleteEbookBookmark(String itemId, String bookmarkId) async {
    try {
      await _boDelete('/books/$itemId/bookmarks/$bookmarkId');
      return true;
    } on _BoHttpError catch (e) {
      return e.status == 404;
    } catch (e) {
      debugPrint('[BookOrbit] delete ebook bookmark $bookmarkId: $e');
      return false;
    }
  }

  @override
  Future<int?> comicPageCount(String fileId) async {
    try {
      final r = await _boGet('/cbz/files/$fileId/pages') as Map<String, dynamic>;
      return (r['pageCount'] as num?)?.toInt();
    } catch (e) {
      debugPrint('[BookOrbit] comic page count for file $fileId: $e');
      return null;
    }
  }

  @override
  String? comicPageUrl(String fileId, int index) =>
      BookOrbitMediaProxy.instance.urlFor('/api/v1/cbz/files/$fileId/pages/$index');

  @override
  Future<List<String>> coverSlots(String itemId) async {
    try {
      final d = await _detail(itemId);
      return (d['coverMedia'] as List<dynamic>? ?? const [])
          .map((e) => '$e')
          .where((e) => e == 'audio' || e == 'ebook')
          .toList();
    } catch (e) {
      debugPrint('[BookOrbit] cover slots for $itemId: $e');
      return const [];
    }
  }

  @override
  Future<String?> defaultCoverSearchProvider() async {
    try {
      final p = await _boGet('/user-preferences/cover-search') as Map<String, dynamic>;
      return ((p['settings'] as Map?)?['defaultProvider'] ?? p['defaultProvider']) as String?;
    } catch (_) {
      return null;
    }
  }

  @override
  String getAuthorImageUrl(String authorId, {int width = 200, int? updatedAt}) {
    final id = int.tryParse(authorId) ?? 0;
    final kind = width <= 400 ? 'thumbnail' : 'image';
    final t = updatedAt == null ? '' : '?t=$updatedAt';
    return BookOrbitMediaProxy.instance.urlFor('/api/v1/authors/$id/$kind$t');
  }

  /// The cover slot an edit goes to: the audiobook's when there is audio,
  /// since that is the one the app shows.
  Future<String> _coverMedium(String bookId) async =>
      _detailHasAudio(await _detail(bookId)) ? 'audio' : 'ebook';

  /// Re-read a book after an edit and tell open views about it the way the
  /// Audiobookshelf socket would.
  Future<Map<String, dynamic>> _afterEdit(String bookId, {bool chaptersChanged = false}) async {
    final k = _key(bookId);
    if (chaptersChanged) {
      _manifests.remove(k);
      _manifestAt.remove(k);
    }
    _recent.removeWhere((key, _) => key.startsWith('personalized:'));
    final detail = await _detail(bookId, fresh: true);
    final manifest = _detailHasAudio(detail) ? await _manifest(bookId) : null;
    final item = BookOrbitMapper.item(detail: detail, manifest: manifest);
    SocketService().emitLocalItemUpdated(item);
    return item;
  }

  Future<Map<String, dynamic>> _updateMedia(String bookId, Map<String, dynamic> body) async {
    final detail = await _detail(bookId, fresh: true);
    final current = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;
    final changes = BookOrbitMapper.metadataPatch(
      metadata: (body['metadata'] as Map?)?.cast<String, dynamic>() ?? const {},
      tags: (body['tags'] as List<dynamic>?)?.map((e) => '$e').toList(),
      current: current,
      hasAudio: _detailHasAudio(detail),
    );
    if (changes.isEmpty) return {'updated': false, 'libraryItem': await _afterEdit(bookId)};
    await _boPatch('/books/$bookId/metadata', changes);
    return {'updated': true, 'libraryItem': await _afterEdit(bookId)};
  }

  // Book Dock: BookOrbit's import inbox, shown as one more library.

  /// The cover URL picked for each dock file, by file id, from the last read.
  final Map<String, String> _dockCovers = {};

  String _dockFileId(String itemId) =>
      itemId.substring(BookOrbitMapper.dockItemPrefix.length);

  Future<Map<String, dynamic>?> _dockLibrary() async {
    if (!await _can('book_dock_access')) return null;
    return {
      'id': ApiService.bookDockLibraryId,
      'name': 'Book Dock',
      'displayOrder': 1 << 20,
      'icon': 'database',
      'mediaType': 'book',
      'provider': 'audible',
      'folders': const [],
      'settings': {'coverAspectRatio': 0},
      'bookDock': true,
    };
  }

  void _rememberDockFile(Map<String, dynamic> file) {
    final cover = BookOrbitMapper.dockMetadata(file)['coverUrl'];
    final id = '${file['id']}';
    if (cover is String && cover.startsWith('http')) {
      _dockCovers[id] = cover;
    } else {
      _dockCovers.remove(id);
    }
  }

  Future<Map<String, dynamic>> _dockFile(String fileId) async {
    final file = await _boGet('/book-dock/files/$fileId') as Map<String, dynamic>;
    _rememberDockFile(file);
    return file;
  }

  /// A picked cover shows through BookOrbit's image proxy like on the web,
  /// which needs edit rights; otherwise the cover read from the file.
  String _dockCoverUrl(String fileId) {
    final picked = _dockCovers[fileId];
    if (picked != null && _hasPermission('library_edit_metadata')) {
      return BookOrbitMediaProxy.instance
          .urlFor('/api/v1/books/cover/proxy?url=${Uri.encodeQueryComponent(picked)}');
    }
    return BookOrbitMediaProxy.instance.urlFor('/api/v1/book-dock/files/$fileId/cover');
  }

  Future<Map<String, dynamic>> _dockItems(Map<String, String> q, {String? search}) async {
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final limit = (int.tryParse(q['limit'] ?? '') ?? 20).clamp(1, 100);
    final desc = q['desc'] == '1';
    final sort = switch (q['sort']) {
      'media.metadata.title' || 'media.metadata.titleIgnorePrefix' => 'fileName',
      'size' => 'fileSize',
      _ => 'createdAt',
    };
    final res = await _boGet('/book-dock/files', {
      'page': page + 1,
      'limit': limit,
      'sort': sort,
      'order': desc ? 'desc' : 'asc',
      if (search != null && search.trim().isNotEmpty) 'search': search.trim(),
    }) as Map<String, dynamic>;
    final items = <Map<String, dynamic>>[];
    for (final f in (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      _rememberDockFile(f);
      items.add(BookOrbitMapper.dockItem(f));
    }
    return {
      'results': items,
      'total': res['total'] ?? items.length,
      'limit': limit,
      'page': page,
      'sortBy': q['sort'],
      'sortDesc': desc,
      'filterBy': q['filter'],
      'mediaType': 'book',
      'minified': q['minified'] != '0',
      'collapseseries': false,
      'include': '',
    };
  }

  /// The dock library answers the library routes Absorb calls; the ones
  /// with nothing behind them (series, authors, ...) answer empty.
  Future<http.Response?> _routeDockLibrary(int n, String sub, Map<String, String> q) async {
    final dock = await _dockLibrary();
    if (dock == null) return _status(404, 'Book Dock is not available');
    final emptyFilterData = <String, dynamic>{
      'authors': const [],
      'series': const [],
      'genres': const [],
      'tags': const [],
      'narrators': const [],
      'languages': const [],
      'publishers': const [],
      'publishedDecades': const [],
    };
    if (n == 3) {
      return _json({
        ...dock,
        if ((q['include'] ?? '').contains('filterdata')) 'filterdata': emptyFilterData,
      });
    }
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final limit = int.tryParse(q['limit'] ?? '') ?? 20;
    switch (sub) {
      case 'items':
        return _json(await _dockItems(q));
      case 'personalized':
        final recent = await _dockItems({'page': '0', 'limit': '20', 'desc': '1'});
        final entities = recent['results'] as List<dynamic>;
        return _json([
          if (entities.isNotEmpty)
            {
              'id': 'recently-added',
              'label': 'Recently Added',
              'labelStringKey': 'LabelRecentlyAdded',
              'type': 'book',
              'entities': entities,
              'total': entities.length,
            },
        ]);
      case 'search':
        final text = q['q'] ?? '';
        final found = text.trim().isEmpty
            ? const <dynamic>[]
            : (await _dockItems({'limit': '${(int.tryParse(q['limit'] ?? '') ?? 25).clamp(1, 100)}'},
                    search: text))['results'] as List<dynamic>;
        return _json({
          'book': [
            for (final item in found)
              {
                'libraryItem': item,
                'matchKey': 'title',
                'matchText': (((item as Map)['media'] as Map)['metadata'] as Map)['title'],
              },
          ],
          'podcast': const [],
          'series': const [],
          'authors': const [],
          'narrators': const [],
          'tags': const [],
          'genres': const [],
        });
      case 'filterdata':
        return _json(emptyFilterData);
      case 'series':
      case 'collections':
      case 'playlists':
        return _json({'results': const [], 'total': 0, 'limit': limit, 'page': page});
      case 'authors':
        return _json(q.containsKey('page')
            ? {'results': const [], 'total': 0, 'limit': limit, 'page': page}
            : {'authors': const []});
      case 'narrators':
        return _json({'narrators': const []});
      case 'stats':
        final summary = await _boGet('/book-dock/summary') as Map<String, dynamic>;
        return _json({
          'totalItems': summary['total'] ?? 0,
          'totalSize': 0,
          'totalDuration': 0,
          'numAudioFiles': 0,
          'numAudioTracks': 0,
          'totalAuthors': 0,
          'totalGenres': 0,
        });
    }
    return null;
  }

  /// Item routes for a dock file: read, edit, pick a cover, apply what the
  /// server found online, and discard. Anything else (play, chapters, ...)
  /// waits until the file is in a library.
  Future<http.Response?> _routeDockItem(
    String method,
    String itemId,
    String sub,
    int n,
    Map<String, dynamic> body,
  ) async {
    final fileId = _dockFileId(itemId);
    if (int.tryParse(fileId) == null) return _status(404, 'Book Dock file not found');
    if (n == 3 && method == 'GET') return _json(BookOrbitMapper.dockItem(await _dockFile(fileId)));
    if (n == 3 && method == 'DELETE') {
      final ok = await removeBookDockItem(itemId);
      return ok ? _json({'success': true}) : _status(500, 'Could not remove the file');
    }
    if (n == 4 && sub == 'media' && method == 'PATCH') {
      final file = await _dockFile(fileId);
      final next = BookOrbitMapper.dockMetadataPatch(
        BookOrbitMapper.dockMetadata(file),
        (body['metadata'] as Map?)?.cast<String, dynamic>() ?? const {},
      );
      return _json({'updated': true, 'libraryItem': await _saveDockMetadata(fileId, next)});
    }
    if (n == 4 && sub == 'cover' && method == 'POST') {
      final url = _upstreamImageUrl('${body['url'] ?? ''}');
      if (!url.startsWith('http')) return _status(400, 'No cover URL');
      final file = await _dockFile(fileId);
      await _saveDockMetadata(fileId, BookOrbitMapper.dockMetadata(file)..['coverUrl'] = url);
      return _json({'success': true});
    }
    if (n == 4 && sub == 'match' && method == 'POST') {
      final updated = await useFoundBookDockDetails(itemId);
      return _json({
        'updated': updated,
        'libraryItem': BookOrbitMapper.dockItem(await _dockFile(fileId)),
      });
    }
    return _status(409, 'This file is still in the Book Dock');
  }

  Future<Map<String, dynamic>> _saveDockMetadata(String fileId, Map<String, dynamic> metadata) async {
    final file = await _boPatch('/book-dock/files/$fileId', {'selectedMetadata': metadata})
        as Map<String, dynamic>;
    _rememberDockFile(file);
    final item = BookOrbitMapper.dockItem(file);
    SocketService().emitLocalItemUpdated(item);
    return item;
  }

  void _afterDockGone(String itemId) {
    _dockCovers.remove(_dockFileId(itemId));
    _recent.removeWhere((key, _) => key.startsWith('personalized:'));
    SocketService().emitLocalItemRemoved({'id': itemId, 'libraryId': ApiService.bookDockLibraryId});
  }

  @override
  Future<List<BookDockDestination>> bookDockDestinations() async {
    try {
      final caps = await _boGet('/uploads/capabilities') as Map<String, dynamic>;
      if (caps['canUploadToLibrary'] != true) return const [];
      final out = <BookDockDestination>[];
      for (final lib in (caps['libraries'] as List<dynamic>? ?? const []).whereType<Map>()) {
        for (final folder in (lib['folders'] as List<dynamic>? ?? const []).whereType<Map>()) {
          out.add(BookDockDestination(
            libraryId: '${lib['id']}',
            libraryName: '${lib['name'] ?? ''}',
            folderId: '${folder['id']}',
            folderName: '${folder['name'] ?? ''}',
          ));
        }
      }
      return out;
    } catch (e) {
      debugPrint('[BookOrbit] Book Dock destinations: $e');
      return const [];
    }
  }

  @override
  Future<BookDockFileResult> fileBookDockItem(String itemId, BookDockDestination destination) async {
    final fileId = int.tryParse(_dockFileId(itemId));
    final libraryId = int.tryParse(destination.libraryId);
    final folderId = int.tryParse(destination.folderId);
    if (fileId == null || libraryId == null || folderId == null) {
      return const BookDockFileResult(success: false);
    }
    try {
      // As an override: a file's own target would beat a default.
      final res = await _boPost('/book-dock/finalize', {
        'fileIds': [fileId],
        'overrides': [
          {'fileId': fileId, 'libraryId': libraryId, 'folderId': folderId},
        ],
      }, const Duration(minutes: 2)) as Map<String, dynamic>;
      Map? result;
      for (final r in (res['results'] as List<dynamic>? ?? const []).whereType<Map>()) {
        if (r['fileId'] == fileId) result = r;
      }
      final ok = result?['success'] == true;
      debugPrint('[BookOrbit] Book Dock file $fileId -> library $libraryId: '
          '${ok ? 'filed as book ${result?['bookId']}' : 'not filed (${result?['message']})'}');
      if (ok) {
        _afterDockGone(itemId);
        _recent.clear();
      }
      return BookDockFileResult(
        success: ok,
        duplicate: result?['isDuplicate'] == true,
        message: result?['message'] as String?,
      );
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] Book Dock finalize $fileId: ${e.status} ${e.message}');
      return BookDockFileResult(success: false, message: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] Book Dock finalize $fileId: $e');
      return const BookDockFileResult(success: false);
    }
  }

  @override
  Future<bool> removeBookDockItem(String itemId) async {
    try {
      await _boDelete('/book-dock/files/${_dockFileId(itemId)}');
      _afterDockGone(itemId);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Book Dock discard $itemId: $e');
      return false;
    }
  }

  @override
  Future<bool> lookUpBookDockDetails(String itemId) async {
    try {
      await _boPost('/book-dock/files/${_dockFileId(itemId)}/refetch-metadata', const <String, dynamic>{});
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Book Dock look up again $itemId: $e');
      return false;
    }
  }

  @override
  Future<bool> useFoundBookDockDetails(String itemId) async {
    try {
      final fileId = _dockFileId(itemId);
      final file = await _dockFile(fileId);
      final found = file['fetchedMetadata'];
      if (found is! Map || found.isEmpty) return false;
      await _saveDockMetadata(
        fileId,
        BookOrbitMapper.dockMergeFound(
          BookOrbitMapper.dockMetadata(file),
          Map<String, dynamic>.from(found),
        ),
      );
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Book Dock use found details $itemId: $e');
      return false;
    }
  }

  /// Covers picked from a search come back through the proxy; BookOrbit
  /// wants the original address.
  String _upstreamImageUrl(String url) {
    final picked = _coverPicks[url];
    if (picked != null) return picked;
    if (!BookOrbitMediaProxy.instance.owns(url)) return url;
    final uri = Uri.parse(url);
    return uri.path.endsWith('/books/cover/proxy') ? (uri.queryParameters['url'] ?? url) : url;
  }

  Future<http.Response> _coverFromUrl(String bookId, String url, {String? slot}) async {
    if (url.isEmpty) return _status(400, 'No cover URL');
    await _boPost(
      '/books/$bookId/cover/from-url?medium=${slot ?? await _coverMedium(bookId)}',
      {'url': _upstreamImageUrl(url)},
      const Duration(seconds: 45),
    );
    await _afterEdit(bookId);
    return _json({'success': true});
  }

  @override
  Future<bool> updateItemCoverUrl(String itemId, String url, {String? coverSlot}) async {
    try {
      if (ApiService.isBookDockItem(itemId)) {
        final res = await _routeDockItem('POST', itemId, 'cover', 4, {'url': url});
        return res?.statusCode == 200;
      }
      return (await _coverFromUrl(itemId, url, slot: coverSlot)).statusCode == 200;
    } catch (e) {
      debugPrint('[BookOrbit] updateItemCoverUrl error: $e');
      return false;
    }
  }

  @override
  Future<bool> removeItemCover(String itemId, {String? coverSlot}) async {
    // A dock file's cover comes from the file or a picked URL; it is set at
    // filing time, so there is nothing to remove yet.
    if (ApiService.isBookDockItem(itemId)) return false;
    try {
      await _boDelete('/books/$itemId/cover?medium=${coverSlot ?? await _coverMedium(itemId)}');
      await _afterEdit(itemId);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] removeItemCover error: $e');
      return false;
    }
  }

  @override
  Future<bool> uploadItemCover(String itemId, String filePath, {String? coverSlot}) async {
    if (ApiService.isBookDockItem(itemId)) return false;
    try {
      final bytes = await (await http.MultipartFile.fromPath('file', filePath)).finalize().toBytes();
      await _boMultipart(
        '/books/$itemId/cover?medium=${coverSlot ?? await _coverMedium(itemId)}',
        bytes,
        filename: filePath.split(RegExp(r'[\\/]')).last,
        contentType: _imageType(filePath, null),
      );
      await _afterEdit(itemId);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] uploadItemCover error: $e');
      return false;
    }
  }

  static String _imageType(String name, String? header) {
    final h = header?.split(';').first.trim().toLowerCase();
    if (h != null && h.startsWith('image/')) return h;
    final ext = name.toLowerCase().split('?').first.split('.').last;
    return switch (ext) {
      'png' => 'image/png',
      'webp' => 'image/webp',
      'gif' => 'image/gif',
      'heic' => 'image/heic',
      'avif' => 'image/avif',
      _ => 'image/jpeg',
    };
  }

  /// POST one image as multipart. The body is built here because the http
  /// package can't label a part's type without another dependency, and
  /// BookOrbit turns away anything not marked image/*.
  Future<dynamic> _boMultipart(String path, List<int> bytes,
      {required String filename, required String contentType}) async {
    await _ensureFreshAccessToken();
    final boundary = 'absorb${DateTime.now().microsecondsSinceEpoch}';
    final safeName = filename.replaceAll('"', '');
    final body = <int>[
      ...utf8.encode('--$boundary\r\n'
          'Content-Disposition: form-data; name="file"; filename="$safeName"\r\n'
          'Content-Type: $contentType\r\n\r\n'),
      ...bytes,
      ...utf8.encode('\r\n--$boundary--\r\n'),
    ];
    Future<http.Response> send() async {
      final req = http.Request('POST', _boUri(path))
        ..headers.addAll(_headers)
        ..headers['Content-Type'] = 'multipart/form-data; boundary=$boundary'
        ..bodyBytes = body;
      final client = _httpClient ?? http.Client();
      try {
        final streamed = await client.send(req).timeout(const Duration(seconds: 60));
        return await http.Response.fromStream(streamed).timeout(const Duration(seconds: 60));
      } finally {
        if (_httpClient == null) client.close();
      }
    }

    var r = await send();
    if (r.statusCode == 401) {
      final outcome = await _refreshAccessToken();
      if (outcome == _RefreshOutcome.refreshed) r = await send();
      if (outcome == _RefreshOutcome.rejected) onAuthExpired?.call();
    }
    return _decode(r);
  }

  /// BookOrbit's own one-tap match: it searches with what the book already
  /// has and fills fields by the server's metadata rules, so the title,
  /// author and provider the app sends have nothing to steer.
  Future<Map<String, dynamic>> _quickMatch(String bookId) async {
    String fingerprint(Map<String, dynamic> d) => jsonEncode([
          BookOrbitMapper.item(detail: d)['media'],
          d['coverVersion'],
        ]);
    final before = fingerprint(await _detail(bookId, fresh: true));
    await _boPost('/books/$bookId/refresh-metadata', null, const Duration(seconds: 120));
    final item = await _afterEdit(bookId, chaptersChanged: true);
    final after = fingerprint(_details[_key(bookId)]!);
    return {'updated': before != after, 'libraryItem': item};
  }

  /// [_quickMatch] for many books in one request. BookOrbit streams one event
  /// per book as it goes; [onProgress] hears how many are done. With
  /// [ignoreCache] every provider is asked again instead of reusing saved
  /// answers.
  Future<({int matched, int failed})> quickMatchBooks(
    List<String> itemIds, {
    bool ignoreCache = false,
    void Function(int done, int total)? onProgress,
  }) async {
    final ids = itemIds.map(int.tryParse).whereType<int>().toList();
    if (ids.isEmpty) return (matched: 0, failed: itemIds.length);
    await _ensureFreshAccessToken();
    final request = http.Request('POST', _boUri('/books/bulk-refresh-metadata'))
      ..headers.addAll({..._headers, 'Accept': 'text/event-stream'})
      ..body = jsonEncode({'bookIds': ids, if (ignoreCache) 'ignoreCache': true});
    final client = _httpClient ?? http.Client();
    var done = 0;
    var matched = 0;
    try {
      final response = await client.send(request).timeout(const Duration(seconds: 30));
      if (response.statusCode != 200) {
        final e = _BoHttpError(response.statusCode, await response.stream.bytesToString());
        throw BookOrbitAdminError(e.status, e.serverMessage, e.serverCode);
      }
      // A stream that goes quiet this long has stalled; what finished is kept.
      final lines = response.stream
          .transform(utf8.decoder)
          .transform(const LineSplitter())
          .timeout(const Duration(minutes: 3));
      await for (final line in lines) {
        if (!line.startsWith('data:')) continue;
        final Object? event;
        try {
          event = jsonDecode(line.substring(5).trim());
        } catch (_) {
          continue;
        }
        if (event is! Map) continue;
        if (event['done'] == true) {
          matched = (event['processed'] as num?)?.toInt() ?? matched;
          break;
        }
        final bookId = event['bookId'];
        if (bookId == null) continue;
        done++;
        final detail = event['detail'];
        if (event['success'] != false && detail is Map<String, dynamic>) {
          matched++;
          final k = _key('$bookId');
          _keepDetail(k, detail);
          _manifests.remove(k);
          _manifestAt.remove(k);
          SocketService().emitLocalItemUpdated(BookOrbitMapper.item(detail: detail));
        }
        onProgress?.call(done, ids.length);
      }
    } on TimeoutException {
      debugPrint('[BookOrbit] Quick match stream stalled after $done of ${ids.length}');
    } finally {
      if (_httpClient == null) client.close();
    }
    _recent.removeWhere((key, _) => key.startsWith('personalized:'));
    // Books the server never reported on count as not matched.
    return (matched: matched, failed: itemIds.length - matched);
  }

  Future<http.Response> _deleteBooks(List<String> ids, {required bool hard}) async {
    // BookOrbit has no way to drop a book and keep its files.
    if (!hard) return _status(400, 'BookOrbit always deletes the files');
    final bookIds = ids.map(int.tryParse).whereType<int>().toList();
    if (bookIds.isEmpty || bookIds.length != ids.length) return _status(404, 'Book not found');
    await _boDelete('/books', body: {'bookIds': bookIds});
    for (final id in ids) {
      final k = _key(id);
      _details.remove(k);
      _detailAt.remove(k);
      _manifests.remove(k);
      _manifestAt.remove(k);
      SocketService().emitLocalItemRemoved({'id': id});
    }
    _recent.removeWhere((key, _) => key.startsWith('personalized:'));
    return _json({'success': true});
  }

  Future<http.Response> _deleteFile(String bookId, String fileId) async {
    final id = int.tryParse(fileId);
    if (id == null) return _status(404, 'File not found');
    await _boDelete('/books/files/$id');
    debugPrint('[BookOrbit] Deleted file $id of $bookId');
    if (_narrations[_key(bookId)]?.fileId == id) _narrations.remove(_key(bookId));
    if (_readAlongTimings[_key(bookId)]?.fileId == id) _readAlongTimings.remove(_key(bookId));
    // The file is gone either way; a book that couldn't be read back after
    // still shows its old files until the next refresh.
    try {
      await _afterEdit(bookId, chaptersChanged: true);
    } catch (e) {
      debugPrint('[BookOrbit] $bookId not refreshed after deleting file $id: $e');
    }
    return _json({'success': true});
  }

  /// Sends only what changed: a new name makes BookOrbit look the author up
  /// again in the background.
  Future<Map<String, dynamic>> _updateAuthor(String authorId, Map<String, dynamic> body) async {
    final current = await _boGet('/authors/$authorId') as Map<String, dynamic>;
    final changes = <String, dynamic>{};
    final name = '${body['name'] ?? ''}'.trim();
    if (name.isNotEmpty && name != current['name']) {
      changes['name'] = name.length > 500 ? name.substring(0, 500) : name;
    }
    if (body.containsKey('description')) {
      final d = '${body['description'] ?? ''}'.trim();
      final next = d.isEmpty ? null : (d.length > 10000 ? d.substring(0, 10000) : d);
      if (next != current['description']) changes['description'] = next;
    }
    final res = changes.isEmpty ? current : await _boPatch('/authors/$authorId', changes);
    return {'author': BookOrbitMapper.author(res as Map<String, dynamic>)};
  }

  /// BookOrbit only takes an uploaded author image, so fetch it here first.
  Future<http.Response> _authorImageFromUrl(String authorId, String url) async {
    final uri = Uri.tryParse(url.trim());
    if (uri == null || !(uri.scheme == 'http' || uri.scheme == 'https')) {
      return _status(400, 'Not an image URL');
    }
    final res = await http.get(uri).timeout(const Duration(seconds: 30));
    final type = res.headers['content-type'];
    if (res.statusCode != 200 || res.bodyBytes.isEmpty || (type != null && !type.startsWith('image/'))) {
      return _status(400, 'Could not download the image');
    }
    await _boMultipart(
      '/authors/$authorId/image',
      res.bodyBytes,
      filename: uri.pathSegments.isEmpty ? 'author.jpg' : uri.pathSegments.last,
      contentType: _imageType(uri.path, type),
    );
    return _json({'success': true});
  }

  /// Like Quick Match for books: the server looks the author up with its
  /// own provider settings.
  Future<Map<String, dynamic>> _matchAuthor(String authorId) async {
    final before = await _boGet('/authors/$authorId') as Map<String, dynamic>;
    final after = await _boPost('/authors/$authorId/enrichment/refresh', null, const Duration(seconds: 60))
        as Map<String, dynamic>;
    String key(Map<String, dynamic> a) => jsonEncode([a['name'], a['description'], a['imageUrl']]);
    return {'updated': key(before) != key(after), 'author': BookOrbitMapper.author(after)};
  }

  static const _coverProviders = {
    'audiobookcovers': 'audiobookcovers',
    'itunes': 'itunes',
    'duckduckgo': 'duckduckgo',
    'google': 'duckduckgo',
    'all': 'all',
  };

  Future<List<String>> _searchCovers(Map<String, String> q) => _searchCoverUrls(
        title: q['title'] ?? '',
        author: q['author'],
        provider: q['provider'] ?? 'all',
        audiobook: q['isAudiobook'] != 'false',
      );

  @override
  Future<List<String>> searchCovers(String title,
      {String? author, String provider = 'google', String? coverSlot}) async {
    try {
      return await _searchCoverUrls(
        title: title,
        author: author,
        provider: provider,
        audiobook: coverSlot != 'ebook',
      );
    } catch (e) {
      debugPrint('[BookOrbit] cover search failed: $e');
      return const [];
    }
  }

  /// Display URL of a cover search result -> the full-size image to set.
  static final Map<String, String> _coverPicks = {};

  /// Cover search the way BookOrbit's web editor does it: [audiobook] says
  /// which slot it is for, which changes what each source looks for, and
  /// results show through BookOrbit's image proxy like on the web.
  Future<List<String>> _searchCoverUrls({
    required String title,
    String? author,
    required String provider,
    required bool audiobook,
  }) async {
    final source = _coverProviders[provider];
    final t = title.trim();
    if (source == null || t.isEmpty || (source == 'audiobookcovers' && !audiobook)) return const [];
    final a = (author ?? '').trim();
    final res = await _boGet('/books/cover/search', {
      'title': t,
      if (a.isNotEmpty) 'author': a,
      'isAudiobook': '$audiobook',
      'provider': source,
    }, const Duration(seconds: 30));
    if (_coverPicks.length > 500) _coverPicks.clear();
    final urls = <String>[];
    for (final r in (res as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      final full = '${r['url'] ?? ''}';
      final preview = r['previewUrl'];
      if (preview is String && preview.startsWith('/')) {
        final shown = BookOrbitMediaProxy.instance.urlFor(preview);
        if (full.startsWith('http')) _coverPicks[shown] = full;
        urls.add(shown);
      } else if (full.startsWith('http')) {
        urls.add(full);
      }
    }
    return urls;
  }

  /// Audiobookshelf finds a book's Audible match through its own server.
  /// BookOrbit only searches Audible when its admin turned that provider on,
  /// so ask Audible's catalog directly, as the rating lookup by ASIN does.
  @override
  Future<Map<String, dynamic>?> searchAudibleRating(String title, String? author) async {
    final wanted = _plainTitle(title);
    if (wanted.isEmpty) return null;
    final firstAuthor = (author ?? '').split(',').first.trim();
    try {
      final uri = Uri.parse('https://api.audible${ApiService._audibleTld}/1.0/catalog/products').replace(
        queryParameters: {
          'title': title.trim(),
          if (firstAuthor.isNotEmpty) 'author': firstAuthor,
          'num_results': '5',
          'products_sort_by': 'Relevance',
          'response_groups': 'product_desc,rating',
        },
      );
      final r = await http.get(uri).timeout(const Duration(seconds: 10));
      if (r.statusCode != 200) return null;
      final products = ((jsonDecode(r.body) as Map<String, dynamic>)['products'] as List<dynamic>? ?? const [])
          .whereType<Map<String, dynamic>>();
      for (final p in products) {
        final asin = p['asin'] as String?;
        final found = _plainTitle('${p['title'] ?? ''}');
        // Same book, not just a good keyword hit.
        if (asin == null || found.isEmpty || !(found.contains(wanted) || wanted.contains(found))) continue;
        final overall = (p['rating'] as Map?)?['overall_distribution'] as Map?;
        final score = (overall?['average_rating'] as num?)?.toDouble();
        if (score == null || !score.isFinite || score <= 0 || score > 5) continue;
        final count = (overall?['num_ratings'] as num?)?.toInt();
        return {'rating': score, 'count': count != null && count >= 0 ? count : null, 'asin': asin};
      }
    } catch (e) {
      debugPrint('[BookOrbit] Audible rating search failed: $e');
    }
    return null;
  }

  static String _plainTitle(String s) =>
      s.toLowerCase().replaceAll(RegExp(r'[^\p{L}\p{N}]+', unicode: true), ' ').trim();

  @override
  Future<List<Map<String, dynamic>>> getSimilarBooks(String itemId) async {
    try {
      final res = await _boGet('/books/$itemId/recommendations') as List<dynamic>;
      return res.whereType<Map<String, dynamic>>().map(BookOrbitMapper.similarBook).toList();
    } catch (e) {
      debugPrint('[BookOrbit] No similar books for $itemId: $e');
      return const [];
    }
  }

  @override
  Future<bool> setReadStatus(String itemId, String status) async {
    try {
      await _boPatch('/books/$itemId/status', {'status': status});
      _forgetProgress(itemId);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] setReadStatus error: $e');
      return false;
    }
  }

  @override
  Future<bool> setPersonalNote(String itemId, String? note) async {
    final text = note?.trim();
    try {
      final d = await _boPatch('/books/$itemId/personal-note', {
        'note': text == null || text.isEmpty ? null : (text.length > 10000 ? text.substring(0, 10000) : text),
      }) as Map<String, dynamic>;
      _details[_key(itemId)] = d;
      _detailAt[_key(itemId)] = DateTime.now();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] setPersonalNote error: $e');
      return false;
    }
  }

  @override
  Future<List<Map<String, String>>?> bookMatchProviders() async {
    try {
      final res = await _boGet('/metadata-fetch/providers') as List<dynamic>;
      return [
        for (final p in res.whereType<Map<String, dynamic>>())
          if (p['key'] is String) {'key': p['key'] as String, 'label': '${p['label'] ?? p['key']}'},
      ];
    } catch (e) {
      debugPrint('[BookOrbit] provider list failed: $e');
      return null;
    }
  }

  @override
  Future<BookRequestAccess> bookRequestAccess() async {
    if (!await _can('book_request_access') || !_showBookRequests) return BookRequestAccess.none;
    return BookRequestAccess(
      canRequest: true,
      canManage: _hasPermission('manage_book_requests'),
      autoApprove: _hasPermission('book_request_auto_approve'),
      selfFulfill: _hasPermission('book_request_self_fulfill'),
      pairs: (await _features()).contains('book-request-pairs'),
    );
  }

  @override
  Future<({List<BookRequest> items, int total})?> bookRequests({
    bool all = false,
    int page = 1,
    int limit = 25,
    bool includeDismissed = false,
  }) async {
    try {
      final res = await _boGet(all ? '/admin/book-requests' : '/book-requests', {
        'page': '$page',
        'limit': '$limit',
        if (includeDismissed) 'includeDismissed': 'true',
      }) as Map<String, dynamic>;
      return (
        items: [
          for (final r in (res['items'] as List<dynamic>? ?? const []).whereType<Map>())
            if (r['id'] is num) BookRequest(Map<String, dynamic>.from(r)),
        ],
        total: (res['total'] as num?)?.toInt() ?? 0,
      );
    } catch (e) {
      debugPrint('[BookOrbit] book requests (all=$all page=$page): $e');
      return null;
    }
  }

  @override
  Future<List<BookRequestAvailability?>> bookRequestAvailability(
    List<MatchCandidate> records,
    String mediaKind,
  ) async {
    String? clip(String v, int max) {
      final s = v.trim();
      if (s.isEmpty) return null;
      return s.length > max ? s.substring(0, max) : s;
    }
    final out = <BookRequestAvailability?>[];
    // The server takes at most 50 a time.
    for (var start = 0; start < records.length; start += 50) {
      final batch = records.sublist(start, math.min(start + 50, records.length));
      try {
        final res = await _boPost('/book-requests/availability', {
          'items': [
            for (final c in batch)
              {
                'title': clip(c.title, 500) ?? '?',
                'mediaKind': mediaKind,
                if (c.authors.isNotEmpty) 'author': ?clip(c.authors.first, 255),
                'isbn13': ?clip(c.isbn13, 20),
                'providerKey': ?clip(c.provider, 50),
                'providerId': ?clip(c.providerId, 255),
              },
          ],
        }) as List<dynamic>;
        for (var i = 0; i < batch.length; i++) {
          out.add(i < res.length ? BookRequestAvailability.fromJson(res[i]) : null);
        }
      } catch (e) {
        debugPrint('[BookOrbit] request availability: $e');
        out.addAll([for (final _ in batch) null]);
      }
    }
    return out;
  }

  @override
  Future<BookRequestSubmitResult> submitBookRequest(Map<String, dynamic> body) async {
    try {
      return BookRequestSubmitResult.fromJson(await _boPost('/book-requests', body));
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] book request refused: ${e.status} ${e.message}');
      return BookRequestSubmitResult(error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] book request: $e');
      return const BookRequestSubmitResult();
    }
  }

  /// The format [bookId] is missing and could be asked for from the book,
  /// as BookOrbit's book page offers it. Null when this account can't make
  /// requests or hid them, the server can't file a request into a book
  /// (before 3.4), or the book has both formats or reads itself aloud.
  Future<MissingFormatRequest?> missingFormatRequest(String bookId) async {
    final access = await bookRequestAccess();
    if (!access.canRequest || !access.pairs) return null;
    final Map<String, dynamic> detail;
    try {
      detail = await _detail(bookId);
    } catch (e) {
      debugPrint('[BookOrbit] missing format for $bookId: $e');
      return null;
    }
    final kind = missingRequestFormat([
      for (final f in (detail['files'] as List<dynamic>? ?? const []).whereType<Map>()) Map<String, dynamic>.from(f),
    ]);
    if (kind == null) return null;
    final work = _requestWork(detail);
    final title = work['title'] as String?;
    if (title == null) return null;
    try {
      final authors = work['authors'] as List<String>;
      final res = await _boPost('/book-requests/availability', {
        'items': [
          {
            'title': title,
            'mediaKind': kind,
            if (authors.isNotEmpty) 'author': authors.first,
            'isbn13': ?work['isbn13'],
          },
        ],
      }) as List<dynamic>;
      return MissingFormatRequest(kind, res.isEmpty ? null : BookRequestAvailability.fromJson(res.first));
    } catch (e) {
      // The request can still be made; the answer only says who asked first.
      debugPrint('[BookOrbit] missing $kind availability for $bookId: $e');
      return MissingFormatRequest(kind);
    }
  }

  /// Asks for [mediaKind] of [bookId], aimed at the book so the new format
  /// lands beside the one there instead of as a second book.
  Future<BookRequestSubmitResult> requestMissingFormat(String bookId, String mediaKind) async {
    final id = int.tryParse(bookId);
    if (id == null) return const BookRequestSubmitResult();
    final Map<String, dynamic> detail;
    try {
      detail = await _detail(bookId);
    } catch (e) {
      debugPrint('[BookOrbit] missing format request for $bookId: $e');
      return const BookRequestSubmitResult();
    }
    final work = _requestWork(detail);
    if (work['title'] == null) return const BookRequestSubmitResult();
    debugPrint('[BookOrbit] Requesting the $mediaKind for book $bookId');
    return submitBookRequest({...work, 'mediaKind': mediaKind, 'targetBookId': id});
  }

  /// What BookOrbit's book page sends about a book when asking for its other
  /// format. Its form refuses unknown fields and caps each length.
  static Map<String, dynamic> _requestWork(Map<String, dynamic> detail) {
    String? clip(Object? v, int max) {
      final s = v is String ? v.trim() : '';
      if (s.isEmpty) return null;
      return s.length > max ? s.substring(0, max) : s;
    }

    final files = (detail['files'] as List<dynamic>? ?? const []).whereType<Map>();
    final year = (detail['publishedYear'] as num?)?.toInt();
    return {
      'title': clip(detail['title'], 500) ?? clip(files.firstOrNull?['filename'], 500),
      'authors': <String>[
        for (final a in (detail['authors'] as List<dynamic>? ?? const []).whereType<Map>().take(50))
          ?clip(a['name'], 255),
      ],
      'isbn13': ?clip(detail['isbn13'], 20),
      'isbn10': ?clip(detail['isbn10'], 20),
      'seriesName': ?clip(detail['seriesName'], 500),
      if (year != null && year >= 0 && year <= 9999) 'publishedYear': year,
      // The other format should be in the language of the one on the shelf.
      'language': ?clip(detail['language'], 20),
    };
  }

  @override
  Future<BookRequestPairResult> submitBookRequestPair(Map<String, dynamic> body) async {
    try {
      final res = await _boPost('/book-requests/pairs', body);
      if (res is! Map) return const BookRequestPairResult();
      return BookRequestPairResult(
        ebook: BookRequestSubmitResult.fromJson(res['ebook']),
        audiobook: BookRequestSubmitResult.fromJson(res['audiobook']),
      );
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] paired book request refused: ${e.status} ${e.message}');
      return BookRequestPairResult(error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] paired book request: $e');
      return const BookRequestPairResult();
    }
  }

  // Managers work any request through the admin routes; someone allowed to
  // download directly works their own through the fulfilment twins.
  Future<String> _fulfilBase() async =>
      await _can('manage_book_requests') ? '/admin/book-requests' : '/book-request-fulfilment';

  @override
  Future<({BookRequestReleases? releases, String? error})> bookRequestReleases(
    int id, {
    bool refresh = false,
    ({String title, String author, String? isbn})? terms,
  }) async {
    String? clip(String? v, int max) {
      final s = v?.trim() ?? '';
      if (s.isEmpty) return null;
      return s.length > max ? s.substring(0, max) : s;
    }
    final base = await _fulfilBase();
    // Every tracker is asked in turn, which can take most of a minute.
    const wait = Duration(minutes: 3);
    try {
      final Object? res = terms == null
          ? await _boGet('$base/$id/releases', {if (refresh) 'refresh': 'true'}, wait)
          : await _boPost('$base/$id/releases/search', {
              'title': ?clip(terms.title, 500),
              if (clip(terms.author, 255) != null) 'authors': [clip(terms.author, 255)],
              'isbn': clip(terms.isbn, 20),
            }, wait);
      if (res is! Map<String, dynamic>) return (releases: null, error: null);
      return (releases: BookRequestReleases.fromJson(res), error: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] releases for request $id: ${e.status} ${e.message}');
      return (releases: null, error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] releases for request $id: $e');
      return (releases: null, error: null);
    }
  }

  @override
  Future<({String? status, String? error})> inspectBookRequestRelease(int id, int indexerId, String guid) async {
    final base = await _fulfilBase();
    try {
      final res = await _boPost('$base/$id/releases/inspect', {
        'indexerId': indexerId,
        'releaseGuid': guid,
      }, const Duration(minutes: 1));
      return (status: res is Map ? '${res['status'] ?? ''}' : null, error: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] inspect release for request $id: ${e.status} ${e.message}');
      return (status: null, error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] inspect release for request $id: $e');
      return (status: null, error: null);
    }
  }

  @override
  Future<({BookRequest? request, String? error})> grabBookRequestRelease(int id, int indexerId, String guid) async {
    final base = await _fulfilBase();
    try {
      final res = await _boPost('$base/$id/grab', {
        'indexerId': indexerId,
        'releaseGuid': guid,
      }, const Duration(minutes: 2));
      if (res is! Map || res['id'] is! num) return (request: null, error: null);
      return (request: BookRequest(Map<String, dynamic>.from(res)), error: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] grab for request $id: ${e.status} ${e.message}');
      return (request: null, error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] grab for request $id: $e');
      return (request: null, error: null);
    }
  }

  @override
  Future<({BookRequestReview? review, String? error})> bookRequestReview(int id) async {
    final base = await _fulfilBase();
    try {
      final res = await _boGet('$base/$id/review');
      if (res is! Map<String, dynamic>) return (review: null, error: null);
      return (review: BookRequestReview.fromJson(res), error: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] review for request $id: ${e.status} ${e.message}');
      return (review: null, error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] review for request $id: $e');
      return (review: null, error: null);
    }
  }

  @override
  Future<({bool ok, BookRequest? request, String? error})> bookRequestAction(
    int id,
    BookRequestAction action, {
    String? note,
    int? libraryId,
    int? downloadId,
  }) async {
    final trimmed = note?.trim() ?? '';
    final decision = trimmed.isEmpty
        ? null
        : trimmed.length > 2000
            ? trimmed.substring(0, 2000)
            : trimmed;
    try {
      final Object? res = switch (action) {
        BookRequestAction.cancel => await _boPost('/book-requests/$id/cancel', const {}),
        BookRequestAction.dismiss => await _boPost('/book-requests/$id/dismiss', const {}),
        BookRequestAction.restore => await _boPost('/book-requests/$id/restore', const {}),
        BookRequestAction.leave => await _boDelete('/book-requests/$id/subscription'),
        BookRequestAction.approve => await _boPost('/admin/book-requests/$id/approve', {
            'decisionNote': ?decision,
            'targetLibraryId': ?libraryId,
          }),
        BookRequestAction.reject => await _boPost('/admin/book-requests/$id/reject', {
            'decisionNote': ?decision,
          }),
        BookRequestAction.delete => await _boDelete('/admin/book-requests/$id'),
        BookRequestAction.forceFile =>
          await _boPost('${await _fulfilBase()}/$id/force-file', const {}, const Duration(minutes: 2)),
        BookRequestAction.discardImport => await _boPost('${await _fulfilBase()}/$id/discard-import', const {}),
        BookRequestAction.stopDownload => downloadId == null
            ? throw ArgumentError('stopDownload needs the download id')
            : await _boPost('/book-requests/$id/downloads/$downloadId/cancel', const {}),
      };
      return (
        ok: true,
        request: res is Map && res['id'] is num ? BookRequest(Map<String, dynamic>.from(res)) : null,
        error: null,
      );
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] book request $id ${action.name}: ${e.status} ${e.message}');
      return (ok: false, request: null, error: e.serverMessage);
    } catch (e) {
      debugPrint('[BookOrbit] book request $id ${action.name}: $e');
      return (ok: false, request: null, error: null);
    }
  }

  @override
  Future<Map<String, int>> bookRequestDefaultLibraries() async {
    try {
      final res = await _boGet('/book-requests/default-destinations') as Map<String, dynamic>;
      return {
        for (final e in res.entries)
          if (e.value is Map && (e.value as Map)['libraryId'] is num)
            e.key: ((e.value as Map)['libraryId'] as num).toInt(),
      };
    } catch (e) {
      debugPrint('[BookOrbit] request default libraries: $e');
      return const {};
    }
  }

  @override
  Stream<MatchSearchEvent> searchMatches(
    String itemId, {
    String? title,
    String? author,
    String? isbn,
    bool? isAudiobook,
    String? mediaKind,
    List<String>? mediaKinds,
  }) async* {
    String? clip(String? v, int max) {
      final s = v?.trim() ?? '';
      if (s.isEmpty) return null;
      return s.length > max ? s.substring(0, max) : s;
    }
    final query = <String, dynamic>{
      'title': clip(title, 500),
      'author': clip(author, 255),
      'isbn': clip(isbn, 30),
      // A book's own id lets the server use what it already knows of it.
      if (!ApiService.isBookDockItem(itemId) && int.tryParse(itemId) != null) 'bookId': itemId,
      if (isAudiobook != null) 'isAudiobook': '$isAudiobook',
      'mediaKind': ?mediaKind,
      if (mediaKinds != null && mediaKinds.isNotEmpty) 'mediaKinds': mediaKinds.join(','),
    };
    if (query['title'] == null && query['author'] == null && query['isbn'] == null) return;
    await _ensureFreshAccessToken();
    final request = http.Request('GET', _boUri('/metadata-fetch/stream', query))
      ..headers.addAll({..._headers, 'Accept': 'text/event-stream'});
    final client = _httpClient ?? http.Client();
    try {
      final response = await client.send(request).timeout(const Duration(seconds: 30));
      if (response.statusCode != 200) {
        throw _BoHttpError(response.statusCode, await response.stream.bytesToString());
      }
      String? event;
      final data = StringBuffer();
      MatchSearchEvent? take() {
        final text = data.toString();
        final name = event;
        data.clear();
        event = null;
        if (text.isEmpty) return null;
        try {
          final decoded = jsonDecode(text);
          if (decoded is! Map<String, dynamic>) return null;
          if (name == 'provider-status') {
            return MatchSearchEvent.status('${decoded['provider']}', '${decoded['outcome']}');
          }
          if (name == null || name == 'message') return MatchSearchEvent.result(MatchCandidate(decoded));
        } catch (_) {}
        return null;
      }
      final lines = response.stream.transform(utf8.decoder).transform(const LineSplitter());
      await for (final line in lines) {
        if (line.isEmpty) {
          final e = take();
          if (e != null) yield e;
        } else if (line.startsWith('event:')) {
          event = line.substring(6).trim();
        } else if (line.startsWith('data:')) {
          if (data.isNotEmpty) data.write('\n');
          data.write(line.substring(5).trim());
        }
      }
      final last = take();
      if (last != null) yield last;
    } finally {
      if (_httpClient == null) client.close();
    }
  }

  /// The app's provider names that BookOrbit spells differently. Anything
  /// else is passed through, since the list mostly comes from the server.
  static const _bookProviders = {'openlibrary': 'openLibrary'};

  /// Provider search, which BookOrbit streams back as server-sent events,
  /// one candidate per event.
  Future<List<Map<String, dynamic>>> _searchBooks(Map<String, String> q) async {
    final asked = (q['provider'] ?? '').trim();
    final provider = _bookProviders[asked] ?? asked;
    final title = (q['title'] ?? '').trim();
    final author = (q['author'] ?? '').trim();
    if (provider.isEmpty || (title.isEmpty && author.isEmpty)) return const [];
    final r = await super._authGet(
      _boUri('/metadata-fetch/stream', {
        if (title.isNotEmpty) 'title': title.length > 500 ? title.substring(0, 500) : title,
        if (author.isNotEmpty) 'author': author.length > 255 ? author.substring(0, 255) : author,
        'providers': provider,
      }),
      timeout: const Duration(seconds: 60),
    );
    if (r.statusCode != 200) throw _BoHttpError(r.statusCode, r.body);
    final out = <Map<String, dynamic>>[];
    for (final block in utf8.decode(r.bodyBytes).split(RegExp(r'\r?\n\r?\n'))) {
      final lines = block.split(RegExp(r'\r?\n'));
      if (lines.any((l) => l.startsWith('event:'))) continue;
      final data = lines.where((l) => l.startsWith('data:')).map((l) => l.substring(5).trim()).join('\n');
      if (data.isEmpty) continue;
      try {
        final c = jsonDecode(data);
        if (c is Map<String, dynamic>) out.add(BookOrbitMapper.searchResult(c));
      } catch (_) {}
    }
    return out;
  }

  /// Chapter lookup by ASIN. BookOrbit only fetches chapters for an ASIN a
  /// book already has stored, so this asks Audnexus directly, the same
  /// source Audiobookshelf's lookup reads.
  Future<Map<String, dynamic>> _searchChapters(String asin, String region, {String? bookId}) async {
    const notFound = {'error': 'Chapters not found', 'stringKey': 'MessageChaptersNotFound'};
    final id = asin.trim();
    if (!RegExp(r'^[A-Za-z0-9]{10}$').hasMatch(id)) return notFound;
    // BookOrbit asks Audible first and Audnexus after; a server without its
    // chapter editor, or with neither reachable, leaves it to the phone.
    if (bookId != null && int.tryParse(bookId) != null) {
      final res = await lookupChapters(bookId, id, region);
      if (res.value != null) return res.value!;
      if (res.failure == BoChapterFailure.notFound && res.message != null) return notFound;
    }
    final uri = Uri.https('api.audnex.us', '/books/$id/chapters', {'region': region.toLowerCase()});
    try {
      final r = await http.get(uri).timeout(const Duration(seconds: 20));
      if (r.statusCode != 200) return notFound;
      final data = jsonDecode(r.body);
      return data is Map<String, dynamic> && data['chapters'] is List ? data : notFound;
    } catch (e) {
      debugPrint('[BookOrbit] chapter lookup failed: $e');
      return notFound;
    }
  }

  static String? _errorCode(String body) {
    try {
      final decoded = jsonDecode(body);
      return decoded is Map ? decoded['errorCode'] as String? : null;
    } catch (_) {
      return null;
    }
  }

  Future<({T? value, BoChapterFailure? failure, String? message})> _chapterCall<T>(
    String what,
    Future<dynamic> Function() call,
    T? Function(Object?) parse,
  ) async {
    try {
      final value = parse(await call());
      if (value == null) return (value: null, failure: BoChapterFailure.failed, message: null);
      return (value: value, failure: null, message: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] chapters: $what failed: $e');
      final code = _errorCode(e.body);
      return (
        value: null,
        failure: boChapterFailureFor(e.status, code),
        message: code == null ? null : e.serverMessage,
      );
    } catch (e) {
      debugPrint('[BookOrbit] chapters: $what failed: $e');
      return (value: null, failure: BoChapterFailure.failed, message: null);
    }
  }

  /// The chapter editor's view of [bookId]: the stored list, its revision and
  /// where else chapters can come from. Null on a server before 3.6.0, which
  /// keeps none of that, or when it couldn't be asked.
  Future<BoChapterState?> chapterState(String bookId) async {
    final res = await _chapterCall('state of $bookId', () => _boGet('/books/$bookId/chapters'), BoChapterState.fromJson);
    return res.value;
  }

  /// Saves the list over [baseRevision], kept in the history. [lock] keeps
  /// rescans and metadata refreshes from replacing it.
  Future<({BoChapterState? value, BoChapterFailure? failure, String? message})> saveChapters(
    String bookId,
    List<BoChapter> chapters, {
    required String baseRevision,
    bool lock = true,
  }) async {
    final res = await _chapterCall(
      'save for $bookId',
      () => _boPut('/books/$bookId/chapters', {
        'chapters': [for (final c in chapters) c.toJson()],
        'baseRevision': baseRevision,
        'lock': lock,
      }),
      BoChapterState.fromJson,
    );
    if (res.value != null) {
      debugPrint('[BookOrbit] chapters for $bookId saved: ${chapters.length}, ${lock ? 'protected' : 'not protected'}');
      await _chaptersChanged(bookId);
    }
    return res;
  }

  Future<void> _chaptersChanged(String bookId) async {
    try {
      await _afterEdit(bookId, chaptersChanged: true);
    } catch (e) {
      debugPrint('[BookOrbit] $bookId not refreshed after a chapter change: $e');
    }
  }

  Future<({Map<String, dynamic>? value, BoChapterFailure? failure, String? message})> lookupChapters(
    String bookId,
    String asin,
    String region,
  ) =>
      _chapterCall(
        'lookup $asin for $bookId',
        () => _boGet('/books/$bookId/chapters/lookup', {'asin': asin, 'region': region.toLowerCase()}),
        (raw) => raw is Map<String, dynamic> ? boLookupAsAudnexus(raw) : null,
      );

  /// Chapters named by the book's EPUB: `toc` gives titles only, `read_along`
  /// times on the read along's own narration.
  Future<({BoEbookChapters? value, BoChapterFailure? failure, String? message})> ebookChapters(
    String bookId,
    String source,
  ) =>
      _chapterCall(
        '$source chapters for $bookId',
        () => _boGet('/books/$bookId/chapters/ebook', {'source': source}),
        (raw) => raw is Map
            ? BoEbookChapters(
                BoChapter.listFrom(raw['chapters']),
                titlesOnly: raw['titlesOnly'] == true,
                runtimeMs: (raw['runtimeMs'] as num?)?.round(),
              )
            : null,
      );

  Future<({List<BoChapterVersion>? value, BoChapterFailure? failure, String? message})> chapterVersions(
    String bookId,
  ) =>
      _chapterCall(
        'history of $bookId',
        () => _boGet('/books/$bookId/chapters/versions'),
        (raw) => raw is List ? [for (final v in raw) ?BoChapterVersion.fromJson(v)] : null,
      );

  Future<({BoChapterVersion? value, BoChapterFailure? failure, String? message})> chapterVersion(
    String bookId,
    int versionId,
  ) =>
      _chapterCall(
        'version $versionId of $bookId',
        () => _boGet('/books/$bookId/chapters/versions/$versionId'),
        BoChapterVersion.fromJson,
      );

  /// Runs `write` (the saved list into the audio files), `revert` (back to
  /// the files' own chapters) or `read` (the files' chapters, nothing saved)
  /// in BookOrbit's background queue and waits for it. [onProgress] hears
  /// files done of files to do.
  Future<({BoChapterJob? value, BoChapterFailure? failure, String? message})> runChapterJob(
    String bookId,
    String kind, {
    required String baseRevision,
    void Function(int done, int total)? onProgress,
    bool Function()? stillWanted,
    Duration pollEvery = const Duration(seconds: 2),
    Duration giveUpAfter = const Duration(minutes: 20),
  }) async {
    var res = await _chapterCall(
      '$kind for $bookId',
      () => _boPost('/books/$bookId/chapters/jobs/$kind', {'baseRevision': baseRevision}),
      BoChapterJob.fromJson,
    );
    final until = DateTime.now().add(giveUpAfter);
    while (res.value != null && !res.value!.finished) {
      if (DateTime.now().isAfter(until)) {
        debugPrint('[BookOrbit] chapters: $kind for $bookId still running after ${giveUpAfter.inMinutes} minutes');
        return (value: res.value, failure: BoChapterFailure.failed, message: null);
      }
      onProgress?.call(res.value!.filesWritten, res.value!.filesTotal);
      await Future.delayed(pollEvery);
      // BookOrbit carries on without anyone watching.
      if (stillWanted != null && !stillWanted()) return res;
      final id = res.value!.id;
      res = await _chapterCall('$kind $id for $bookId', () => _boGet('/books/$bookId/chapters/jobs/$id'), BoChapterJob.fromJson);
    }
    final job = res.value;
    if (job == null) return res;
    if (!job.succeeded) {
      debugPrint('[BookOrbit] chapters: $kind for $bookId failed: ${job.errorCode}');
      return (value: job, failure: boChapterFailureFor(409, job.errorCode), message: null);
    }
    debugPrint('[BookOrbit] chapters: $kind for $bookId done (${job.filesWritten}/${job.filesTotal} files)');
    if (kind != 'read') await _chaptersChanged(bookId);
    return res;
  }

  /// Audiobookshelf-shaped content URLs (`/api/items/<book>/file/<file>`)
  /// become proxied BookOrbit asset streams.
  @override
  String buildTrackUrl(String contentUrl, {String? sessionId, int? trackIndex, int? playMethod}) {
    final uri = Uri.parse(contentUrl);
    if (BookOrbitMediaProxy.instance.owns(contentUrl) || NarrationStream.instance.owns(contentUrl)) return contentUrl;
    final seg = uri.pathSegments;
    final i = seg.indexOf('items');
    if (i >= 0 && i + 3 < seg.length && seg[i + 2] == 'file') {
      final bookId = seg[i + 1];
      final fileId = seg[i + 3];
      final asset = uri.queryParameters['asset'] ?? _assetByFile[_key(fileId)];
      if (asset != null) return _assetContentUrl(bookId, asset);
      return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$fileId/download');
    }
    if (uri.path.contains('/api/v1/')) {
      final at = uri.path.indexOf('/api/v1/');
      return BookOrbitMediaProxy.instance.urlFor(uri.path.substring(at) + (uri.hasQuery ? '?${uri.query}' : ''));
    }
    return contentUrl;
  }

  String _assetContentUrl(String bookId, String asset) {
    final v = _assetVersion[asset];
    return BookOrbitMediaProxy.instance
        .urlFor('/api/v1/audiobooks/$bookId/assets/$asset/content${v == null ? '' : '?v=$v'}');
  }

  @override
  String buildDownloadFileUrl(String itemId, String ino) {
    final ticket = _tickets[_key(itemId)];
    if (ticket != null &&
        ticket.fileIds.contains(ino) &&
        ticket.expiresAt.isAfter(DateTime.now().add(const Duration(hours: 1)))) {
      return '$_v1/watch-downloads/files/$ino';
    }
    return buildFileUrl(itemId, ino);
  }

  @override
  String buildFileUrl(String itemId, String ino) {
    final asset = _assetByFile[_key(ino)];
    if (asset != null) return _assetContentUrl(itemId, asset);
    return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/serve');
  }

  @override
  String buildEbookUrl(String itemId, String ino) =>
      BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/serve');

  /// A narrated EPUB's audio is hundreds of MB the reader never touches; the
  /// server can hand over the book without it.
  @override
  String buildReaderEbookUrl(String itemId, String ino) {
    final detail = _details[_key(itemId)];
    if (detail != null) {
      final media = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;
      if ('${(media['narration'] as Map?)?['fileId']}' == ino || '${(media['readAlongEpub'] as Map?)?['fileId']}' == ino) {
        return BookOrbitMediaProxy.instance.urlFor('/api/v1/books/files/$ino/audioless-epub/download');
      }
    }
    return buildEbookUrl(itemId, ino);
  }

  /// BookOrbit streams the EPUB itself from disk, while the audio files
  /// inside it are read whole into the server's memory on every request,
  /// which crawls on a book with one big audio file. Its download tickets
  /// cover audio files only, so the EPUB goes with a freshly refreshed
  /// sign-in.
  @override
  Future<({String url, Map<String, String> headers})> narratedEpubDownload(String itemId, String ino) async {
    await _ensureFreshAccessToken();
    return (url: '$_v1/books/files/$ino/download', headers: mediaHeaders);
  }

  @override
  Map<String, String> downloadHeadersFor(String url) {
    if (url.startsWith('$_v1/watch-downloads/media-overlay/files/')) {
      final ticket = _narrationTickets[_key(Uri.parse(url).queryParameters['book'] ?? '')];
      if (ticket != null) return {...customHeaders, 'Authorization': 'Bearer ${ticket.token}'};
    }
    if (url.startsWith('$_v1/watch-downloads/files/')) {
      final fileId = Uri.parse(url).pathSegments.last;
      for (final t in _tickets.values) {
        if (t.fileIds.contains(fileId)) {
          return {...customHeaders, 'Authorization': 'Bearer ${t.token}'};
        }
      }
    }
    return mediaHeaders;
  }

  /// Background downloads outlive a fifteen-minute access token, so ask the
  /// server for a download ticket (good for twelve hours) covering the
  /// book's audio files. Without one the files go through the in-app proxy.
  final Map<String, ({String token, DateTime expiresAt, Map<String, String> paths})> _narrationTickets = {};

  @override
  String? buildNarrationDownloadUrl(String itemId, String contentUrl) {
    final uri = Uri.parse(contentUrl);
    const marker = '/media-overlay/file/';
    final at = uri.path.indexOf(marker);
    if (at < 0) return null;
    final href = uri.path
        .substring(at + marker.length)
        .split('/')
        .map(Uri.decodeComponent)
        .join('/');
    final ticket = _narrationTickets[_key(itemId)];
    final path = ticket?.paths[href];
    if (ticket != null &&
        path != null &&
        ticket.expiresAt.isAfter(DateTime.now().add(const Duration(hours: 1)))) {
      return '$_cleanBaseUrl$path?book=$itemId';
    }
    return buildTrackUrl(contentUrl);
  }

  /// A download ticket for a narrated EPUB's audio files, so a background
  /// download outlives the access token like an audiobook's does.
  Future<void> _prepareNarrationDownload(String itemId) async {
    final n = await _narration(itemId, fresh: true);
    if (n == null) return;
    final hrefs = n.overlay.tracks.map((t) => t.href).take(2048).toList();
    try {
      final res = await _boPost('/watch-downloads/media-overlay', {
        'bookId': int.parse(itemId),
        'fileId': n.fileId,
        'hrefs': hrefs,
      }) as Map<String, dynamic>;
      final token = res['token'] as String?;
      final expires = DateTime.tryParse(res['expiresAt'] as String? ?? '');
      final paths = <String, String>{
        for (final f in (res['files'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())
          if (f['href'] is String && f['downloadPath'] is String) f['href'] as String: f['downloadPath'] as String,
      };
      if (token != null && expires != null && paths.isNotEmpty) {
        _narrationTickets[_key(itemId)] = (token: token, expiresAt: expires, paths: paths);
      }
    } catch (e) {
      debugPrint('[BookOrbit] No narration download ticket for $itemId ($e) - using the proxy');
    }
  }

  @override
  Future<void> prepareDownload(String itemId) async {
    await ensureMediaReady();
    final manifest = await _manifest(itemId, fresh: true);
    if (manifest == null) {
      await _prepareNarrationDownload(itemId);
      return;
    }
    final fileIds = (manifest['assets'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        .map((a) => a['fileId'])
        .whereType<int>()
        .toList();
    if (fileIds.isEmpty) return;
    try {
      final res = await _boPost('/watch-downloads', {
        'bookId': int.parse(itemId),
        'fileIds': fileIds.take(256).toList(),
      }) as Map<String, dynamic>;
      final token = res['token'] as String?;
      final expires = DateTime.tryParse(res['expiresAt'] as String? ?? '');
      if (token != null && expires != null) {
        _tickets[_key(itemId)] = _BoTicket(token, expires, fileIds.map((e) => '$e').toSet());
      }
    } catch (e) {
      debugPrint('[BookOrbit] No download ticket for $itemId ($e) - using the proxy');
    }
  }

  Future<Map<String, dynamic>?> _playbackState(String bookId) async {
    try {
      final state = await _boGet('/audiobooks/$bookId/playback-state');
      if (state is Map<String, dynamic>) {
        final rev = (state['revision'] as num?)?.toInt();
        if (rev != null) _revisions[_key(bookId)] = rev;
        return state;
      }
      _revisions[_key(bookId)] = 0;
      return null;
    } on _BoHttpError catch (e) {
      if (e.status == 404) return null;
      rethrow;
    }
  }

  ({String? cfi, double? percent, int? updated, int? fileId}) _ebookFrom(
      Map<String, dynamic> detail, List<dynamic> fileProgress) {
    final item = BookOrbitMapper.item(detail: detail);
    final ebook = (item['media'] as Map)['ebookFile'] as Map?;
    final fileId = int.tryParse('${ebook?['ino']}');
    if (fileId == null) return (cfi: null, percent: null, updated: null, fileId: null);
    for (final p in fileProgress.whereType<Map<String, dynamic>>()) {
      if (p['fileId'] == fileId) {
        final pct = (p['percentage'] as num?)?.toDouble();
        final cfi = p['cfi'] as String? ?? (p['pageNumber'] != null ? '${p['pageNumber']}' : null);
        if ((pct == null || pct == 0) && cfi == null) break;
        return (cfi: cfi, percent: pct, updated: BookOrbitMapper.ms(p['updatedAt']), fileId: fileId);
      }
    }
    // A read along EPUB added after reading began has no place of its own
    // until BookOrbit next syncs one. The other copy's percent stands in; its
    // page can't be opened in this copy.
    if ((item['media'] as Map)['readAlongEpub'] != null) {
      final epubs = {
        for (final f in (detail['files'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())
          if ('${f['format']}'.toLowerCase() == 'epub') (f['id'] as num?)?.toInt(),
      };
      Map<String, dynamic>? newest;
      for (final p in fileProgress.whereType<Map<String, dynamic>>()) {
        final pct = (p['percentage'] as num?)?.toDouble() ?? 0;
        if (pct <= 0 || p['fileId'] == fileId || !epubs.contains((p['fileId'] as num?)?.toInt())) continue;
        if (newest == null || (BookOrbitMapper.ms(p['updatedAt']) ?? 0) > (BookOrbitMapper.ms(newest['updatedAt']) ?? 0)) {
          newest = p;
        }
      }
      if (newest != null) {
        return (
          cfi: null,
          percent: (newest['percentage'] as num).toDouble(),
          updated: BookOrbitMapper.ms(newest['updatedAt']),
          fileId: fileId,
        );
      }
    }
    return (cfi: null, percent: null, updated: null, fileId: fileId);
  }

  Future<Map<String, dynamic>?> _itemProgress(
    String bookId, {
    Map<String, dynamic>? detail,
    Map<String, dynamic>? manifest,
  }) async {
    detail ??= await _detail(bookId);
    final hasAudio = _detailHasAudio(detail);
    manifest ??= hasAudio ? await _manifest(bookId) : null;
    final state = manifest != null ? await _playbackState(bookId) : null;
    ({String? cfi, double? percent, int? updated, int? fileId}) ebook =
        (cfi: null, percent: null, updated: null, fileId: null);
    final itemMedia = BookOrbitMapper.item(detail: detail)['media'] as Map;
    var fp = const <dynamic>[];
    if (itemMedia['ebookFile'] != null) {
      try {
        fp = await _boGet('/books/$bookId/progress') as List<dynamic>;
        ebook = _ebookFrom(detail, fp);
      } catch (_) {}
    }
    // A narrated EPUB with no audiobook: listening progress is the narration
    // position kept on the EPUB.
    final narration = itemMedia['narration'] as Map?;
    double? narrationAt;
    final narrationTotal = (narration?['duration'] as num?)?.toDouble() ?? 0;
    if (narration != null) {
      final fileId = int.tryParse('${narration['fileId']}');
      for (final r in fp.whereType<Map<String, dynamic>>()) {
        if ((r['fileId'] as num?)?.toInt() != fileId) continue;
        // BookOrbit's own reader can leave a sentence or only a page, with no
        // seconds: those are placed on the narration too.
        narrationAt = (r['positionSeconds'] as num?)?.toDouble() ??
            await _placeNarrationSpot(bookId,
                fragment: r['mediaOverlayFragment'] as String?,
                section: (r['mediaOverlaySectionIndex'] as num?)?.toInt(),
                cfi: r['cfi'] as String?);
      }
    }
    final readStatus = detail['readStatus'] as Map<String, dynamic>?;
    if (state == null && ebook.percent == null && readStatus == null) return null;
    final p = BookOrbitMapper.progress(
      bookId: bookId,
      manifest: manifest,
      state: state,
      readStatus: readStatus,
      ebookPercent: ebook.percent,
      ebookLocation: ebook.cfi,
      ebookUpdatedAt: ebook.updated,
    );
    if (!hasAudio && ebook.percent != null) p['progress'] = (ebook.percent! / 100).clamp(0.0, 1.0);
    if (narrationAt != null && narrationTotal > 0) {
      p['duration'] = narrationTotal;
      p['currentTime'] = narrationAt;
      if (p['isFinished'] != true) p['progress'] = (narrationAt / narrationTotal).clamp(0.0, 1.0);
    } else if (narration != null) {
      // No listening spot on the EPUB that can be placed (no copy of the book
      // here): nothing to move a paused player to, least of all 0.
      p.remove('currentTime');
    }
    return p;
  }

  // Books with an audiobook being read as ebooks, by id, for Continue
  // Reading: BookOrbit's own list goes by a book's primary file, which is
  // the audiobook, so it never has them.
  static final Map<String, Map<String, dynamic>> _ebookReadCards = {};

  Future<List<Map<String, dynamic>>> _allProgress() async {
    final byId = <String, Map<String, dynamic>>{};
    final reading = <String, Map<String, dynamic>>{};
    Future<void> collect(List<String> statuses, String sortField, int maxPages) async {
      for (var page = 0; page < maxPages; page++) {
        final res = await _boPost('/books/query', {
          'filter': {
            'type': 'group',
            'join': 'AND',
            'rules': [_rule('readStatus', 'includesAny', statuses)],
          },
          'sort': [{'field': sortField, 'dir': 'desc'}],
          'pagination': {'page': page, 'size': 200},
        }) as Map<String, dynamic>;
        final items = (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
        for (final c in items) {
          _cardItem(c);
          byId['${c['id']}'] = BookOrbitMapper.cardProgress(c);
          if (statuses.contains('reading')) reading['${c['id']}'] = c;
        }
        final total = (res['total'] as num?)?.toInt() ?? 0;
        if (items.length < 200 || (page + 1) * 200 >= total) break;
      }
    }

    await collect(['reading', 'rereading', 'on_hold'], 'startedAt', 5);
    await collect(['read', 'skimmed'], 'finishedAt', 2);
    // Real positions for what is being listened to right now, so another
    // device's place carries over.
    try {
      final listening = (await _shelfCards('continue-listening', 12)).map((c) => '${c['id']}').toList();
      final real = await _pool(listening.map((id) => () async {
            try {
              final manifest = await _manifest(id);
              if (manifest == null) return await _narrationProgress(id, byId[id]);
              final state = await _playbackState(id);
              if (state == null) return null;
              final card = byId[id];
              return BookOrbitMapper.progress(
                bookId: id,
                manifest: manifest,
                state: state,
                readStatus: card == null ? null : {'status': card['isFinished'] == true ? 'read' : 'reading', 'updatedAt': null},
              );
            } catch (_) {
              return null;
            }
          }).toList());
      for (final p in real.whereType<Map<String, dynamic>>()) {
        byId['${p['libraryItemId']}'] = p;
      }
    } catch (e) {
      debugPrint('[BookOrbit] Continue-listening positions failed: $e');
    }
    await _addEbookPercents(byId, reading);
    return byId.values.toList();
  }

  /// A book with an audiobook and an ebook is listed by its audiobook, so
  /// its reading is read off the ebook's own file. Without it the Read
  /// button lost its percent after a restart, and Continue Reading never
  /// had the book. A narrated EPUB is listed by its narration, so its page
  /// is read the same way; BookOrbit already has it on Continue Reading.
  Future<void> _addEbookPercents(Map<String, Map<String, dynamic>> byId, Map<String, Map<String, dynamic>> reading) async {
    final narrated = <String>{};
    final both = <MapEntry<String, Map<String, dynamic>>>[];
    for (final e in reading.entries) {
      final item = BookOrbitMapper.item(card: e.value);
      final media = item['media'] as Map;
      if (media['ebookFile'] == null) continue;
      if (media['narration'] != null) {
        narrated.add(e.key);
        both.add(e);
      } else if ((item['bookOrbit'] as Map?)?['audioCover'] == true) {
        both.add(e);
      }
    }
    final found = await _pool(both
        .map((e) => () async {
              try {
                return _ebookFrom(e.value, await _boGet('/books/${e.key}/progress') as List<dynamic>);
              } catch (_) {
                return null;
              }
            })
        .toList());
    final cards = <String, Map<String, dynamic>>{};
    for (var i = 0; i < both.length; i++) {
      final ebook = found[i];
      final p = byId[both[i].key];
      if (ebook == null || p == null || (ebook.percent == null && ebook.cfi == null)) continue;
      final pct = ((ebook.percent ?? 0) / 100).clamp(0.0, 1.0);
      p['ebookProgress'] = pct;
      if (ebook.cfi != null) p['ebookLocation'] = ebook.cfi;
      if (pct > 0 && pct < 1 && p['isFinished'] != true && !narrated.contains(both[i].key)) {
        cards[both[i].key] = both[i].value;
      }
    }
    _ebookReadCards
      ..clear()
      ..addAll(cards);
  }

  /// The progress of a book read aloud from its EPUB: its place is kept on
  /// the EPUB file, not as an audiobook. Null for any other book.
  Future<Map<String, dynamic>?> _narrationProgress(String id, Map<String, dynamic>? card) async {
    final n = await _narration(id);
    if (n == null) return null;
    final spot = await _narrationPosition(id, n.fileId);
    if (spot == null) return null;
    final duration = n.overlay.duration;
    final finished = card?['isFinished'] == true;
    return {
      ...?card,
      'id': card?['id'] ?? 'bo-$id',
      'libraryItemId': id,
      'mediaItemId': id,
      'mediaItemType': 'book',
      'episodeId': null,
      'currentTime': spot.seconds,
      'duration': duration,
      'progress': finished ? 1.0 : (duration > 0 ? (spot.seconds / duration).clamp(0.0, 1.0) : 0.0),
      'isFinished': finished,
      'lastUpdate': spot.updatedAt ?? card?['lastUpdate'] ?? 0,
    }..remove('positionUnknown');
  }

  /// A library scan as Audiobookshelf asks for one: BookOrbit's scanner for a
  /// library, or its watcher's rescan for the Book Dock.
  Future<Map<String, dynamic>> _scanLibrary(String libId) async {
    if (libId == ApiService.bookDockLibraryId) {
      await _boPost('/book-dock/rescan');
      debugPrint('[BookOrbit] Book Dock rescan started');
    } else {
      await _boPost('/scanner/libraries/$libId/scan');
      debugPrint('[BookOrbit] library $libId scan started');
    }
    return {'success': true};
  }

  /// Save a book-absolute position. Returns the HTTP status that best
  /// describes the outcome for Audiobookshelf callers.
  // Books and series taken off the Continue shelves. BookOrbit has no way to
  // hide one, so Absorb keeps the list, per account; a book comes back once
  // it is listened to or read again, the way Audiobookshelf does it.
  static const _hiddenBooksKey = 'bookorbit_hidden_continue';
  static const _hiddenSeriesKey = 'bookorbit_hidden_continue_series';

  Future<void> _hideFromContinue(String key, String id) async {
    final ids = await ScopedPrefs.getStringList(key);
    if (!ids.contains(id)) await ScopedPrefs.setStringList(key, [...ids, id]);
    _recent.removeWhere((k, _) => k.startsWith('personalized:'));
  }

  Future<void> _backOnContinue(String bookId) async {
    final ids = await ScopedPrefs.getStringList(_hiddenBooksKey);
    if (!ids.remove(bookId)) return;
    await ScopedPrefs.setStringList(_hiddenBooksKey, ids);
    _recent.removeWhere((k, _) => k.startsWith('personalized:'));
  }

  Future<int> _putPosition(String bookId, double absoluteSeconds, {DateTime? capturedAt}) async {
    await _backOnContinue(bookId);
    var manifest = await _manifest(bookId);
    if (manifest == null) return _putNarrationPosition(bookId, absoluteSeconds);
    final when = (capturedAt ?? DateTime.now()).toUtc();
    final operationId = _uuid();
    for (var attempt = 0; attempt < 3; attempt++) {
      final pos = BookOrbitMapper.trackPosition(manifest!, absoluteSeconds);
      if (pos == null) return 404;
      var base = _revisions[_key(bookId)];
      if (base == null) {
        final state = await _playbackState(bookId);
        final serverAt = DateTime.tryParse(state?['capturedAt'] as String? ?? '');
        if (serverAt != null && serverAt.isAfter(when)) return 200;
        base = _revisions[_key(bookId)] ?? 0;
      }
      try {
        final saved = await _boPut('/audiobooks/$bookId/playback-state', {
          'assetId': pos.assetId,
          'positionMs': pos.positionMs,
          'capturedAt': _iso(when),
          'operationId': operationId,
          'baseRevision': base,
          'manifestRevision': manifest['revision'],
        }) as Map<String, dynamic>;
        final rev = (saved['revision'] as num?)?.toInt();
        if (rev != null) _revisions[_key(bookId)] = rev;
        return 200;
      } on _BoHttpError catch (e) {
        if (e.status == 409) {
          _revisions.remove(_key(bookId));
          final state = await _playbackState(bookId);
          final serverAt = DateTime.tryParse(state?['capturedAt'] as String? ?? '');
          if (serverAt != null && !serverAt.isBefore(when)) return 200;
          continue;
        }
        if (e.status == 412) {
          manifest = await _manifest(bookId, fresh: true);
          if (manifest == null) return 404;
          continue;
        }
        debugPrint('[BookOrbit] Position for $bookId not saved: ${e.status} ${e.message}');
        return e.status;
      }
    }
    return 409;
  }

  Future<void> _setStatus(String bookId, Map<String, dynamic> body) async {
    await _boPatch('/books/$bookId/status', body);
    // The refresh right after reads progress: a cached list from before the
    // change showed a just-finished book as still being read.
    _forgetProgress(bookId);
  }

  void _forgetProgress(String bookId) {
    _details.remove(_key(bookId));
    _detailAt.remove(_key(bookId));
    _recent.removeWhere((key, _) => key == 'progress' || key.startsWith('personalized:'));
  }

  static String? _dateParam(Object? ms) {
    if (ms is! num || ms <= 0) return null;
    final d = DateTime.fromMillisecondsSinceEpoch(ms.toInt());
    final now = DateTime.now();
    return _iso(d.isAfter(now) ? now : d);
  }

  Future<void> _patchProgress(String bookId, Map<String, dynamic> body) async {
    if (bookId.length > 36) return;
    final isFinished = body['isFinished'];
    if (isFinished == true) {
      // List items carry no duration here, so the caller's end-of-book
      // position can be 0. The end comes from the track list instead.
      final manifest = await _manifest(bookId);
      if (manifest != null) {
        final status = await _putPosition(bookId, BookOrbitMapper.totalSeconds(manifest));
        if (status >= 500) throw _BoHttpError(status, 'Position not saved');
      }
    } else if (body['currentTime'] is num && isFinished == null) {
      final status = await _putPosition(bookId, (body['currentTime'] as num).toDouble());
      if (status >= 500) throw _BoHttpError(status, 'Position not saved');
    }
    if (body.containsKey('ebookLocation') || body.containsKey('ebookProgress')) {
      await _saveEbookProgress(bookId, body['ebookLocation'] as String?, (body['ebookProgress'] as num?)?.toDouble());
    }
    if (isFinished == true) {
      await _setStatus(bookId, {
        'status': 'read',
        if (_dateParam(body['finishedAt']) != null) 'finishedAt': _dateParam(body['finishedAt']),
      });
    } else if (isFinished == false) {
      // Audiobookshelf clears the position when a book is un-finished.
      await _clearPosition(bookId);
      await _unfinish(bookId);
    } else if (body['finishedAt'] != null) {
      final d = _dateParam(body['finishedAt']);
      if (d != null) await _setStatus(bookId, {'finishedAt': d});
    }
    final started = _dateParam(body['startedAt'] ?? body['createdAt']);
    if (started != null && isFinished == null && body['currentTime'] == null) {
      await _setStatus(bookId, {'startedAt': started});
    }
  }

  Future<void> _saveEbookProgress(String bookId, String? location, double? progress) async {
    await _backOnContinue(bookId);
    final detail = await _detail(bookId);
    final media = BookOrbitMapper.item(detail: detail)['media'] as Map;
    final ebook = media['ebookFile'] as Map?;
    final fileId = ebook?['ino'];
    if (fileId == null) return;
    final pct = ((progress ?? 0) * 100).clamp(0.0, 100.0);
    final page = location == null ? null : int.tryParse(location);
    await _boPost('/books/files/$fileId/progress', {
      'percentage': pct,
      if (location != null && page == null) 'cfi': location,
      if (page != null) 'pageNumber': page,
      ...await _narrationSpotToKeep(bookId, media, '$fileId'),
    });
    if (progress != null && progress >= 1.0) {
      await _setStatus(bookId, {'status': 'read'});
    }
  }

  Future<void> _clearPosition(String bookId) async {
    try {
      await _boDelete('/audiobooks/$bookId/playback-state');
    } on _BoHttpError catch (e) {
      if (e.status != 404) rethrow;
    }
    _revisions[_key(bookId)] = 0;
  }

  /// Take a finished book back to reading. Any status set from here is a
  /// manual one, which BookOrbit never updates on its own again, so nothing
  /// is written unless the book is actually marked finished.
  Future<void> _unfinish(String bookId) async {
    final status = ((await _detail(bookId, fresh: true))['readStatus'] as Map?)?['status'];
    if (status == 'read' || status == 'skimmed') {
      await _setStatus(bookId, {'status': 'reading'});
    }
  }

  /// A reset leaves the book as never started, like Audiobookshelf's: no
  /// audio spot, no place in any of its files, and unread, so it leaves
  /// BookOrbit's Currently Reading and Continue shelves. Listening sessions
  /// and finished reads stay; BookOrbit closes a read still open as abandoned.
  Future<void> _deleteProgress(String progressId) async {
    final bookId = progressId.startsWith('bo-') ? progressId.substring(3) : progressId;
    await _clearPosition(bookId);
    final rows = await _boGet('/books/$bookId/progress') as List<dynamic>;
    for (final row in rows.whereType<Map>()) {
      final fileId = row['fileId'];
      if (fileId == null) continue;
      try {
        await _boDelete('/books/files/$fileId/progress');
      } on _BoHttpError catch (e) {
        if (e.status != 404) rethrow;
      }
    }
    final status = ((await _detail(bookId, fresh: true))['readStatus'] as Map?)?['status'];
    if (status != null && status != 'unread' && status != 'want_to_read') {
      await _setStatus(bookId, {'status': 'unread'});
    }
    _forgetProgress(bookId);
  }

  /// Only the ebook file's progress: the full item progress also reads the
  /// audio manifest and playback state, which made the reader's open-time
  /// check run out of time and start from the phone's older place.
  @override
  Future<Map<String, dynamic>?> getEbookPosition(String itemId) async {
    final detail = await _detail(itemId);
    final fp = await _boGet('/books/$itemId/progress') as List<dynamic>;
    final ebook = _ebookFrom(detail, fp);
    if (ebook.cfi == null && ebook.percent == null) return null;
    return {
      'ebookLocation': ebook.cfi,
      'ebookProgress': ebook.percent == null ? null : (ebook.percent! / 100).clamp(0.0, 1.0),
      'ebookUpdatedAt': ebook.updated,
    };
  }

  @override
  Future<bool> updateEbookProgress(String itemId, {required String ebookLocation, required double ebookProgress}) async {
    lastEbookProgressStatus = null;
    try {
      await _saveEbookProgress(itemId, ebookLocation, ebookProgress);
      lastEbookProgressStatus = 200;
      return true;
    } on _BoHttpError catch (e) {
      lastEbookProgressStatus = e.status;
      debugPrint('[BookOrbit] updateEbookProgress error: $e');
      return false;
    } catch (e) {
      debugPrint('[BookOrbit] updateEbookProgress error: $e');
      return false;
    }
  }

  @override
  Future<bool> setCollectionPublic(String collectionId, bool isPublic) async {
    try {
      await _boPatch('/collections/$collectionId', {'isPublic': isPublic});
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] setCollectionPublic error: $e');
      return false;
    }
  }

  @override
  Future<bool> updateLibraryItemsFinished(List<String> itemIds, {required bool isFinished}) async {
    if (itemIds.isEmpty) return false;
    try {
      await _pool(itemIds.map((id) => () => _patchProgress(id, {'isFinished': isFinished})).toList(), width: 4);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] updateLibraryItemsFinished error: $e');
      return false;
    }
  }

  @override
  Future<bool> resetProgress(String itemId, double duration, {String? progressId}) async {
    try {
      await _deleteProgress(itemId);
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] resetProgress error: $e');
      return false;
    }
  }

  @override
  Future<bool> updateProgressStartDate(String itemId, int startedAt) async {
    try {
      final d = _dateParam(startedAt);
      if (d == null) return false;
      await _setStatus(itemId, {'startedAt': d});
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] updateProgressStartDate error: $e');
      return false;
    }
  }

  @override
  Future<bool> updateProgressFinishedDate(String itemId, int finishedAt) async {
    try {
      final d = _dateParam(finishedAt);
      if (d == null) return false;
      try {
        await _setStatus(itemId, {'status': 'read', 'finishedAt': d});
      } on _BoHttpError catch (e) {
        // Marking a book finished today starts its read today too, so an
        // earlier finish date lands before the start. Move the start with it;
        // the start date can be set on its own afterwards.
        if (e.status != 400 || !e.body.contains('READING_DATES_INVALID_ORDER')) rethrow;
        await _setStatus(itemId, {'status': 'read', 'startedAt': d, 'finishedAt': d});
      }
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] updateProgressFinishedDate error: $e');
      return false;
    }
  }

  static int? _boSessionNumber(Object? id) {
    final s = '$id';
    return s.startsWith('bo-session-') ? int.tryParse(s.substring('bo-session-'.length)) : null;
  }

  void _forgetListeningStats() => _recent.removeWhere((k, _) =>
      k == _key('listening-stats') || k.startsWith(_key('activity-day-')) || k.startsWith(_key('year-stats-')));

  /// The file a listen is logged against: the audiobook's first file, or
  /// the EPUB that reads itself aloud.
  Future<String?> _listenFileId(String bookId) async {
    final manifest = await _manifest(bookId);
    final assets = manifest?['assets'] as List<dynamic>?;
    if (assets != null && assets.isNotEmpty) return '${(assets.first as Map)['fileId']}';
    final narration = (BookOrbitMapper.item(detail: await _detail(bookId))['media'] as Map)['narration'] as Map?;
    return narration?['fileId'] as String?;
  }

  /// Logs listening time the way the player does, so BookOrbit counts it as
  /// listening, or reading time against the ebook file it was read in. No
  /// end point goes with it: BookOrbit moves a book's read status by a long
  /// session's end point, which would take a finished book back to reading.
  Future<void> _saveListen(String bookId, DateTime startedAt, int seconds,
      {String? fileId, bool reading = false}) async {
    final file = fileId ?? (reading ? null : await _listenFileId(bookId));
    if (file == null) throw _BoHttpError(404, 'No file to log the session against');
    final source = _platformSource();
    await _boPost('/books/files/$file/sessions', {
      'sessionId': _uuid(),
      'startedAt': _iso(startedAt),
      'endedAt': _iso(startedAt.add(Duration(seconds: seconds))),
      'durationSeconds': seconds,
      'sessionType': reading ? 'read' : 'listen',
      'source': ?source,
      ...await _clientName(),
    });
  }

  @override
  Future<bool> addListeningSession({
    required String itemId,
    required DateTime startedAt,
    required int seconds,
  }) async {
    try {
      await _saveListen(itemId, startedAt, seconds);
      _forgetListeningStats();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Adding a listening session failed: $e');
      return false;
    }
  }

  /// BookOrbit can move a session to another time but not change its
  /// length, so a new length is logged as a new session in place of the old.
  @override
  Future<bool> updateListeningSession(Map<String, dynamic> session) async {
    final id = _boSessionNumber(session['id']);
    final bookId = '${session['libraryItemId'] ?? ''}';
    final origStart = (session['startedAt'] as num?)?.toInt();
    final origEnd = (session['boEndedAt'] as num?)?.toInt();
    final origSeconds = (session['boSeconds'] as num?)?.toInt();
    final newEnd = (session['updatedAt'] as num?)?.toInt();
    final newSeconds = (session['timeListening'] as num?)?.round();
    if (id == null || bookId.isEmpty || origStart == null || origEnd == null || origSeconds == null ||
        newEnd == null || newSeconds == null || newSeconds <= 0) {
      return false;
    }
    // The edit keeps the time of day and moves the date.
    final start = DateTime.fromMillisecondsSinceEpoch(origStart + newEnd - origEnd);
    try {
      if (newSeconds ~/ 60 == origSeconds ~/ 60) {
        if (start.millisecondsSinceEpoch == origStart) return true;
        await _boPatch('/user-statistics/session-timeline/$id', {
          'startedAt': _iso(start),
          'endedAt': _iso(start.add(Duration(seconds: origSeconds))),
        });
      } else {
        final fileId = session['boFileId'] == null ? null : '${session['boFileId']}';
        final reading = session['boReading'] == true;
        // A reading session can only be logged again against its own file.
        if (reading && fileId == null) return false;
        await _boDelete('/books/$bookId/sessions/$id');
        try {
          await _saveListen(bookId, start, newSeconds, fileId: fileId, reading: reading);
        } catch (e) {
          debugPrint('[BookOrbit] New session length not saved, putting the old one back: $e');
          await _saveListen(bookId, DateTime.fromMillisecondsSinceEpoch(origStart), origSeconds,
              fileId: fileId, reading: reading);
          rethrow;
        }
      }
      _forgetListeningStats();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Editing listening session $id failed: $e');
      return false;
    }
  }

  @override
  Future<bool> deleteListeningSession(String sessionId, {String? itemId}) async {
    final id = _boSessionNumber(sessionId);
    if (id == null || itemId == null) return false;
    try {
      await _boDelete('/books/$itemId/sessions/$id');
      _forgetListeningStats();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Deleting listening session $id failed: $e');
      return false;
    }
  }

  // Static like the other caches: the app builds a new service for nearly
  // every call, and reading a long book's timings again takes seconds.
  static final Map<String, ({MediaOverlay overlay, int fileId})> _narrations = {};
  static final Map<String, Future<({MediaOverlay overlay, int fileId})?>> _narrationLoads = {};

  /// The narration of a book whose only audio is its EPUB reading itself
  /// aloud (EPUB 3 media overlays), or null for any other book.
  Future<({MediaOverlay overlay, int fileId})?> _narration(
    String bookId, {
    Map<String, dynamic>? detail,
    bool fresh = false,
  }) async {
    final k = _key(bookId);
    final cached = _narrations[k];
    if (!fresh && cached != null) return cached;
    // Home reads the timings ahead of a play; a play that starts meanwhile
    // waits for that read instead of making its own.
    final loading = _narrationLoads[k];
    if (!fresh && loading != null) return loading;
    final load = _loadNarration(bookId, k, cached, detail);
    _narrationLoads[k] = load;
    try {
      return await load;
    } finally {
      if (identical(_narrationLoads[k], load)) _narrationLoads.remove(k);
    }
  }

  Future<({MediaOverlay overlay, int fileId})?> _loadNarration(
    String bookId,
    String k,
    ({MediaOverlay overlay, int fileId})? cached,
    Map<String, dynamic>? detail,
  ) async {
    detail ??= await _detail(bookId);
    final media = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;
    final fileId = int.tryParse('${(media['narration'] as Map?)?['fileId']}');
    if (fileId == null) return null;
    // The same narrated file as last time has the same timings: reading
    // them again took seconds on a long book, and held up every start.
    if (cached != null && cached.fileId == fileId) return cached;
    final overlay = await _overlayOf(bookId, fileId);
    if (overlay == null) return null;
    return _narrations[k] = (overlay: overlay, fileId: fileId);
  }

  Future<MediaOverlay?> _overlayOf(String bookId, int fileId) async {
    final playlist = await _boGet('/epub/$bookId/media-overlay', {'fileId': '$fileId'}) as Map<String, dynamic>;
    final parsed = MediaOverlay.fromBookOrbit(playlist);
    if (parsed == null || parsed.isEmpty) return null;
    // The playlist names each narrated file only when the contents point
    // straight at it; the whole contents name the rest.
    try {
      final info = await _boGet('/epub/$bookId/info', {'fileId': '$fileId'}) as Map<String, dynamic>;
      return parsed.withBookOrbitContents(info);
    } catch (e) {
      debugPrint('[BookOrbit] contents for $bookId not read: $e');
      return parsed;
    }
  }

  static final Map<String, ({MediaOverlay overlay, int fileId, double audio})> _readAlongTimings = {};

  /// The copy of [bookId] to read when it has a read along EPUB matching its
  /// audiobook, so read along can follow that EPUB's timings. Null for any
  /// other book, which keeps the copy it was opened with.
  Future<Map<String, dynamic>?> readAlongReaderFile(String bookId) async {
    Map<String, dynamic>? detail;
    try {
      detail = await _detail(bookId).timeout(const Duration(seconds: 10));
    } catch (e) {
      detail = _details[_key(bookId)];
      debugPrint('[BookOrbit] reader copy for $bookId from ${detail == null ? 'nothing' : 'the last details'}: $e');
    }
    if (detail == null) return null;
    final media = BookOrbitMapper.item(detail: detail)['media'] as Map<String, dynamic>;
    if (media['readAlongEpub'] == null) return null;
    return (media['ebookFile'] as Map?)?.cast<String, dynamic>();
  }

  /// The timings of a read along EPUB that sits beside its audiobook, laid on
  /// the audiobook's timeline so they follow the audiobook as it plays. Null
  /// for a book without one, or when BookOrbit doesn't keep the two in step.
  Future<MediaOverlay?> readAlongTimingsFor(String bookId) async {
    try {
      final media = BookOrbitMapper.item(detail: await _detail(bookId))['media'] as Map<String, dynamic>;
      final readAlong = media['readAlongEpub'] as Map?;
      final fileId = int.tryParse('${readAlong?['fileId']}');
      final audio = (readAlong?['audioDuration'] as num?)?.toDouble() ?? 0;
      if (fileId == null || audio <= 0) return null;
      final k = _key(bookId);
      final cached = _readAlongTimings[k];
      if (cached != null && cached.fileId == fileId && cached.audio == audio) return cached.overlay;
      final overlay = await _overlayOf(bookId, fileId);
      if (overlay == null) return null;
      final laid = overlay.scaledTo(audio);
      debugPrint('[BookOrbit] read along timings for $bookId from file $fileId: '
          '${overlay.clips.length} sentences, ${overlay.duration.toStringAsFixed(0)}s laid on ${audio.toStringAsFixed(0)}s');
      _readAlongTimings[k] = (overlay: laid, fileId: fileId, audio: audio);
      return laid;
    } catch (e) {
      debugPrint('[BookOrbit] read along timings for $bookId failed: $e');
      return null;
    }
  }

  /// Public for the reader's read along: the same narration the player is
  /// streaming, so its timings line up exactly.
  /// Whether [bookId] is known here to be a book whose audio is its EPUB's
  /// narration, from a narration already looked up (playing it, or opening
  /// it in the reader). No request.
  bool knownNarrated(String bookId) => _narrations.containsKey(_key(bookId));

  Future<MediaOverlay?> narrationFor(String bookId) async {
    try {
      return (await _narration(bookId))?.overlay;
    } catch (e) {
      debugPrint('[BookOrbit] narration for $bookId failed: $e');
      return null;
    }
  }

  // BookOrbit checks this marker on its own, never through superuser.
  bool get _demoRestricted => _permissions?.contains('demo_restricted') ?? false;

  /// Whether this account may make read alongs. BookOrbit turns demo
  /// accounts away from every read along route.
  Future<bool> canMakeReadAlongs() async => await _can('library_generate_read_aloud') && !_demoRestricted;

  /// Replacing a read along deletes the old file, so BookOrbit only takes it
  /// from someone who may delete books.
  bool get canReplaceReadAlongs => _hasPermission('library_delete_books');

  /// What [bookId] has to make a read along from, with its latest job. Null
  /// when this account can't make them or the server is older than 3.6.0;
  /// throws when the server couldn't be asked.
  Future<ReadAlongCapability?> readAlongCapability(String bookId) async {
    if (!await canMakeReadAlongs()) return null;
    try {
      return ReadAlongCapability.fromJson(await _boGet('/books/$bookId/read-aloud') as Map<String, dynamic>);
    } on _BoHttpError catch (e) {
      if (e.status == 400 || e.status == 403 || e.status == 404) return null;
      rethrow;
    }
  }

  /// Every track goes in, in the book's order, which is what BookOrbit uses
  /// when none are named.
  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> startReadAlong(
    String bookId, {
    required int epubFileId,
    required String language,
    String granularity = 'sentence',
    int? replaceFileId,
  }) async {
    debugPrint('[BookOrbit] Read along for $bookId: epub $epubFileId, $language, $granularity'
        '${replaceFileId != null ? ', replacing $replaceFileId' : ''}');
    return _readAlongCall('start for $bookId', () => _boPost('/books/$bookId/read-aloud-jobs', {
          'epubFileId': epubFileId,
          'language': language,
          'granularity': granularity,
          'replaceFileId': ?replaceFileId,
        }));
  }

  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> readAlongJob(String jobId) =>
      _readAlongCall('job $jobId', () => _boGet('/read-aloud-jobs/$jobId'), quiet: true);

  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> cancelReadAlong(String jobId) =>
      _readAlongCall('cancel $jobId', () => _boDelete('/read-aloud-jobs/$jobId'));

  /// Adds output waiting for review to the book as it is.
  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> publishReadAlong(String jobId) =>
      _readAlongCall('publish $jobId', () => _boPost('/read-aloud-jobs/$jobId/publish', const <String, dynamic>{}));

  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> retryReadAlong(String jobId) =>
      _readAlongCall('retry $jobId', () => _boPost('/read-aloud-jobs/$jobId/retry', const <String, dynamic>{}));

  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> dismissReadAlong(String jobId) =>
      _readAlongCall('dismiss $jobId', () => _boPost('/read-aloud-jobs/$jobId/dismiss', const <String, dynamic>{}));

  Future<({ReadAlongJob? job, ReadAlongFailure? failure})> _readAlongCall(
    String what,
    Future<dynamic> Function() send, {
    bool quiet = false,
  }) async {
    try {
      final job = ReadAlongJob.fromJson(await send());
      if (job == null) {
        debugPrint('[BookOrbit] Read along $what: unreadable answer');
        return (job: null, failure: ReadAlongFailure.failed);
      }
      if (!quiet) debugPrint('[BookOrbit] Read along $what: ${job.status} at ${job.stage}');
      return (job: job, failure: null);
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] Read along $what: ${e.status} ${e.message}');
      return (job: null, failure: readAlongFailureFor(e.status));
    } catch (e) {
      debugPrint('[BookOrbit] Read along $what: $e');
      return (job: null, failure: ReadAlongFailure.failed);
    }
  }

  /// The narration language picked first when a book names none the speech
  /// model knows.
  Future<String?> readAlongDefaultLanguage() async {
    try {
      final res = await _boGet('/user-preferences/read-aloud') as Map<String, dynamic>;
      final code = (res['settings'] as Map?)?['defaultLanguage'];
      return code is String && code.isNotEmpty ? code : null;
    } catch (e) {
      debugPrint('[BookOrbit] Read along default language not read: $e');
      return null;
    }
  }

  Future<bool> setReadAlongDefaultLanguage(String code) async {
    try {
      await _boPut('/user-preferences/read-aloud', {
        'settings': {'defaultLanguage': code},
      });
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Read along default language not saved: $e');
      return false;
    }
  }

  /// BookOrbit keeps reading sessions of its own: the time goes on the ebook
  /// file as reading, not listening.
  @override
  Future<bool> logReadingTime(
    String itemId, {
    required String sessionId,
    required DateTime startedAt,
    required int seconds,
    required double audioAt,
    required double audioDuration,
    String? title,
    double? ebookStart,
    double? ebookEnd,
  }) async {
    try {
      final detail = await _detail(itemId);
      final ebook = (BookOrbitMapper.item(detail: detail)['media'] as Map)['ebookFile'] as Map?;
      final fileId = ebook?['ino'];
      if (fileId == null) return false;
      final end = DateTime.now();
      final span = math.max(0, end.difference(startedAt).inSeconds);
      final source = _platformSource();
      await _boPost('/books/files/$fileId/sessions', {
        'sessionId': sessionId.length > 64 ? sessionId.substring(0, 64) : sessionId,
        'startedAt': _iso(startedAt),
        'endedAt': _iso(end),
        'durationSeconds': math.min(seconds, span),
        if (ebookStart != null && ebookEnd != null)
          'progressDelta': double.parse(((ebookEnd - ebookStart) * 100).toStringAsFixed(4)),
        if (ebookEnd != null) 'endProgress': (ebookEnd * 100).clamp(0.0, 100.0),
        'sessionType': 'read',
        if (source != null) 'source': source,
        ...await _clientName(),
      });
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] reading time for $itemId not logged: $e');
      return false;
    }
  }

  /// BookOrbit keeps a narrated EPUB's listening spot on the same row as its
  /// page. Before 3.5.0 a page save without it cleared it, so there the spot
  /// rides along. From 3.5.0 a save that leaves it out keeps it, and sending
  /// the one read a moment ago could put back an older spot over a newer one.
  Future<Map<String, Object?>> _narrationSpotToKeep(String bookId, Map media, String fileId) async {
    if ('${(media['narration'] as Map?)?['fileId']}' != fileId) return const {};
    // `reader-file-positions` arrived in the same release.
    if ((await _features()).contains('reader-file-positions')) return const {};
    try {
      final at = await _narrationPosition(bookId, int.parse(fileId), place: false);
      if (at == null) return const {};
      final clip = (await _narration(bookId))?.overlay.clipAt(at.seconds);
      return {
        'positionSeconds': at.seconds,
        'mediaOverlayFragment': clip?.textSrc,
        'mediaOverlaySectionIndex': clip?.section,
      };
    } catch (e) {
      debugPrint('[BookOrbit] narration spot for $bookId not kept: $e');
      return const {};
    }
  }

  /// Where the narration was left, in seconds, from the EPUB's progress.
  /// [place] works out a spot BookOrbit kept without seconds; without it
  /// only seconds saved on the row count.
  Future<({double seconds, int? updatedAt})?> _narrationPosition(String bookId, int fileId,
      {bool place = true}) async {
    try {
      final rows = await _boGet('/books/$bookId/progress') as List<dynamic>;
      for (final r in rows.whereType<Map<String, dynamic>>()) {
        if ((r['fileId'] as num?)?.toInt() != fileId) continue;
        final at = BookOrbitMapper.ms(r['updatedAt']);
        final s = (r['positionSeconds'] as num?)?.toDouble();
        if (s != null) return (seconds: s, updatedAt: at);
        if (!place) return null;
        // BookOrbit's own reader saves the sentence it read aloud, or only
        // the page it reached, with no seconds: place them on the narration.
        final placed = await _placeNarrationSpot(bookId,
            fragment: r['mediaOverlayFragment'] as String?,
            section: (r['mediaOverlaySectionIndex'] as num?)?.toInt(),
            cfi: r['cfi'] as String?);
        return placed == null ? null : (seconds: placed, updatedAt: at);
      }
    } on _BoHttpError catch (e) {
      if (e.status != 404) rethrow;
    }
    return null;
  }

  /// Places a reading spot in a narrated EPUB on its narration's timeline,
  /// from the copy of the book kept on this phone. Set by the app at start;
  /// a spot with no copy here stays unplaced.
  static Future<double?> Function(String bookId, MediaOverlay overlay, String cfi)? placeReadingSpot;
  static final Map<String, double> _placedSpots = {};

  /// BookOrbit's timings for a book as kept on this phone (downloaded, or
  /// read along before). Set by the app at start. A play checks the server's
  /// spot for a moment only, and fetching a long book's timings takes longer.
  static Future<MediaOverlay?> Function(String bookId)? keptNarration;

  Future<double?> _placeNarrationSpot(String bookId, {String? fragment, int? section, String? cfi}) async {
    if ((fragment == null || fragment.isEmpty) && (cfi == null || cfi.isEmpty)) return null;
    var overlay = _narrations[_key(bookId)]?.overlay;
    if (overlay == null) {
      try {
        overlay = await keptNarration?.call(bookId);
      } catch (_) {}
    }
    if (overlay == null) {
      debugPrint('[BookOrbit] $bookId: reading the narration timings from the server to place its spot');
      try {
        overlay = (await _narration(bookId))?.overlay;
      } catch (e) {
        debugPrint('[BookOrbit] $bookId: no narration to place the spot on: $e');
        return null;
      }
    }
    if (overlay == null) return null;
    if (fragment != null && fragment.isNotEmpty) {
      final clip = overlay.clipByFragment(fragment, section);
      if (clip != null) {
        final t = overlay.startOf(clip);
        debugPrint('[BookOrbit] $bookId: BookOrbit read aloud to $fragment, ${t.toStringAsFixed(0)}s into the narration');
        return t;
      }
    }
    if (cfi == null || cfi.isEmpty) return null;
    final key = '${_key(bookId)}|$cfi';
    final known = _placedSpots[key];
    if (known != null) return known;
    final place = placeReadingSpot;
    if (place == null) return null;
    double? t;
    try {
      t = await place(bookId, overlay, cfi);
    } catch (e) {
      debugPrint('[BookOrbit] $bookId: reading spot not placed: $e');
    }
    if (t == null) {
      debugPrint('[BookOrbit] $bookId: BookOrbit has only a page here, and it could not be placed on the narration');
      return null;
    }
    _placedSpots[key] = t;
    debugPrint('[BookOrbit] $bookId: BookOrbit read to a page ${t.toStringAsFixed(0)}s into the narration');
    return t;
  }

  /// Saved where BookOrbit's own read along keeps its place: the narration
  /// position on the EPUB, with the sentence it reached.
  Future<int> _putNarrationPosition(String bookId, double seconds) async {
    final ({MediaOverlay overlay, int fileId})? n;
    try {
      n = await _narration(bookId);
    } on _BoHttpError catch (e) {
      return e.status;
    }
    if (n == null) return 404;
    final total = n.overlay.duration;
    final clip = n.overlay.clipAt(seconds);
    try {
      await _boPost('/books/files/${n.fileId}/progress', {
        'percentage': total > 0 ? (seconds / total * 100).clamp(0.0, 100.0) : 0,
        'positionSeconds': math.max(0.0, seconds),
        'mediaOverlayFragment': clip?.textSrc,
        'mediaOverlaySectionIndex': clip?.section,
        'source': 'narration',
      });
      return 200;
    } on _BoHttpError catch (e) {
      debugPrint('[BookOrbit] Narration position for $bookId not saved: ${e.status} ${e.message}');
      return e.status;
    }
  }

  static String _narrationTrackPath(String bookId, int fileId, OverlayTrack track) {
    final path = track.href.split('/').map(Uri.encodeComponent).join('/');
    return '/api/v1/epub/$bookId/media-overlay/file/$path?fileId=$fileId';
  }

  /// Escapes BookOrbit leaves in a narration file's path, since it undoes
  /// them with decodeURI, and then can't find the file under that name: a
  /// comma written %2C is the usual one.
  static final _unservableHref = RegExp(r'%(23|24|26|2B|2C|2F|3A|3B|3D|3F|40)', caseSensitive: false);

  @visibleForTesting
  static bool narrationHrefServable(String href) => !_unservableHref.hasMatch(href);

  Future<Map<String, dynamic>> _startNarrationSession(String bookId, Map<String, dynamic> detail) async {
    final n = await _narration(bookId, detail: detail, fresh: true);
    if (n == null) throw _BoHttpError(404, 'Book has no audiobook assets');
    final overlay = n.overlay;
    final item = BookOrbitMapper.item(detail: detail);
    final media = item['media'] as Map<String, dynamic>;
    final metadata = media['metadata'] as Map<String, dynamic>;
    // Chapters saved with the chapter editor win over the narration's own
    // sections, when they fit its length.
    final edited = BookOrbitMapper.savedChapters(detail, overlay.duration);
    final useEdited = edited.isNotEmpty && (edited.last['start'] as double) < overlay.duration;
    final chapters = useEdited ? edited : overlay.chapters();
    final saved = await _narrationPosition(bookId, n.fileId);
    final current = (saved?.seconds ?? 0).clamp(0.0, overlay.duration).toDouble();
    var tracks = overlay.audioTracks((t) => _narrationTrackPath(bookId, n.fileId, t));
    // Files BookOrbit can't find play out of the EPUB itself, the way an
    // Audiobookshelf narration streams.
    var fromEpub = false;
    if (!overlay.tracks.every((t) => narrationHrefServable(t.href))) {
      final urls = await NarrationStream.instance.serveFromEpub(
          this, bookId, _boUri('/books/files/${n.fileId}/download'), overlay.tracks,
          startTime: current);
      if (urls != null) {
        tracks = overlay.audioTracks((t) => urls[overlay.tracks.indexOf(t)]);
        fromEpub = true;
      }
    }
    media['chapters'] = chapters;
    media['tracks'] = tracks;
    media['duration'] = overlay.duration;
    final now = DateTime.now();
    final sessionId = 'bo-$bookId-${now.millisecondsSinceEpoch}';
    _sessions[sessionId] = _BoListenSession(bookId, _uuid(), now)
      ..fileId = n.fileId
      ..startPercent = overlay.duration > 0 ? (current / overlay.duration * 100).clamp(0.0, 100.0) : null;
    debugPrint('[BookOrbit] narration session for $bookId: ${tracks.length} tracks, '
        '${overlay.clips.length} sentences, ${overlay.duration.toStringAsFixed(0)}s, from ${current.toStringAsFixed(0)}s, '
        '${chapters.length} chapters ${useEdited ? 'saved with the book' : 'from the narration'}'
        '${fromEpub ? ', played out of the EPUB' : ''}');
    return {
      'id': sessionId,
      'userId': '',
      'libraryId': item['libraryId'],
      'libraryItemId': bookId,
      'episodeId': null,
      'mediaType': 'book',
      'mediaMetadata': metadata,
      'chapters': chapters,
      'displayTitle': metadata['title'],
      'displayAuthor': metadata['authorName'],
      'coverPath': media['coverPath'],
      'duration': overlay.duration,
      'playMethod': 0,
      'mediaPlayer': 'exo-player',
      'deviceInfo': _deviceInfo,
      'date': '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}',
      'timeListening': 0,
      'startTime': current,
      'currentTime': current,
      'startedAt': now.millisecondsSinceEpoch,
      'updatedAt': saved?.updatedAt ?? now.millisecondsSinceEpoch,
      'audioTracks': tracks,
      'libraryItem': item,
    };
  }

  Future<Map<String, dynamic>> _startSession(String bookId, Map<String, dynamic> body) async {
    final detail = await _detail(bookId, fresh: true);
    final manifest = await _manifest(bookId, fresh: true);
    if (manifest == null) return _startNarrationSession(bookId, detail);
    final state = await _playbackState(bookId);
    final item = BookOrbitMapper.item(detail: detail, manifest: manifest);
    final media = item['media'] as Map<String, dynamic>;
    final metadata = media['metadata'] as Map<String, dynamic>;
    final current = state == null ? 0.0 : BookOrbitMapper.absolutePosition(manifest, state);
    final now = DateTime.now();
    final sessionId = 'bo-$bookId-${now.millisecondsSinceEpoch}';
    final assets = (manifest['assets'] as List<dynamic>).whereType<Map<String, dynamic>>().toList();
    _sessions[sessionId] = _BoListenSession(bookId, _uuid(), now)
      ..fileId = assets.isEmpty ? null : (assets.first['fileId'] as num?)?.toInt()
      ..startPercent = BookOrbitMapper.totalSeconds(manifest) > 0
          ? (current / BookOrbitMapper.totalSeconds(manifest) * 100).clamp(0.0, 100.0)
          : null;
    return {
      'id': sessionId,
      'userId': '',
      'libraryId': item['libraryId'],
      'libraryItemId': bookId,
      'episodeId': null,
      'mediaType': 'book',
      'mediaMetadata': metadata,
      'chapters': media['chapters'],
      'displayTitle': metadata['title'],
      'displayAuthor': metadata['authorName'],
      'coverPath': media['coverPath'],
      'duration': media['duration'],
      'playMethod': 0,
      'mediaPlayer': 'exo-player',
      'deviceInfo': _deviceInfo,
      'date': '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}',
      'timeListening': 0,
      'startTime': current,
      'currentTime': current,
      'startedAt': now.millisecondsSinceEpoch,
      'updatedAt': BookOrbitMapper.ms(state?['capturedAt']) ?? now.millisecondsSinceEpoch,
      'audioTracks': media['tracks'],
      'libraryItem': item,
    };
  }

  _BoListenSession? _sessionFor(String sessionId) {
    final existing = _sessions[sessionId];
    if (existing != null) return existing;
    final m = RegExp(r'^bo-(\d+)-(\d+)$').firstMatch(sessionId);
    if (m == null) return null;
    final started = DateTime.fromMillisecondsSinceEpoch(int.parse(m.group(2)!));
    return _sessions[sessionId] = _BoListenSession(m.group(1)!, _uuid(), started);
  }

  Future<void> _checkpoint(_BoListenSession s, {DateTime? endedAt}) async {
    final seconds = s.listenedSeconds.round();
    if (seconds < 10) return;
    var fileId = s.fileId;
    if (fileId == null) {
      final manifest = await _manifest(s.bookId);
      final assets = (manifest?['assets'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>();
      fileId = assets.isEmpty ? null : (assets.first['fileId'] as num?)?.toInt();
      if (manifest == null) {
        try {
          fileId = (await _narration(s.bookId))?.fileId;
        } catch (_) {}
      }
      s.fileId = fileId;
    }
    if (fileId == null) return;
    final end = endedAt ?? DateTime.now();
    final span = end.difference(s.startedAt).inSeconds;
    final source = _platformSource();
    try {
      await _boPost('/books/files/$fileId/sessions', {
        'sessionId': s.sessionUuid,
        'startedAt': _iso(s.startedAt),
        'endedAt': _iso(end),
        'durationSeconds': span < seconds ? math.max(span, 0) : seconds,
        if (s.startPercent != null && s.lastPercent != null)
          'progressDelta': double.parse((s.lastPercent! - s.startPercent!).toStringAsFixed(4)),
        if (s.lastPercent != null) 'endProgress': s.lastPercent!.clamp(0.0, 100.0),
        'sessionType': 'listen',
        if (source != null) 'source': source,
        ...await _clientName(),
      });
      if (!s.deviceRemembered) {
        s.deviceRemembered = true;
        await _rememberSessionDevice(s.bookId, _iso(s.startedAt));
      }
    } catch (e) {
      debugPrint('[BookOrbit] Listening session checkpoint failed: $e');
    }
  }

  /// BookOrbit keeps a platform tag on each session but no device, so the
  /// sessions this phone recorded are remembered here to name them later.
  static const _sessionDevicesKey = 'bookorbit_session_devices';

  /// The same list for the paired watch's sessions, kept up to date by
  /// WearSessionListenerService from what the watch publishes.
  static const _watchSessionsKey = 'bookorbit_watch_sessions';

  static String _thisDevice() {
    final name = [ApiService.deviceManufacturer, ApiService.deviceModel]
        .where((s) => s.isNotEmpty)
        .join(' ');
    return name.isEmpty ? 'Absorb' : name;
  }

  Future<void> _rememberSessionDevice(String bookId, String startedAtIso) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final raw = prefs.getString(_sessionDevicesKey);
      final map = raw == null ? <String, dynamic>{} : jsonDecode(raw) as Map<String, dynamic>;
      map['$bookId@$startedAtIso'] = _thisDevice();
      while (map.length > 500) {
        map.remove(map.keys.first);
      }
      await prefs.setString(_sessionDevicesKey, jsonEncode(map));
    } catch (_) {}
  }

  static String _sourceLabel(Object? source) => switch (source) {
        'android' => 'Android',
        'ios' => 'iOS',
        'watchos' => 'Apple Watch',
        'web' => 'BookOrbit web',
        'koreader' => 'KOReader',
        'kobo' => 'Kobo',
        'manual' => 'Manual entry',
        _ => 'BookOrbit',
      };

  Future<http.Response> _syncSession(String sessionId, Map<String, dynamic> body) async {
    final s = _sessionFor(sessionId);
    if (s == null) return _status(404, 'Unknown session');
    final currentTime = (body['currentTime'] as num?)?.toDouble();
    final listened = (body['timeListened'] as num?)?.toDouble() ?? 0;
    if (listened > 0) s.listenedSeconds += listened;
    var status = 200;
    if (currentTime != null) {
      status = await _putPosition(s.bookId, currentTime);
      final manifest = _manifests[_key(s.bookId)];
      final total = manifest == null
          ? (_narrations[_key(s.bookId)]?.overlay.duration ?? 0.0)
          : BookOrbitMapper.totalSeconds(manifest);
      if (total > 0) {
        s.lastPercent = (currentTime / total * 100).clamp(0.0, 100.0);
        s.startPercent ??= s.lastPercent;
      }
    }
    await _checkpoint(s);
    return status == 200 ? _json(const <String, dynamic>{}) : _status(status, 'Sync failed');
  }

  Future<void> _closeSession(String sessionId, Map<String, dynamic> body) async {
    final s = _sessions.remove(sessionId);
    if (s == null) return;
    final currentTime = (body['currentTime'] as num?)?.toDouble();
    if (currentTime != null) await _putPosition(s.bookId, currentTime);
    await _checkpoint(s);
  }

  /// An offline listen from the app's own session log: the position (only if
  /// nothing newer reached the server since) and the listening time.
  Future<Map<String, dynamic>> _localSession(Map<String, dynamic> session) async {
    final bookId = '${session['libraryItemId'] ?? ''}';
    if (bookId.isEmpty || session['episodeId'] != null) return const {};
    // BookOrbit books have number ids; anything else is another server's
    // book that was played here.
    if (int.tryParse(bookId) == null) {
      debugPrint('[BookOrbit] Skipped a session for $bookId: not a book on this server');
      return const {};
    }
    final updated = (session['updatedAt'] as num?)?.toInt();
    final when = updated == null ? DateTime.now() : DateTime.fromMillisecondsSinceEpoch(updated);
    final currentTime = (session['currentTime'] as num?)?.toDouble();
    if (currentTime != null) await _putPosition(bookId, currentTime, capturedAt: when);
    final started = (session['startedAt'] as num?)?.toInt();
    final listened = (session['timeListening'] as num?)?.toDouble() ?? 0;
    if (listened >= 10) {
      final rawId = '${session['id'] ?? _uuid()}';
      final s = _BoListenSession(
        bookId,
        rawId.length > 64 ? rawId.substring(0, 64) : rawId,
        started == null ? when.subtract(Duration(seconds: listened.round())) : DateTime.fromMillisecondsSinceEpoch(started),
      )..listenedSeconds = listened;
      final manifest = _manifests[_key(bookId)] ?? await _manifest(bookId);
      var total = manifest == null ? 0.0 : BookOrbitMapper.totalSeconds(manifest);
      // A narrated EPUB has no audiobook; its length is the narration's.
      // Without one the session went up with no start or end point.
      if (manifest == null) {
        try {
          total = (await _narration(bookId))?.overlay.duration ?? 0.0;
        } catch (_) {}
      }
      final startTime = (session['startTime'] as num?)?.toDouble();
      if (total > 0 && currentTime != null) s.lastPercent = (currentTime / total * 100).clamp(0.0, 100.0);
      if (total > 0 && startTime != null) s.startPercent = (startTime / total * 100).clamp(0.0, 100.0);
      await _checkpoint(s, endedAt: when);
    }
    return {'id': session['id']};
  }

  @override
  Future<Map<String, dynamic>?> startEpisodePlaybackSession(String itemId, String episodeId,
          {bool forceTranscode = false}) async =>
      null;

  Future<List<Map<String, dynamic>>> _rawBookmarks(String bookId) async {
    try {
      final list = await _boGet('/audiobooks/$bookId/bookmarks') as List<dynamic>;
      return list.whereType<Map<String, dynamic>>().toList();
    } on _BoHttpError catch (e) {
      if (e.status == 404 || e.status == 400) return const [];
      rethrow;
    }
  }

  Future<List<Map<String, dynamic>>> _bookmarksFor(String bookId) async =>
      (await _rawBookmarks(bookId)).map(BookOrbitMapper.bookmark).toList();

  Future<List<Map<String, dynamic>>> _recentBookmarks() async {
    final ids = <String>{};
    try {
      ids.addAll((await _shelfCards('continue-listening', 50)).map((c) => '${c['id']}'));
    } catch (_) {}
    final lists = await _pool(ids.map((id) => () async {
          try {
            return await _bookmarksFor(id);
          } catch (_) {
            return <Map<String, dynamic>>[];
          }
        }).toList());
    return lists.expand((l) => l).toList();
  }

  Future<Map<String, dynamic>> _createBookmark(String bookId, Map<String, dynamic> body) async {
    final time = (body['time'] as num?)?.toDouble() ?? 0;
    final title = '${body['title'] ?? ''}'.trim();
    final created = await _boPost('/audiobooks/$bookId/bookmarks', {
      'clientId': _uuid(),
      'positionMs': (time * 1000).round(),
      'title': title.isEmpty ? 'Bookmark' : (title.length > 500 ? title.substring(0, 500) : title),
    }) as Map<String, dynamic>;
    return BookOrbitMapper.bookmark(created);
  }

  Future<Map<String, dynamic>?> _findBookmark(String bookId, double time) async {
    Map<String, dynamic>? best;
    var bestGap = 1.0;
    for (final b in await _rawBookmarks(bookId)) {
      final gap = (((b['positionMs'] as num?) ?? 0) / 1000.0 - time).abs();
      if (gap < bestGap) {
        best = b;
        bestGap = gap;
      }
    }
    return best;
  }

  Future<bool> _updateBookmark(String bookId, Map<String, dynamic> body) async {
    final b = await _findBookmark(bookId, (body['time'] as num?)?.toDouble() ?? -1);
    if (b == null) return false;
    final title = '${body['title'] ?? ''}'.trim();
    if (title.isEmpty) return true;
    await _boPatch('/audiobooks/$bookId/bookmarks/${b['id']}', {'title': title});
    return true;
  }

  Future<bool> _deleteBookmark(String bookId, double time) async {
    final b = await _findBookmark(bookId, time);
    if (b == null) return false;
    await _boDelete('/audiobooks/$bookId/bookmarks/${b['id']}');
    return true;
  }

  /// The Stats screen's numbers in Audiobookshelf's shape, plus a
  /// `bookOrbit` block with what only BookOrbit keeps: listening and reading
  /// apart, time of day, where the time was spent, books finished by month,
  /// and session habits. Every year with activity is read, so totals and
  /// streaks reach back past January.
  Future<Map<String, dynamic>> _listeningStats() async {
    const wait = Duration(seconds: 45);
    final overview = await _boGet('/user-statistics/activity-overview', null, wait) as Map<String, dynamic>;
    final calendar = overview['calendar'] as Map? ?? const {};
    final thisYear = (calendar['year'] as num?)?.toInt();
    final otherYears = [
      for (final y in (calendar['availableYears'] as List<dynamic>? ?? const []))
        if (y is num && y.toInt() != thisYear) y.toInt(),
    ]..sort((a, b) => b.compareTo(a));
    Future<Map<String, dynamic>?> optional(String path) async {
      try {
        return await _boGet(path, null, wait) as Map<String, dynamic>;
      } catch (e) {
        debugPrint('[BookOrbit] Stats: $path failed: $e');
        return null;
      }
    }

    final extra = await Future.wait([
      optional('/user-statistics/activity-details/genre-time'),
      optional('/user-statistics/summary'),
      optional('/user-statistics/activity-details/completion-speed'),
      for (final y in otherYears.take(10)) optional('/user-statistics/activity-calendar/$y'),
    ]);
    final genreTime = extra[0], summary = extra[1], speed = extra[2];

    final total = <String, num>{}, listen = <String, num>{}, read = <String, num>{};
    void addDays(Object? list) {
      for (final d in (list as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
        final day = d['day'] as String?;
        if (day == null) continue;
        final l = (d['listeningSeconds'] as num?) ?? 0;
        final r = (d['readingSeconds'] as num?) ?? 0;
        final t = (d['totalSeconds'] as num?) ?? l + r;
        if (l > 0) listen[day] = l;
        if (r > 0) read[day] = r;
        if (t > 0) total[day] = t;
      }
    }

    for (final cal in extra.skip(3)) {
      addDays(cal?['days']);
    }
    addDays(calendar['days']);
    addDays((overview['dailyActivity'] as Map?)?['days']);

    final items = <String, dynamic>{};
    final genres = <Map<String, dynamic>>[];
    for (final g in (genreTime?['genres'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      genres.add({'genre': g['genre'], 'time': g['totalSeconds'] ?? 0});
      for (final a in (g['authors'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
        for (final b in (a['books'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
          final id = '${b['bookId']}';
          final prev = (items[id] as Map?)?['timeListening'] as num? ?? 0;
          items[id] = {
            'id': id,
            'timeListening': prev + ((b['totalSeconds'] as num?) ?? 0),
            'mediaMetadata': {'title': b['title'], 'authorName': a['author']},
          };
        }
      }
    }

    final rhythm = overview['rhythm'] as Map? ?? const {};
    final pace = overview['pace'] as Map? ?? const {};
    num? paceFor(String bucket) => (pace['byMedia'] as List<dynamic>? ?? const [])
        .whereType<Map>()
        .where((m) => m['bucket'] == bucket)
        .map((m) => m['medianDurationSeconds'] as num?)
        .firstOrNull;
    return {
      'totalTime': total.values.fold<num>(0, (sum, v) => sum + v),
      'items': items,
      'days': total,
      'today': ((overview['snapshot'] as Map?)?['today'] as Map?)?['totalSeconds'] as num? ?? 0,
      'recentSessions': const [],
      'bookOrbit': {
        'timezone': overview['timezone'],
        'listenDays': listen,
        'readDays': read,
        'hours': [
          for (final h in (rhythm['hours'] as List<dynamic>? ?? const []).whereType<Map>())
            {
              'hour': h['hour'],
              'listening': h['listeningSeconds'] ?? 0,
              'reading': h['readingSeconds'] ?? 0,
            },
        ],
        'peakHour': rhythm['peakHour'],
        'favoriteDay': rhythm['favoriteDayOfWeek'],
        'sources': [
          for (final s in ((overview['sources'] as Map?)?['slices'] as List<dynamic>? ?? const []).whereType<Map>())
            if (((s['totalSeconds'] as num?) ?? 0) > 0) {'bucket': s['bucket'], 'time': s['totalSeconds']},
        ],
        'finishedMonths': [
          for (final m in ((overview['completion'] as Map?)?['months'] as List<dynamic>? ?? const []).whereType<Map>())
            {'year': m['year'], 'month': m['month'], 'count': m['count'] ?? 0},
        ],
        'genres': genres,
        'medianSession': pace['medianDurationSeconds'],
        'medianListen': paceFor('listening'),
        'medianRead': paceFor('reading'),
        'medianProgress': pace['medianProgressDelta'],
        'medianDaysToFinish': speed?['medianDays'],
        'started': summary?['startedBooks'],
        'inProgress': summary?['inProgressBooks'],
        'completed': summary?['completedBooks'],
        'meanProgress': summary?['meanProgressPercent'],
        'goalBooks': (overview['goal'] as Map?)?['goalBooks'],
      },
    };
  }

  /// One day's sessions as BookOrbit lists them. Today keeps changing, so it
  /// is asked again sooner than past days.
  Future<Map<String, dynamic>> _activityDay(String day) {
    final now = DateTime.now();
    final today = day == _dayKey(now) || day == _dayKey(now.toUtc());
    return _cached('activity-day-$day', Duration(minutes: today ? 1 : 10), () async =>
        await _boGet('/user-statistics/activity-days/$day', null, const Duration(seconds: 30)) as Map<String, dynamic>);
  }

  static String _dayKey(DateTime d) =>
      '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';

  /// The device behind each session this phone or its watch recorded,
  /// keyed `bookId@startedAt`, as the deviceInfo the Stats screen reads.
  Future<Map<String, Map<String, String>>> _sessionDevices() async {
    final out = <String, Map<String, String>>{};
    try {
      final prefs = await SharedPreferences.getInstance();
      for (final (key, client) in [(_sessionDevicesKey, 'Absorb'), (_watchSessionsKey, 'AbsorbWear')]) {
        final raw = prefs.getString(key);
        if (raw == null) continue;
        for (final e in (jsonDecode(raw) as Map<String, dynamic>).entries) {
          out[e.key] = {'clientName': client, 'deviceName': '${e.value}'};
        }
      }
    } catch (_) {}
    return out;
  }

  /// A session from an activity day in the Stats screen's session shape.
  Map<String, dynamic> _activitySession(
      Map<String, dynamic> s, Map<String, dynamic> items, Map<String, Map<String, String>> devices) {
    final bookId = '${s['bookId']}';
    final meta = (items[bookId] as Map?)?['mediaMetadata'] as Map?;
    final title = s['bookTitle'] as String? ?? meta?['title'] as String?;
    final author = meta?['authorName'] as String?;
    final reading = s['mediaBucket'] == 'reading';
    final seconds = ((s['durationOnDaySeconds'] as num?) ?? 0).round();
    final started = DateTime.tryParse(s['startedAt'] as String? ?? '')?.toLocal();
    final ownDevice = devices['$bookId@${s['startedAt']}'];
    return {
      'id': 'bo-session-${s['id']}',
      'libraryItemId': bookId,
      'episodeId': null,
      'mediaType': 'book',
      'displayTitle': title,
      'displayAuthor': author,
      'mediaMetadata': {'title': title, 'authorName': author},
      'timeListening': seconds,
      'startedAt': BookOrbitMapper.ms(s['startedAt']),
      'updatedAt': BookOrbitMapper.ms(s['endedAt']),
      'boEndedAt': BookOrbitMapper.ms(s['endedAt']),
      'boSeconds': seconds,
      'boFileId': s['bookFileId'],
      'boReading': reading,
      'date': started == null ? null : _dayKey(started),
      'deviceInfo': ownDevice ?? {'clientName': _sourceLabel(s['sourceBucket'])},
      'mediaPlayer': reading ? ApiService.readingMediaPlayer : (s['sourceBucket'] ?? 'web'),
    };
  }

  /// Sessions across every book, newest first. BookOrbit lists sessions by
  /// day rather than overall, so the days with any activity are read newest
  /// first until the page is full. A session that runs past midnight shows
  /// on both days and is put back together, which can take one more day.
  Future<Map<String, dynamic>> _recentSessions(int page, int perPage) async {
    final stats = await _cached('listening-stats', const Duration(minutes: 5), _listeningStats);
    final days = [...((stats['days'] as Map?)?.keys.cast<String>() ?? const <String>[])]
      ..sort((a, b) => b.compareTo(a));
    final want = (page + 1) * perPage;
    final merged = <Object?, Map<String, dynamic>>{};
    List<Map<String, dynamic>> newestFirst() =>
        merged.values.toList()..sort((a, b) => '${b['startedAt']}'.compareTo('${a['startedAt']}'));
    bool cutAtMidnight(Map<String, dynamic> s) {
      final start = DateTime.tryParse(s['startedAt'] as String? ?? '');
      final end = DateTime.tryParse(s['endedAt'] as String? ?? '');
      if (start == null || end == null) return false;
      return ((s['durationOnDaySeconds'] as num?) ?? 0) < end.difference(start).inSeconds - 60;
    }

    var next = 0, extraDays = 0;
    while (next < days.length) {
      final sorted = newestFirst();
      final full = sorted.length >= want;
      if (full && (extraDays >= 2 || !sorted.take(want).any(cutAtMidnight))) break;
      if (full) extraDays++;
      final batch = days.sublist(next, math.min(next + (full ? 1 : 4), days.length));
      next += batch.length;
      for (final day in await Future.wait(batch.map(_activityDay))) {
        for (final s in (day['sessions'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
          final prev = merged[s['id']];
          if (prev == null) {
            merged[s['id']] = Map.of(s);
          } else {
            prev['durationOnDaySeconds'] =
                ((prev['durationOnDaySeconds'] as num?) ?? 0) + ((s['durationOnDaySeconds'] as num?) ?? 0);
          }
        }
      }
    }
    final items = stats['items'] as Map<String, dynamic>? ?? const {};
    final devices = await _sessionDevices();
    final sessions = [
      for (final s in newestFirst().skip(page * perPage).take(perPage)) _activitySession(s, items, devices),
    ];
    return {
      'sessions': sessions,
      'page': page,
      'itemsPerPage': perPage,
    };
  }

  @override
  Future<List<Map<String, dynamic>>?> getListeningSessionsForDay(DateTime day) async {
    try {
      final key = _dayKey(day);
      final res = await _activityDay(key);
      Map<String, dynamic> items = const {};
      try {
        items = (await _cached('listening-stats', const Duration(minutes: 5), _listeningStats))['items']
                as Map<String, dynamic>? ??
            const {};
      } catch (_) {}
      final devices = await _sessionDevices();
      return [
        for (final s in (res['sessions'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>())
          {..._activitySession(s, items, devices), 'date': key},
      ]..sort((a, b) => ((b['updatedAt'] as num?) ?? 0).compareTo((a['updatedAt'] as num?) ?? 0));
    } catch (e) {
      debugPrint('[BookOrbit] Sessions for $day failed: $e');
      return null;
    }
  }

  /// BookOrbit merges settings, so only the zone is sent. It redoes the
  /// account's past days in the new zone on its own, which can take a while
  /// on a long history.
  @override
  Future<bool> setAccountTimeZone(String zone) async {
    try {
      await _boPatch('/users/me/settings', {
        'settings': {'timezone': zone},
      });
      _forgetListeningStats();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Setting the time zone to $zone failed: $e');
      return false;
    }
  }

  /// The account's own settings, as /auth/me returns them.
  Future<Map<String, dynamic>> _mySettings({bool fresh = false}) async {
    if (fresh) _recent.remove(_key('auth-me'));
    final me = await _cached('auth-me', const Duration(seconds: 30),
        () async => await _boGet('/auth/me') as Map<String, dynamic>);
    final settings = me['settings'];
    return settings is Map ? Map<String, dynamic>.from(settings) : <String, dynamic>{};
  }

  @override
  Future<bool> hasServerNotifications() async =>
      await _can('notification_access') && !_demoRestricted;

  @override
  Future<({List<ServerNotification> items, int total})?> serverNotifications({int limit = 20, int offset = 0}) async {
    try {
      final res = await _boGet('/notifications', {'limit': '$limit', 'offset': '$offset'}) as Map<String, dynamic>;
      return (
        items: [
          for (final raw in (res['items'] as List? ?? const []))
            if (ServerNotification.fromJson(raw) case final n?) n,
        ],
        total: (res['total'] as num?)?.toInt() ?? 0,
      );
    } catch (e) {
      debugPrint('[BookOrbit] Notifications failed: $e');
      return null;
    }
  }

  @override
  Future<int?> unreadNotificationCount() async {
    try {
      return ((await _boGet('/notifications/unread-count') as Map)['count'] as num?)?.toInt();
    } catch (e) {
      debugPrint('[BookOrbit] Unread notification count failed: $e');
      return null;
    }
  }

  Future<bool> _notificationCall(String what, Future<void> Function() call) async {
    try {
      await call();
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] $what failed: $e');
      return false;
    }
  }

  @override
  Future<bool> markNotificationRead(int id) =>
      _notificationCall('Marking notification $id read', () => _boPatch('/notifications/$id/read', const {}));

  @override
  Future<bool> markAllNotificationsRead() =>
      _notificationCall('Marking all notifications read', () => _boPatch('/notifications/read-all', const {}));

  @override
  Future<bool> dismissNotification(int id) =>
      _notificationCall('Dismissing notification $id', () => _boDelete('/notifications/$id'));

  @override
  Future<bool> clearNotifications() =>
      _notificationCall('Clearing notifications', () => _boDelete('/notifications'));

  @override
  Future<Map<String, String>?> notificationLevels() async {
    try {
      final stored = (await _mySettings(fresh: true))['notificationPreferences'];
      return {
        for (final category in notificationCategoryGroups.values.expand((c) => c))
          category: resolveNotificationLevel(stored is Map ? stored[category] : null),
      };
    } catch (e) {
      debugPrint('[BookOrbit] Notification settings failed: $e');
      return null;
    }
  }

  @override
  Future<bool> setNotificationLevels(Map<String, String> levels) async {
    try {
      final stored = (await _mySettings(fresh: true))['notificationPreferences'];
      await _boPatch('/users/me/settings', {
        'settings': {
          'notificationPreferences': {
            if (stored is Map) ...stored,
            ...levels,
          },
        },
      });
      _recent.remove(_key('auth-me'));
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Saving notification settings failed: $e');
      return false;
    }
  }

  @override
  Future<bool?> achievementsEnabled() async {
    try {
      final prefs = (await _mySettings(fresh: true))['achievementPreferences'];
      return !(prefs is Map && prefs['enabled'] == false);
    } catch (e) {
      debugPrint('[BookOrbit] Achievement setting failed: $e');
      return null;
    }
  }

  @override
  Future<bool> setAchievementsEnabled(bool enabled) async {
    try {
      await _boPatch('/users/me/settings', {
        'settings': {
          'achievementPreferences': {'enabled': enabled},
        },
      });
      _recent.remove(_key('auth-me'));
      _recent.remove(_key('achievements'));
      return true;
    } catch (e) {
      debugPrint('[BookOrbit] Turning achievements ${enabled ? 'on' : 'off'} failed: $e');
      return false;
    }
  }

  @override
  Future<AchievementCatalogue?> achievements({bool fresh = false}) async {
    try {
      // Someone who switched achievements off in BookOrbit doesn't see them
      // there either.
      final prefs = (await _mySettings(fresh: fresh))['achievementPreferences'];
      if (prefs is Map && prefs['enabled'] == false) return null;
      if (fresh) _recent.remove(_key('achievements'));
      return await _cached('achievements', const Duration(minutes: 5), () async =>
          AchievementCatalogue.fromJson(await _boGet('/achievements', null, const Duration(seconds: 30)) as Map<String, dynamic>));
    } catch (e) {
      debugPrint('[BookOrbit] Achievements failed: $e');
      return null;
    }
  }

  @override
  Future<List<AchievementHint>> achievementHints() async {
    try {
      final res = await _boGet('/achievements/hints', null, const Duration(seconds: 30)) as Map<String, dynamic>;
      return [
        for (final raw in (res['hints'] as List? ?? const []))
          if (AchievementHint.fromJson(raw) case final h?) h,
      ];
    } catch (e) {
      debugPrint('[BookOrbit] Achievement hints failed: $e');
      return const [];
    }
  }

  /// Year in Review from that year's activity calendar and finished books.
  /// BookOrbit keeps no per-book totals by year, so the books listened, top
  /// authors and narrator are left out.
  Future<Map<String, dynamic>> _yearStats(int year) async {
    final now = DateTime.now();
    final Map<String, dynamic> cal;
    try {
      cal = await _boGet('/user-statistics/activity-calendar/$year', null, const Duration(seconds: 30))
          as Map<String, dynamic>;
    } on _BoHttpError catch (e) {
      // Asked for a year before the first one with any activity.
      if (e.status == 400) return const {};
      rethrow;
    }
    num listen = 0, read = 0, sessions = 0;
    var activeDays = 0;
    final byMonth = List<num>.filled(12, 0);
    for (final d in (cal['days'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>()) {
      final l = (d['listeningSeconds'] as num?) ?? 0;
      final r = (d['readingSeconds'] as num?) ?? 0;
      listen += l;
      read += r;
      sessions += (d['sessionsCount'] as num?) ?? 0;
      if (l + r > 0) activeDays++;
      final month = DateTime.tryParse(d['day'] as String? ?? '')?.month;
      if (month != null) byMonth[month - 1] += l + r;
    }
    var finished = 0;
    try {
      final days = (now.difference(DateTime(year)).inDays + 1).clamp(1, 3650);
      final months = await _boGet('/user-statistics/completion-timeline', {'days': days}) as List<dynamic>;
      for (final m in months.whereType<Map>()) {
        if (m['year'] == year) finished += ((m['count'] as num?) ?? 0).toInt();
      }
    } catch (e) {
      debugPrint('[BookOrbit] Finished books for $year failed: $e');
    }
    var topMonth = -1;
    for (var i = 0; i < 12; i++) {
      if (byMonth[i] > 0 && (topMonth < 0 || byMonth[i] > byMonth[topMonth])) topMonth = i;
    }
    return {
      'totalListeningTime': listen,
      'bookOrbitReadingTime': read,
      'bookOrbitActiveDays': activeDays,
      'totalListeningSessions': sessions,
      'numBooksFinished': finished,
      if (topMonth >= 0) 'mostListenedMonth': {'month': topMonth},
    };
  }

  /// One page of a book's reading log, the way BookOrbit's Reading Log tab
  /// reads it: every kind of session (reading, listening, any device) plus a
  /// `stats` summary of all of them under the same filters.
  Future<Map<String, dynamic>> readingLog(
    String bookId, {
    int page = 1,
    int pageSize = 25,
    String sortBy = 'startedAt',
    bool descending = true,
    DateTime? from,
    String? format,
  }) async =>
      await _boGet('/books/$bookId/sessions', {
        'page': page,
        'pageSize': pageSize,
        'sortBy': sortBy,
        'sortDir': descending ? 'desc' : 'asc',
        if (from != null) 'dateFrom': _iso(from),
        if (format != null) 'format': format,
      }) as Map<String, dynamic>;

  Future<List<Map<String, dynamic>>> readingAttempts(String bookId) async {
    final res = await _boGet('/books/$bookId/reading-attempts', {'page': 1, 'pageSize': 50}) as Map<String, dynamic>;
    return (res['items'] as List<dynamic>? ?? const []).whereType<Map<String, dynamic>>().toList();
  }

  Future<Map<String, dynamic>> _itemListeningSessions(String bookId, Map<String, String> q) async {
    final perPage = (int.tryParse(q['itemsPerPage'] ?? '') ?? 100).clamp(1, 100);
    final page = int.tryParse(q['page'] ?? '') ?? 0;
    final res = await _boGet('/books/$bookId/sessions', {
      'page': page + 1,
      'pageSize': perPage,
      'sortBy': 'startedAt',
      'sortDir': 'desc',
    }) as Map<String, dynamic>;
    final total = (res['total'] as num?)?.toInt() ?? 0;
    Map<String, dynamic>? manifest;
    try {
      manifest = await _manifest(bookId);
    } catch (_) {}
    // A narrated EPUB with no audiobook: reading and listening both happen in
    // the one file, so every session on it is this book's, timed against the
    // narration.
    Map? narration;
    if (manifest == null) {
      try {
        narration = (BookOrbitMapper.item(detail: await _detail(bookId))['media'] as Map)['narration'] as Map?;
      } catch (_) {}
    }
    final bookSeconds = manifest != null
        ? BookOrbitMapper.totalSeconds(manifest)
        : ((narration?['duration'] as num?)?.toDouble() ?? 0.0);
    // Session rows carry the book's own title and author, as Audiobookshelf's do.
    final book = manifest?['book'] as Map?;
    var title = book?['title'] as String?;
    var author = (book?['authors'] as List<dynamic>?)?.map((a) => '$a').join(', ');
    if (title == null) {
      try {
        final d = await _detail(bookId);
        title = d['title'] as String?;
        author = (d['authors'] as List<dynamic>? ?? const [])
            .map((a) => a is Map ? '${a['name'] ?? ''}' : '$a')
            .where((a) => a.isNotEmpty)
            .join(', ');
      } catch (_) {}
    }
    final mine = await _sessionDevices();
    final sessions = (res['items'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        // Reading the ebook of the same book is not listening, unless the
        // ebook is what reads it aloud.
        .where((s) =>
            narration != null ||
            s['format'] == null ||
            s['sessionType'] == 'listen' ||
            BookOrbitMapper.isAudioFormat(s['format'] as String?))
        .map((s) {
      final started = DateTime.tryParse(s['startedAt'] as String? ?? '')?.toLocal();
      final endPct = (s['endProgress'] as num?)?.toDouble();
      final deltaPct = (s['progressDelta'] as num?)?.toDouble();
      final endAt = endPct != null && bookSeconds > 0 ? endPct / 100 * bookSeconds : null;
      final startAt = endAt != null && deltaPct != null
          ? ((endPct! - deltaPct) / 100 * bookSeconds).clamp(0.0, bookSeconds)
          : endAt;
      final ownDevice = mine['$bookId@${s['startedAt']}'];
      return {
        'id': 'bo-session-${s['id']}',
        'libraryItemId': bookId,
        'episodeId': null,
        'mediaType': 'book',
        'displayTitle': title,
        'displayAuthor': author,
        'mediaMetadata': {'title': title, 'authorName': author},
        if (bookSeconds > 0) 'duration': bookSeconds,
        'timeListening': s['durationSeconds'] ?? 0,
        if (startAt != null) 'startTime': startAt,
        if (endAt != null) 'currentTime': endAt,
        'startedAt': BookOrbitMapper.ms(s['startedAt']),
        'updatedAt': BookOrbitMapper.ms(s['endedAt']),
        'boEndedAt': BookOrbitMapper.ms(s['endedAt']),
        'boSeconds': s['durationSeconds'] ?? 0,
        'boFileId': s['bookFileId'],
        'date': started == null
            ? null
            : '${started.year}-${started.month.toString().padLeft(2, '0')}-${started.day.toString().padLeft(2, '0')}',
        'deviceInfo': ownDevice ?? {'clientName': _sourceLabel(s['source'])},
        'mediaPlayer': s['source'] ?? 'web',
      };
    }).toList();
    return {
      'sessions': sessions,
      'total': total,
      'numPages': total == 0 ? 1 : (total / perPage).ceil(),
      'page': page,
      'itemsPerPage': perPage,
    };
  }
}