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

class FileLogOutput extends LogOutput {
  late final Directory _logDirectory;
  late final String _todayLogFileName;

  FileLogOutput() {
    _init();
  }

  Future<void> _init() async {
    _logDirectory = await getApplicationDocumentsDirectory();
    final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
    _todayLogFileName = 'log_$today.txt';
    await _cleanupOldLogs();
  }

  @override
  void output(OutputEvent event) async {
    final file = await _getTodayLogFile();
    final logMessage = event.lines.join('\n') + '\n';
    await file.writeAsString(logMessage, mode: FileMode.append, flush: true);
  }

  Future<File> _getTodayLogFile() async {
    final path = '${_logDirectory.path}/$_todayLogFileName';
    final file = File(path);
    if (!await file.exists()) {
      await file.create(recursive: true);
    }
    return file;
  }

  /// Keep only the most recent 3 days of logs
  Future<void> _cleanupOldLogs() async {
    final files = _logDirectory
        .listSync()
        .whereType<File>()
        .where((f) => f.path.contains(RegExp(r'log_\d{4}-\d{2}-\d{2}\.txt')))
        .toList();

    files.sort((a, b) => b.path.compareTo(a.path)); 

    if (files.length > 3) {
      final oldFiles = files.sublist(3);
      for (final f in oldFiles) {
        try {
          await f.delete();
        } catch (e) {
          
        }
      }
    }
  }

  /// For reading today's log
  Future<String> readTodayLogs() async {
    final file = await _getTodayLogFile();
    return file.readAsString();
  }

  /// Read all log files (optional utility)
  Future<Map<String, String>> readAllLogs() async {
    final files = _logDirectory
        .listSync()
        .whereType<File>()
        .where((f) => f.path.contains('log_'))
        .toList();

    Map<String, String> logs = {};
    for (final f in files) {
      logs[f.path.split('/').last] = await f.readAsString();
    }
    return logs;
  }
}
