using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Plugin.SRFPlay.Services.Interfaces;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Plugin.SRFPlay.ScheduledTasks;

/// <summary>
/// Scheduled task for checking and removing expired SRF Play content.
/// </summary>
public class ExpirationCheckTask : IScheduledTask
{
    private readonly ILogger<ExpirationCheckTask> _logger;
    private readonly IContentExpirationService _expirationService;
    private readonly IStreamProxyService _streamProxyService;

    /// <summary>
    /// Initializes a new instance of the <see cref="ExpirationCheckTask"/> class.
    /// </summary>
    /// <param name="logger">The logger instance.</param>
    /// <param name="expirationService">The content expiration service.</param>
    /// <param name="streamProxyService">The stream proxy service.</param>
    public ExpirationCheckTask(
        ILogger<ExpirationCheckTask> logger,
        IContentExpirationService expirationService,
        IStreamProxyService streamProxyService)
    {
        _logger = logger;
        _expirationService = expirationService;
        _streamProxyService = streamProxyService;
    }

    /// <inheritdoc />
    public string Name => "Check SRF Play Content Expiration";

    /// <inheritdoc />
    public string Description => "Checks for expired SRF Play content and removes it from the library";

    /// <inheritdoc />
    public string Category => "SRF Play";

    /// <inheritdoc />
    public string Key => "SRFPlayExpirationCheck";

    /// <inheritdoc />
    public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Starting SRF Play expiration check task");
        progress?.Report(0);

        try
        {
            var config = Plugin.Instance?.Configuration;
            if (config == null)
            {
                _logger.LogWarning("Plugin configuration not available");
                return;
            }

            // Check and remove expired content
            progress?.Report(25);
            var removedCount = await _expirationService.CheckAndRemoveExpiredContentAsync(cancellationToken).ConfigureAwait(false);

            // Clean up old stream proxy mappings
            progress?.Report(75);
            _streamProxyService.CleanupOldMappings();

            progress?.Report(100);
            _logger.LogInformation("SRF Play expiration check task completed. Removed {Count} expired items", removedCount);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during SRF Play expiration check task");
            throw;
        }
    }

    /// <inheritdoc />
    public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
    {
        var config = Plugin.Instance?.Configuration;
        var intervalHours = config?.ExpirationCheckIntervalHours ?? 24;

        // Run daily at 3 AM or every X hours as configured
        return new[]
        {
            new TaskTriggerInfo
            {
                Type = TaskTriggerInfo.TriggerDaily,
                TimeOfDayTicks = TimeSpan.FromHours(3).Ticks
            },
            new TaskTriggerInfo
            {
                Type = TaskTriggerInfo.TriggerInterval,
                IntervalTicks = TimeSpan.FromHours(intervalHours).Ticks
            }
        };
    }
}
