import 'dart:convert';
import 'dart:io';

import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/app_base_request.dart';

import '../../base/base_response.dart';
import '../../di/get_it.dart';
import '../../utils/async_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/http_handler.dart';
import '../../utils/sse_parse_util.dart';
import '../api/atmob_api.dart';
import '../api/atmob_stream_api.dart';
import '../api/request/intimacy_analyze_request.dart';
import '../api/request/intimacy_generate_character_request.dart';
import '../api/request/intimacy_reply_analyze_request.dart';
import '../api/request/intimacy_reply_chat_request.dart';
import '../api/response/intimacy_analyze_chat_config_response.dart';
import '../api/response/intimacy_analyze_config_response.dart';
import '../api/response/intimacy_analyze_reply_config_response.dart';
import '../api/response/intimacy_analyze_response.dart';
import '../api/response/intimacy_chat_analyze_response.dart';
import '../api/response/intimacy_reply_analyze_response.dart';

/// 亲密度分析Repository层
@LazySingleton()
class IntimacyAnalyzeRepository {
  final String tag = "IntimacyAnalyzeRepository";

  final AtmobApi atmobApi;
  final AtmobStreamApi atmobStreamApi;

  /// 亲密度配置
  Rxn<IntimacyAnalyzeConfigResponse> intimacyAnalyzeConfig =
      Rxn<IntimacyAnalyzeConfigResponse>();

  /// 对话分析配置
  Rxn<IntimacyAnalyzeChatConfigResponse> intimacyAnalyzeChatConfig =
      Rxn<IntimacyAnalyzeChatConfigResponse>();

  /// 识图回复配置
  Rxn<IntimacyAnalyzeReplyConfigResponse> intimacyAnalyzeReplyConfig =
      Rxn<IntimacyAnalyzeReplyConfigResponse>();

  IntimacyAnalyzeRepository(this.atmobApi, this.atmobStreamApi) {
    AtmobLog.d(tag, '$tag...init');
    // 初始化时，刷新配置
    _refreshIntimacyAnalyzeConfig();
    _refreshIntimacyAnalyzeChatConfig();
    _refreshIntimacyAnalyzeReplyConfig();
  }

  /// 从Getx的依赖注入中，获取实例，适合在没有依赖注入上下文的地方使用
  IntimacyAnalyzeRepository getInstance() {
    return getIt.get<IntimacyAnalyzeRepository>();
  }

  /// 刷新亲密度配置
  void _refreshIntimacyAnalyzeConfig() {
    AsyncUtil.retry(
      () => requestIntimacyAnalyzeConfig(),
      Duration(seconds: 3),
      maxRetry: 100,
    ).then((IntimacyAnalyzeConfigResponse configResponse) {
      AtmobLog.d(tag, "获取亲密度配置成功: ${configResponse.toJson()}");
      intimacyAnalyzeConfig.value = configResponse;
    });
  }

  /// 刷新对话分析配置
  void _refreshIntimacyAnalyzeChatConfig() {
    AsyncUtil.retry(
      () => requestIntimacyAnalyzeChatConfig(),
      Duration(seconds: 3),
      maxRetry: 100,
    ).then((IntimacyAnalyzeChatConfigResponse configResponse) {
      AtmobLog.d(tag, "获取对话分析配置成功: ${configResponse.toJson()}");
      intimacyAnalyzeChatConfig.value = configResponse;
    });
  }

  /// 刷新识图回复配置
  void _refreshIntimacyAnalyzeReplyConfig() {
    AsyncUtil.retry(
      () => requestIntimacyAnalyzeReplyConfig(),
      Duration(seconds: 3),
      maxRetry: 100,
    ).then((IntimacyAnalyzeReplyConfigResponse configResponse) {
      AtmobLog.d(tag, "获取识图回复配置成功: ${configResponse.toJson()}");
      intimacyAnalyzeReplyConfig.value = configResponse;
    });
  }

  /// 获取亲密度配置
  Future<IntimacyAnalyzeConfigResponse> requestIntimacyAnalyzeConfig() {
    return atmobApi
        .getIntimacyAnalyzeConfig(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }

  /// 获取对话分析配置
  Future<IntimacyAnalyzeChatConfigResponse> requestIntimacyAnalyzeChatConfig() {
    return atmobApi
        .getIntimacyAnalyzeChatConfig(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }

  /// 对话分析（SSE流式）
  Future<Stream<Message>> intimacyChatAnalyze(
    IntimacyChatAnalyzeRequest request,
  ) {
    return atmobStreamApi
        .intimacyChatAnalyze(request)
        .then((response) async {
          List<String>? contentType = response.headers['Content-Type'];
          if (contentType != null) {
            for (var value in contentType) {
              if (value.contains('text/event-stream')) {
                return response.stream;
              } else if (value.contains('application/json')) {
                BaseResponse<String> baseResponse = BaseResponse.fromJson(
                  jsonDecode(
                    await response.stream
                        .map((bytes) => utf8.decoder.convert(bytes))
                        .toList()
                        .then((value) => value.join()),
                  ),
                  (json) => json as String,
                );
                throw ServerErrorException(
                  baseResponse.code,
                  baseResponse.message,
                );
              }
            }
          }
          throw Exception('Invalid content type');
        })
        .then((stream) => SSEParseUtil.parse(stream));
  }

  /// 获取识图回复配置
  Future<IntimacyAnalyzeReplyConfigResponse>
  requestIntimacyAnalyzeReplyConfig() {
    return atmobApi
        .getIntimacyAnalyzeReplyConfig(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }

  /// 分析亲密度
  Future<IntimacyAnalyzeResponse> getIntimacyAnalyze(
    IntimacyAnalyzeRequest request,
  ) {
    return atmobApi.getIntimacyAnalyze(request).then(HttpHandler.handle(true));
  }

  /// 生成亲密度人设
  Future<void> intimacyCharacterGenerate(
    IntimacyGenerateCharacterRequest request,
  ) {
    return atmobApi
        .intimacyCharacterGenerate(request)
        .then(HttpHandler.handle(true));
  }

  /// 识图回复
  Future<IntimacyReplyAnalyzeResponse> intimacyReplyAnalyze(
    IntimacyReplyAnalyzeRequest request,
  ) {
    return atmobApi
        .intimacyReplyAnalyze(request)
        .then(HttpHandler.handle(true));
  }
}
