import 'dart:async';
import 'dart:io';
import 'package:logging/logging.dart';
import '../utils/path_utils.dart';

/// 日志服务
class LogService {
  static final LogService _instance = LogService._internal();
  factory LogService() => _instance;
  LogService._internal();

  final Logger _rootLogger = Logger.root;
  final StreamController<String> _logController = StreamController<String>.broadcast();
  IOSink? _logFile;

  Stream<String> get logStream => _logController.stream;

  /// 初始化日志系统
  Future<void> initialize() async {
    // 配置日志输出
    _rootLogger.level = Level.ALL;
    _rootLogger.onRecord.listen((record) {
      final message = '[${record.time}] [${record.level.name}] ${record.message}';
      _logController.add(message);
      _logToFile(message);
    });

    // 打开日志文件
    try {
      final logDir = Directory(PathUtils.binFile('logs'));
      if (!await logDir.exists()) {
        await logDir.create(recursive: true);
      }
      
      final logFile = File(PathUtils.binFile('logs/client.log'));
      _logFile = logFile.openWrite(mode: FileMode.append);
    } catch (e) {
      // 静默失败
    }
  }

  /// 写入日志文件
  void _logToFile(String message) {
    try {
      if (_logFile != null) {
        _logFile!.writeln(message);
        _logFile!.flush();
      }
    } catch (e) {
      // 忽略写入错误，避免崩溃
      // print('写入日志文件失败: $e');
    }
  }

  /// 获取最新日志（限制行数）
  Future<String> getRecentLogs({int maxLines = 1000}) async {
    try {
      final file = File(PathUtils.binFile('logs/client.log'));
      if (await file.exists()) {
        final lines = await file.readAsLines();
        if (lines.length > maxLines) {
          return lines.sublist(lines.length - maxLines).join('\n');
        }
        return lines.join('\n');
      }
    } catch (e) {
      // 静默失败
    }
    return '';
  }

  /// 清理日志
  Future<void> clearLogs() async {
    try {
      final file = File(PathUtils.binFile('logs/client.log'));
      if (await file.exists()) {
        await file.writeAsString('');
        _logController.add('日志已清理');
      }
    } catch (e) {
      // 静默失败
    }
  }

  /// 关闭日志服务
  Future<void> close() async {
    await _logFile?.flush();
    await _logFile?.close();
    await _logController.close();
  }
}
