using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
using SerilogLogger = Serilog.ILogger;
using SerilogLog = Serilog.Log;

namespace ZB.MOM.WW.OtOpcUa.Host.Engines;

/// <summary>
/// F8b — production <see cref="IVirtualTagEvaluator"/> binding. Compiles each unique
/// expression once via <see cref="ScriptEvaluator{TContext, TResult}"/> (Roslyn-backed
/// sandbox) and caches the resulting evaluator keyed by source. Subsequent evaluations are
/// in-process method invocations on the dependency dictionary — fast enough to run inline
/// inside the actor's message handler.
///
/// Single-tag mode: cross-tag <c>ctx.SetVirtualTag</c> writes are dropped (logged) because
/// fan-out between actors is owned by <c>DependencyMuxActor</c>, not by the eval engine.
/// Cycle detection + cascade ordering live in <see cref="VirtualTagEngine"/>; this adapter
/// stays single-tag scoped to keep <see cref="VirtualTagActor"/>'s message loop simple.
/// </summary>
public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IDisposable
{
    private static readonly SerilogLogger ScriptLogger = SerilogLog.ForContext<RoslynVirtualTagEvaluator>();

    private readonly ConcurrentDictionary<string, ScriptEvaluator<VirtualTagContext, object?>> _cache
        = new(StringComparer.Ordinal);
    private readonly ILogger<RoslynVirtualTagEvaluator> _logger;
    private readonly TimeSpan _runTimeout;
    private bool _disposed;

    /// <summary>Initializes a new RoslynVirtualTagEvaluator with the given logger and optional timeout.</summary>
    /// <param name="logger">Logger for recording compilation and execution errors.</param>
    /// <param name="runTimeout">Maximum execution time for each script; defaults to 2 seconds if not specified.</param>
    public RoslynVirtualTagEvaluator(ILogger<RoslynVirtualTagEvaluator> logger, TimeSpan? runTimeout = null)
    {
        _logger = logger;
        _runTimeout = runTimeout ?? TimeSpan.FromSeconds(2);
    }

    /// <summary>Evaluates a virtual tag expression against a set of dependencies.</summary>
    /// <param name="virtualTagId">The virtual tag identifier, used for logging.</param>
    /// <param name="expression">The C# expression to evaluate.</param>
    /// <param name="dependencies">Dictionary of tag names to values available in the expression context.</param>
    /// <returns>The evaluation result, either successful with a value or failed with an error message.</returns>
    public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
    {
        if (_disposed) return VirtualTagEvalResult.Failure("evaluator disposed");
        if (string.IsNullOrWhiteSpace(expression)) return VirtualTagEvalResult.Failure("empty expression");

        ScriptEvaluator<VirtualTagContext, object?> evaluator;
        try
        {
            evaluator = _cache.GetOrAdd(expression, ScriptEvaluator<VirtualTagContext, object?>.Compile);
        }
        catch (CompilationErrorException ex)
        {
            _logger.LogWarning(ex, "VirtualTag {Id}: Roslyn compile failed", virtualTagId);
            return VirtualTagEvalResult.Failure($"compile error: {ex.Message}");
        }
        catch (ScriptSandboxViolationException ex)
        {
            _logger.LogWarning(ex, "VirtualTag {Id}: sandbox violation", virtualTagId);
            return VirtualTagEvalResult.Failure($"sandbox violation: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "VirtualTag {Id}: compile threw", virtualTagId);
            return VirtualTagEvalResult.Failure($"compile failure: {ex.Message}");
        }

        var readCache = BuildReadCache(dependencies);
        var context = new VirtualTagContext(
            readCache,
            setVirtualTag: (path, _) =>
                _logger.LogDebug("VirtualTag {Id}: cross-tag write to {Path} dropped (single-tag adapter)",
                    virtualTagId, path),
            logger: ScriptLogger);

        try
        {
            using var cts = new CancellationTokenSource(_runTimeout);
            var raw = evaluator.RunAsync(context, cts.Token).GetAwaiter().GetResult();
            return VirtualTagEvalResult.Ok(raw);
        }
        catch (OperationCanceledException)
        {
            return VirtualTagEvalResult.Failure($"script timed out after {_runTimeout.TotalSeconds:F1}s");
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "VirtualTag {Id}: script execution threw", virtualTagId);
            return VirtualTagEvalResult.Failure($"script threw: {ex.Message}");
        }
    }

    private static IReadOnlyDictionary<string, DataValueSnapshot> BuildReadCache(
        IReadOnlyDictionary<string, object?> deps)
    {
        // VirtualTagContext.GetTag returns a DataValueSnapshot — we wrap each raw dep value
        // as Good-quality so the script's `(int)ctx.GetTag("a").Value` pattern works. Null
        // values stay null; the script can null-check via GetTag(path).Value.
        var nowUtc = DateTime.UtcNow;
        var cache = new Dictionary<string, DataValueSnapshot>(StringComparer.Ordinal);
        foreach (var kv in deps)
        {
            cache[kv.Key] = new DataValueSnapshot(kv.Value, StatusCode: 0u, SourceTimestampUtc: nowUtc, ServerTimestampUtc: nowUtc);
        }
        return cache;
    }

    /// <summary>Disposes the evaluator and cleans up all cached script evaluators.</summary>
    public void Dispose()
    {
        if (_disposed) return;
        _disposed = true;
        foreach (var ev in _cache.Values)
        {
            try { ev.Dispose(); } catch { /* best-effort */ }
        }
        _cache.Clear();
    }
}
