import 'dart:convert';

import 'package:injectable/injectable.dart';

import '../../base/base_response.dart';
import '../../utils/atmob_log.dart';
import '../../utils/http_handler.dart';
import '../../utils/sse_parse_util.dart';
import '../api/atmob_stream_api.dart';
import '../api/request/deep_seek_chat_request.dart';

@lazySingleton
class ChatRepository {
  final AtmobStreamApi atmobStreamApi;
  var tag = "ChatRepository";

  ChatRepository(this.atmobStreamApi) {
    AtmobLog.d(tag, '$tag....init');
  }



  Future<Stream<Message>> streamDeepSeek(String chatContent) {
    return atmobStreamApi
        .deepSeekChat(DeepSeekChatRequest(chatContent))
        .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));
  }
}
