/// 聊天消息模型

/// 聊天消息模型
class ChatMessage {
  final String id;
  final String role; // 'user', 'assistant', 'system'
  final String content;
  final DateTime timestamp;

  const ChatMessage({
    required this.id,
    required this.role,
    required this.content,
    required this.timestamp,
  });

  factory ChatMessage.fromJson(Map<String, dynamic> json) {
    return ChatMessage(
      id: json['id'] as String,
      role: json['role'] as String,
      content: json['content'] as String,
      timestamp: DateTime.parse(json['timestamp'] as String),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'role': role,
      'content': content,
      'timestamp': timestamp.toIso8601String(),
    };
  }

  /// 转换为 OpenAI API 格式
  Map<String, String> toApiFormat() {
    return {
      'role': role,
      'content': content,
    };
  }

  /// 是否是用户消息
  bool get isUser => role == 'user';

  /// 是否是 AI 消息
  bool get isAssistant => role == 'assistant';

  /// 创建用户消息
  factory ChatMessage.user(String content) {
    return ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      role: 'user',
      content: content,
      timestamp: DateTime.now(),
    );
  }

  /// 创建 AI 消息
  factory ChatMessage.assistant(String content) {
    return ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      role: 'assistant',
      content: content,
      timestamp: DateTime.now(),
    );
  }

  /// 创建系统消息
  factory ChatMessage.system(String content) {
    return ChatMessage(
      id: 'system',
      role: 'system',
      content: content,
      timestamp: DateTime.now(),
    );
  }
}

/// 聊天会话模型
class ChatSession {
  final String characterId;
  final List<ChatMessage> messages;
  final DateTime lastUpdated;

  const ChatSession({
    required this.characterId,
    required this.messages,
    required this.lastUpdated,
  });

  factory ChatSession.fromJson(Map<String, dynamic> json) {
    return ChatSession(
      characterId: json['character_id'] as String,
      messages: (json['messages'] as List)
          .map((m) => ChatMessage.fromJson(m))
          .toList(),
      lastUpdated: DateTime.parse(json['last_updated'] as String),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'character_id': characterId,
      'messages': messages.map((m) => m.toJson()).toList(),
      'last_updated': lastUpdated.toIso8601String(),
    };
  }

  /// 创建空会话
  factory ChatSession.empty(String characterId) {
    return ChatSession(
      characterId: characterId,
      messages: [],
      lastUpdated: DateTime.now(),
    );
  }

  /// 添加消息并返回新会话
  ChatSession addMessage(ChatMessage message) {
    return ChatSession(
      characterId: characterId,
      messages: [...messages, message],
      lastUpdated: DateTime.now(),
    );
  }
}
