import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../models/chat_message_model.dart';
import '../models/llm_config_model.dart';
import '../models/character_model.dart';
import '../repositories/llm_config_repository.dart';

/// AI 聊天服务
/// 
/// 负责调用 LLM API 进行对话
class ChatService {
  ChatService._();

  /// 发送消息并获取 AI 回复
  /// 
  /// [character] 当前对话的角色
  /// [messages] 历史消息列表
  /// [userMessage] 用户新发送的消息
  /// [onStream] 流式输出回调（每次收到新内容时调用）
  static Future<String> sendMessage({
    required CharacterModel character,
    required List<ChatMessage> messages,
    required String userMessage,
    Function(String)? onStream,
  }) async {
    // 获取 LLM 配置
    final config = await LlmConfigRepository.getActiveConfig();
    if (config == null) {
      throw Exception('LLM 配置未找到，请先配置 API Key');
    }

    // 构建消息列表
    final apiMessages = <Map<String, String>>[];

    // 1. System prompt（角色人设）
    final systemPrompt = character.aiSystemPrompt ?? 
        '你是 ${character.name}，${character.tagline ?? "一个AI角色"}。${character.description ?? ""}';
    apiMessages.add({'role': 'system', 'content': systemPrompt});

    // 2. 历史消息（最多保留最近 20 条）
    final recentMessages = messages.length > 20 
        ? messages.sublist(messages.length - 20) 
        : messages;
    for (final msg in recentMessages) {
      if (msg.role != 'system') {
        apiMessages.add(msg.toApiFormat());
      }
    }

    // 3. 新用户消息
    apiMessages.add({'role': 'user', 'content': userMessage});

    debugPrint('📤 发送到 LLM: ${apiMessages.length} 条消息');

    // 判断是否使用流式输出
    if (config.stream && onStream != null) {
      return _sendStreamRequest(config, apiMessages, onStream);
    } else {
      return _sendNormalRequest(config, apiMessages);
    }
  }

  /// 普通请求（非流式）
  static Future<String> _sendNormalRequest(
    LlmConfigModel config,
    List<Map<String, String>> messages,
  ) async {
    try {
      final response = await http.post(
        Uri.parse(config.chatCompletionsUrl),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${config.apiKey}',
        },
        body: jsonEncode({
          'model': config.model,
          'messages': messages,
          'temperature': config.temperature,
          'max_tokens': config.maxTokens,
          'stream': false,
        }),
      );

      if (response.statusCode != 200) {
        debugPrint('❌ LLM API 错误: ${response.statusCode} ${response.body}');
        throw Exception('API 请求失败: ${response.statusCode}');
      }

      final data = jsonDecode(response.body);
      final content = data['choices'][0]['message']['content'] as String;
      debugPrint('📥 收到回复: ${content.substring(0, content.length.clamp(0, 50))}...');
      return content;
    } catch (e) {
      debugPrint('❌ LLM 请求失败: $e');
      rethrow;
    }
  }

  /// 流式请求
  static Future<String> _sendStreamRequest(
    LlmConfigModel config,
    List<Map<String, String>> messages,
    Function(String) onStream,
  ) async {
    try {
      final client = http.Client();
      final request = http.Request('POST', Uri.parse(config.chatCompletionsUrl));
      
      request.headers.addAll({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ${config.apiKey}',
        'Accept': 'text/event-stream',
      });

      request.body = jsonEncode({
        'model': config.model,
        'messages': messages,
        'temperature': config.temperature,
        'max_tokens': config.maxTokens,
        'stream': true,
      });

      final response = await client.send(request);

      if (response.statusCode != 200) {
        final body = await response.stream.bytesToString();
        debugPrint('❌ LLM API 错误: ${response.statusCode} $body');
        throw Exception('API 请求失败: ${response.statusCode}');
      }

      final completer = Completer<String>();
      final buffer = StringBuffer();

      response.stream
          .transform(utf8.decoder)
          .transform(const LineSplitter())
          .listen(
        (line) {
          if (line.startsWith('data: ')) {
            final data = line.substring(6);
            if (data == '[DONE]') {
              return;
            }
            try {
              final json = jsonDecode(data);
              final delta = json['choices']?[0]?['delta']?['content'];
              if (delta != null && delta is String) {
                buffer.write(delta);
                onStream(buffer.toString());
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        },
        onDone: () {
          client.close();
          final result = buffer.toString();
          debugPrint('📥 流式回复完成: ${result.length} 字符');
          completer.complete(result);
        },
        onError: (e) {
          client.close();
          debugPrint('❌ 流式请求错误: $e');
          completer.completeError(e);
        },
      );

      return completer.future;
    } catch (e) {
      debugPrint('❌ LLM 流式请求失败: $e');
      rethrow;
    }
  }

  /// 获取角色的问候语
  static String getGreeting(CharacterModel character) {
    return character.aiGreeting ?? 
        '你好，我是 ${character.name}。有什么我可以帮你的吗？';
  }
}
