import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';

class DailyLogUtils {
  // 获取日志文件路径（按日期命名）
  static Future<File> _getLogFile() async {
    final dir = await getApplicationDocumentsDirectory();
    final date = DateFormat('yyyy-MM-dd').format(DateTime.now());
    final filePath = '${dir.path}/$date.log';
    final file = File(filePath);
    if (!await file.exists()) {
      await file.create(recursive: true);
    }
    return file;
  }

  // 写入日志核心方法，带日志等级
  static Future<void> _writeLogWithLevel(String level, String content) async {
    final file = await _getLogFile();
    final now = DateTime.now();
    final time = DateFormat('HH:mm:ss').format(now);
    final logLine = '[$time][$level] $content\n';
    await file.writeAsString(logLine, mode: FileMode.append);
  }

  // 写入 info 日志（原 writeLog 保留）
  static Future<void> writeLog(String content) async {
    print("[dailylog-->info] $content]");
    await _writeLogWithLevel('INFO', content);
  }

  // 写入 warning 日志
  static Future<void> writeWarning(String content) async {
        print("[dailylog-->waring] $content]");
    await _writeLogWithLevel('WARNING', content);
  }

  // 写入 error 日志
  static Future<void> writeError(String content) async {
    print("[dailylog-->error] $content]");
    await _writeLogWithLevel('ERROR', content);
  }

  // 写入 debug 日志
  static Future<void> writeDebug(String content) async {
    print("[dailylog-->debug] $content]");
    await _writeLogWithLevel('DEBUG', content);
  }

  static Future<void> printLog(String content) async {
    print("logger--->" + content);
    // await writeLog(content);
  }

  // 读取当天日志
  static Future<String> readTodayLog() async {  
    final file = await _getLogFile();
    return await file.readAsString();
  }

  // 获取所有日志文件（返回 File 列表）
  static Future<List<FileSystemEntity>> listLogFiles() async {
    final dir = await getApplicationDocumentsDirectory();
    final files = dir.listSync();
    return files.where((f) => f.path.endsWith('.log')).toList();
  }

  // 清除所有日志
  static Future<void> clearAllLogs() async {
    final files = await listLogFiles();
    for (final f in files) {
      await File(f.path).delete();
    }
  }

  /// 获取指定日期范围内的日志文件（包含起止日期）
  static Future<List<File>> getLogsBetween(
      DateTime fromDate, DateTime toDate) async {
    final dir = await getApplicationDocumentsDirectory();
    final logFiles = <File>[];
    final dateFormat = DateFormat('yyyy-MM-dd');

    for (DateTime date = fromDate;
        !date.isAfter(toDate);
        date = date.add(Duration(days: 1))) {
      final fileName = '${dateFormat.format(date)}.log';
      final file = File('${dir.path}/$fileName');
      if (await file.exists()) {
        logFiles.add(file);
      }
    }

    return logFiles;
  }
}
