import 'package:result_monad/result_monad.dart';

import '../../models/exec_error.dart';
import '../../models/friendica_version.dart';
import '../../models/instance_info.dart';

const _defaultMaxImageBytes = 819200;
const _defaultMaxCharacters = 4000;

Result<InstanceInfo, ExecError> fromInstanceV1Json(Map<String, dynamic> json) {
  return runCatching(() {
    final maxStatusCharacters = json['max_toot_chars'] ?? _defaultMaxCharacters;
    final versionString = json['version'];
    return Result.ok(InstanceInfo(
      friendicaVersion: FriendicaVersion.fromMastodonVersionString(
        versionString,
      ),
      maxStatusCharacters: maxStatusCharacters,
      versionString: versionString,
      maxImageBytes: _defaultMaxImageBytes,
    ));
  }).execErrorCast();
}

Result<InstanceInfo, ExecError> fromInstanceV2Json(Map<String, dynamic> json) {
  return runCatching(() {
    final maxStatusCharacters = json['configuration']?['statuses']
            ?['max_characters'] ??
        _defaultMaxCharacters;
    final maxImageBytes = json['configuration']?['media_attachments']
            ?['image_size_limit'] ??
        _defaultMaxImageBytes;
    final versionString =
        json['friendica']?['version'] ?? 'Not a friendica server';
    final version = FriendicaVersion.fromVersionString(versionString);
    return Result.ok(InstanceInfo(
      friendicaVersion: version,
      maxStatusCharacters: maxStatusCharacters,
      versionString: versionString,
      maxImageBytes: maxImageBytes,
    ));
  }).execErrorCast();
}
