using MEL = Microsoft.Extensions.Logging;

namespace ClawdDotNet.Core.Logging;

/// <summary>
/// Implementiert Microsoft.Extensions.Logging.ILogger und leitet alle
/// Einträge an den zentralen FileLogWriter weiter.
/// Jede Instanz ist einem Modul zugeordnet (z.B. "Core", "Tool_Database").
/// </summary>
public sealed class ModuleLogger : MEL.ILogger
{
    private readonly string _module;
    private readonly FileLogWriter _writer;
    private readonly FileLoggerOptions _options;

    public ModuleLogger(string module, FileLogWriter writer, FileLoggerOptions options)
    {
        _module = module;
        _writer = writer;
        _options = options;
    }

    public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;

    public bool IsEnabled(MEL.LogLevel logLevel)
    {
        var mapped = MapLevel(logLevel);
        return mapped >= _options.MinimumLevel;
    }

    public void Log<TState>(
        MEL.LogLevel logLevel,
        MEL.EventId eventId,
        TState state,
        Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        if (!IsEnabled(logLevel))
            return;

        var message = formatter(state, exception);
        var entry = new LogEntry(
            DateTime.Now,
            MapLevel(logLevel),
            _module,
            message,
            exception);

        _writer.Enqueue(entry);
    }

    private static LogLevel MapLevel(MEL.LogLevel level) => level switch
    {
        MEL.LogLevel.Trace => LogLevel.Debug,
        MEL.LogLevel.Debug => LogLevel.Debug,
        MEL.LogLevel.Information => LogLevel.Info,
        MEL.LogLevel.Warning => LogLevel.Warn,
        MEL.LogLevel.Error => LogLevel.Error,
        MEL.LogLevel.Critical => LogLevel.Error,
        _ => LogLevel.Info
    };
}
