import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/chat_message_model.dart';

/// 本地聊天存储服务
/// 
/// 使用 SharedPreferences 存储聊天记录
class ChatStorageService {
  ChatStorageService._();

  static const String _keyPrefix = 'chat_session_';

  /// 获取聊天会话
  static Future<ChatSession> getSession(String characterId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_keyPrefix$characterId';
      final data = prefs.getString(key);
      
      if (data == null) {
        return ChatSession.empty(characterId);
      }

      return ChatSession.fromJson(jsonDecode(data));
    } catch (e) {
      debugPrint('❌ 读取聊天记录失败: $e');
      return ChatSession.empty(characterId);
    }
  }

  /// 保存聊天会话
  static Future<void> saveSession(ChatSession session) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_keyPrefix${session.characterId}';
      await prefs.setString(key, jsonEncode(session.toJson()));
      debugPrint('✅ 聊天记录已保存 (${session.messages.length} 条消息)');
    } catch (e) {
      debugPrint('❌ 保存聊天记录失败: $e');
    }
  }

  /// 添加消息到会话
  static Future<ChatSession> addMessage(String characterId, ChatMessage message) async {
    final session = await getSession(characterId);
    final newSession = session.addMessage(message);
    await saveSession(newSession);
    return newSession;
  }

  /// 清除角色的聊天记录
  static Future<void> clearSession(String characterId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final key = '$_keyPrefix$characterId';
      await prefs.remove(key);
      debugPrint('✅ 聊天记录已清除');
    } catch (e) {
      debugPrint('❌ 清除聊天记录失败: $e');
    }
  }

  /// 获取所有聊天会话的角色 ID 列表
  static Future<List<String>> getAllSessionIds() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();
      return keys
          .where((k) => k.startsWith(_keyPrefix))
          .map((k) => k.substring(_keyPrefix.length))
          .toList();
    } catch (e) {
      debugPrint('❌ 获取会话列表失败: $e');
      return [];
    }
  }
}
