using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.SiteEventLogging;

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

/// <summary>
/// WP3.2 (site_events volume policy — docs/plans/2026-08-15-site-events-policy-design.md):
/// site-only hosted service that periodically flushes <see cref="ScriptRunSummaryRecorder"/>
/// into one aggregate "script" Info site event. Registered by
/// <c>ServiceCollectionExtensions.AddSiteRuntime</c>, which only the site composition root
/// calls (<c>SiteServiceRegistration.Configure</c>) — central never runs scripts, so central
/// never registers this service, which is what makes it "Site nodes only" per the design memo.
///
/// <para>The interval is read from <see cref="IOptionsMonitor{TOptions}"/> on every tick (not
/// captured once at construction) so <see cref="SiteRuntimeOptions.ScriptRunSummaryIntervalSeconds"/>
/// is hot-reloadable — an operator can shorten or lengthen it, or disable it (<c>0</c>), live.
/// Mirrors <c>ScriptSchedulerStatsReporter</c>'s shape: fixed cadence, exceptions logged and
/// swallowed so the loop survives every flush failure.</para>
/// </summary>
public sealed class ScriptRunSummaryFlushService : BackgroundService
{
    /// <summary>Poll cadence used while summaries are disabled (<c>ScriptRunSummaryIntervalSeconds == 0</c>) — coarse enough to amortise re-checking whether the interval was re-enabled live.</summary>
    private static readonly TimeSpan DisabledPollInterval = TimeSpan.FromSeconds(30);

    private readonly ScriptRunSummaryRecorder _recorder;
    private readonly ISiteEventLogger _siteEventLogger;
    private readonly IOptionsMonitor<SiteRuntimeOptions> _optionsMonitor;
    private readonly ILogger<ScriptRunSummaryFlushService> _logger;

    /// <summary>Initializes a new instance of <see cref="ScriptRunSummaryFlushService"/>.</summary>
    /// <param name="recorder">The recorder whose accumulated counters this service flushes.</param>
    /// <param name="siteEventLogger">The site event logger the flushed summary row is written to.</param>
    /// <param name="optionsMonitor">Supplies the hot-reloadable flush interval.</param>
    /// <param name="logger">Logger instance.</param>
    public ScriptRunSummaryFlushService(
        ScriptRunSummaryRecorder recorder,
        ISiteEventLogger siteEventLogger,
        IOptionsMonitor<SiteRuntimeOptions> optionsMonitor,
        ILogger<ScriptRunSummaryFlushService> logger)
    {
        _recorder = recorder ?? throw new ArgumentNullException(nameof(recorder));
        _siteEventLogger = siteEventLogger ?? throw new ArgumentNullException(nameof(siteEventLogger));
        _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <inheritdoc />
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var intervalSeconds = _optionsMonitor.CurrentValue.ScriptRunSummaryIntervalSeconds;
            var wait = intervalSeconds > 0 ? TimeSpan.FromSeconds(intervalSeconds) : DisabledPollInterval;

            try
            {
                await Task.Delay(wait, stoppingToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                break;
            }

            if (intervalSeconds <= 0)
            {
                // Summaries disabled for this tick's window: counters keep accumulating in
                // the recorder (harmless — the next enabled flush just reports a longer
                // window), we simply don't emit or reset yet.
                continue;
            }

            try
            {
                await _recorder.FlushAsync(_siteEventLogger).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "ScriptRunSummaryFlushService flush failed; next tick will retry.");
            }
        }
    }
}
