namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;

/// <summary>
/// WP3.2 (site_events volume policy — docs/plans/2026-08-15-site-events-policy-design.md):
/// decides whether an instance script run should emit the legacy per-run Started/Completed
/// Info site events, or stay silent and let <see cref="ScriptRunSummaryRecorder"/>'s interval
/// aggregate carry the signal instead. Pure and side-effect-free — no DI, no actor context —
/// so the three opt-in shapes (global switch, exact per-script match, per-instance wildcard)
/// are unit-testable in isolation and reusable from <see cref="ScriptRunLauncher"/> without
/// dragging config plumbing into the run body.
/// </summary>
public static class ScriptRunEventPolicy
{
    /// <summary>
    /// True when per-run Started/Completed Info events should be emitted for this run.
    /// </summary>
    /// <param name="options">
    /// The effective <see cref="SiteRuntimeOptions"/> snapshot for this run (the caller reads
    /// <c>IOptionsMonitor&lt;SiteRuntimeOptions&gt;.CurrentValue</c> per run so this stays
    /// hot-togglable — see <see cref="SiteRuntimeOptions.PerRunScriptEvents"/>).
    /// </param>
    /// <param name="instanceName">The owning instance's name.</param>
    /// <param name="scriptName">The script's name.</param>
    /// <returns>
    /// <c>true</c> if <see cref="SiteRuntimeOptions.PerRunScriptEvents"/> is set, or if
    /// <see cref="SiteRuntimeOptions.PerRunScriptEventScripts"/> contains an exact
    /// <c>"{instanceName}/{scriptName}"</c> entry or an <c>"{instanceName}/*"</c> wildcard
    /// entry for this instance; otherwise <c>false</c>.
    /// </returns>
    public static bool ShouldEmitPerRun(SiteRuntimeOptions options, string instanceName, string scriptName)
    {
        ArgumentNullException.ThrowIfNull(options);

        if (options.PerRunScriptEvents)
            return true;

        var scripts = options.PerRunScriptEventScripts;
        if (scripts is not { Count: > 0 })
            return false;

        var exact = $"{instanceName}/{scriptName}";
        var wildcard = $"{instanceName}/*";

        foreach (var entry in scripts)
        {
            if (string.Equals(entry, exact, StringComparison.Ordinal) ||
                string.Equals(entry, wildcard, StringComparison.Ordinal))
            {
                return true;
            }
        }

        return false;
    }
}
