using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Extensions.Logging;
using ScadaLink.Commons.Types;

namespace ScadaLink.SiteRuntime.Scripts;

/// <summary>
/// WP-19: Script Trust Model — compiles C# scripts using Roslyn with restricted API access.
/// Forbidden APIs: System.IO, Process, Threading (except async/await), Reflection,
/// System.Net.Sockets, System.Net.Http.
/// </summary>
public class ScriptCompilationService
{
    private readonly ILogger<ScriptCompilationService> _logger;

    /// <summary>
    /// Namespaces that are forbidden in user scripts for security.
    /// </summary>
    private static readonly string[] ForbiddenNamespaces =
    [
        "System.IO",
        "System.Diagnostics.Process",
        "System.Threading",
        "System.Reflection",
        "System.Net.Sockets",
        "System.Net.Http"
    ];

    /// <summary>
    /// Specific types/members allowed even within forbidden namespaces.
    /// async/await is OK despite System.Threading being blocked.
    /// </summary>
    private static readonly string[] AllowedExceptions =
    [
        "System.Threading.Tasks",
        "System.Threading.CancellationToken",
        "System.Threading.CancellationTokenSource"
    ];

    public ScriptCompilationService(ILogger<ScriptCompilationService> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// Validates that the script source code does not reference forbidden APIs.
    /// Returns a list of violation messages, empty if clean.
    /// </summary>
    public IReadOnlyList<string> ValidateTrustModel(string code)
    {
        var violations = new List<string>();
        var tree = CSharpSyntaxTree.ParseText(code);
        var root = tree.GetRoot();
        var text = root.ToFullString();

        foreach (var ns in ForbiddenNamespaces)
        {
            if (text.Contains(ns, StringComparison.Ordinal))
            {
                // Check if it matches an allowed exception
                var isAllowed = AllowedExceptions.Any(allowed =>
                    text.Contains(allowed, StringComparison.Ordinal) &&
                    ns != allowed &&
                    allowed.StartsWith(ns, StringComparison.Ordinal));

                // More precise: check each occurrence
                var idx = 0;
                while ((idx = text.IndexOf(ns, idx, StringComparison.Ordinal)) >= 0)
                {
                    var remainder = text.Substring(idx);
                    var matchesAllowed = AllowedExceptions.Any(a =>
                        remainder.StartsWith(a, StringComparison.Ordinal));

                    if (!matchesAllowed)
                    {
                        violations.Add($"Forbidden API reference: '{ns}' at position {idx}");
                        break;
                    }
                    idx += ns.Length;
                }
            }
        }

        return violations;
    }

    /// <summary>
    /// Shared Roslyn scripting options (references + imports) used by both full
    /// script compilation and trigger-expression compilation.
    /// </summary>
    private static ScriptOptions BuildScriptOptions() => ScriptOptions.Default
        .WithReferences(
            typeof(object).Assembly,
            typeof(Enumerable).Assembly,
            typeof(Math).Assembly,
            typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly,
            typeof(Commons.Types.DynamicJsonElement).Assembly)
        .WithImports(
            "System",
            "System.Collections.Generic",
            "System.Linq",
            "System.Threading.Tasks");

    /// <summary>
    /// Compiles a script into a reusable delegate that takes a ScriptRuntimeContext
    /// and parameters dictionary, and returns an object? result.
    /// </summary>
    public ScriptCompilationResult Compile(string scriptName, string code)
        => CompileCore(scriptName, code, typeof(ScriptGlobals));

    /// <summary>
    /// Compiles a bare C# boolean trigger expression against the restricted
    /// read-only <see cref="TriggerExpressionGlobals"/>. The expression is a
    /// trailing expression (no <c>return</c>); Roslyn scripting yields its
    /// value, which the caller coerces to <c>bool</c>. Reuses the same script
    /// options and forbidden-API trust validation as <see cref="Compile"/>.
    /// </summary>
    public ScriptCompilationResult CompileTriggerExpression(string name, string expression)
        => CompileCore(name, expression, typeof(TriggerExpressionGlobals));

    /// <summary>
    /// Shared compilation path: validates the trust model, builds the script
    /// against the given globals type, and returns the compiled result.
    /// </summary>
    private ScriptCompilationResult CompileCore(string name, string code, Type globalsType)
    {
        // Validate trust model
        var violations = ValidateTrustModel(code);
        if (violations.Count > 0)
        {
            _logger.LogWarning(
                "Script {Script} failed trust validation: {Violations}",
                name, string.Join("; ", violations));
            return ScriptCompilationResult.Failed(violations);
        }

        try
        {
            var script = CSharpScript.Create<object?>(
                code,
                BuildScriptOptions(),
                globalsType: globalsType);

            var diagnostics = script.Compile();
            var errors = diagnostics
                .Where(d => d.Severity == DiagnosticSeverity.Error)
                .Select(d => d.GetMessage())
                .ToList();

            if (errors.Count > 0)
            {
                _logger.LogWarning(
                    "Script {Script} compilation failed: {Errors}",
                    name, string.Join("; ", errors));
                return ScriptCompilationResult.Failed(errors);
            }

            _logger.LogDebug("Script {Script} compiled successfully", name);
            return ScriptCompilationResult.Succeeded(script);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unexpected error compiling script {Script}", name);
            return ScriptCompilationResult.Failed([$"Compilation exception: {ex.Message}"]);
        }
    }
}

/// <summary>
/// Result of script compilation, containing either the compiled script or error messages.
/// </summary>
public class ScriptCompilationResult
{
    public bool IsSuccess { get; }
    public Script<object?>? CompiledScript { get; }
    public IReadOnlyList<string> Errors { get; }

    private ScriptCompilationResult(bool success, Script<object?>? script, IReadOnlyList<string> errors)
    {
        IsSuccess = success;
        CompiledScript = script;
        Errors = errors;
    }

    public static ScriptCompilationResult Succeeded(Script<object?> script) =>
        new(true, script, []);

    public static ScriptCompilationResult Failed(IReadOnlyList<string> errors) =>
        new(false, null, errors);
}

/// <summary>
/// Global variables available to compiled scripts. The ScriptRuntimeContext is injected
/// as the "Instance" global, and parameters are available via "Parameters".
/// </summary>
public class ScriptGlobals
{
    public ScriptRuntimeContext Instance { get; set; } = null!;
    public ScriptParameters Parameters { get; set; } = new ScriptParameters();
    public CancellationToken CancellationToken { get; set; }

    /// <summary>
    /// Alarm context when this script is invoked as an on-trigger handler.
    /// Null for instance scripts, shared scripts, and inbound-API-routed
    /// scripts. Lets on-trigger scripts read the firing alarm's Name, Level
    /// (HiLo only), Priority, and per-band Message to branch routing logic.
    /// </summary>
    public Commons.Types.Scripts.AlarmContext? Alarm { get; set; }

    /// <summary>
    /// Where this script sits in the composition tree. Defaults to root for
    /// scripts on top-level templates; a flattened composed script gets
    /// SelfPath = "TempSensor" (etc.) and a ParentPath set to one level up.
    /// </summary>
    public Commons.Types.Scripts.ScriptScope Scope { get; set; } =
        Commons.Types.Scripts.ScriptScope.Root;

    /// <summary>
    /// Top-level ExternalSystem access for scripts (delegates to Instance.ExternalSystem).
    /// Usage: ExternalSystem.Call("systemName", "methodName", params)
    /// </summary>
    public ScriptRuntimeContext.ExternalSystemHelper ExternalSystem => Instance.ExternalSystem;

    /// <summary>
    /// Top-level Database access for scripts (delegates to Instance.Database).
    /// Usage: Database.Connection("name") or Database.CachedWrite("name", "sql", params)
    /// </summary>
    public ScriptRuntimeContext.DatabaseHelper Database => Instance.Database;

    /// <summary>
    /// Top-level Notify access for scripts (delegates to Instance.Notify).
    /// Usage: Notify.To("listName").Send("subject", "message")
    /// </summary>
    public ScriptRuntimeContext.NotifyHelper Notify => Instance.Notify;

    /// <summary>
    /// Top-level Scripts access for shared script calls (delegates to Instance.Scripts).
    /// Usage: Scripts.CallShared("scriptName", params)
    /// </summary>
    public ScriptRuntimeContext.ScriptCallHelper Scripts => Instance.Scripts;

    /// <summary>
    /// Read/write the current template's attributes by name. Resolves to the
    /// canonical name for the script's scope, so a script on a composed
    /// TempSensor reads its own Temperature via <c>Attributes["Temperature"]</c>.
    /// </summary>
    public AttributeAccessor Attributes => new(Instance, Scope.SelfPath);

    /// <summary>
    /// Indexed access to child compositions.
    /// <c>Children["TempSensor"].Attributes["Temperature"]</c> reads the
    /// composed child's attribute. <c>Children["TempSensor"].CallScript("Sample")</c>
    /// invokes a script on the child.
    /// </summary>
    public ChildrenAccessor Children => new(Instance, Scope.SelfPath);

    /// <summary>
    /// Parent composition (null when this script is on a root-level template).
    /// <c>Parent.Attributes["SpeedRPM"]</c> reaches the parent's attribute;
    /// <c>Parent.CallScript("Trip")</c> invokes a parent script.
    /// </summary>
    public CompositionAccessor? Parent =>
        Scope.ParentPath == null ? null : new CompositionAccessor(Instance, Scope.ParentPath);
}
