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

namespace Jellyfin.Plugin.SRFPlay.ScheduledTasks;

/// <summary>
/// Scheduled task for refreshing SRF Play content.
/// </summary>
public class ContentRefreshTask : IScheduledTask
{
    private readonly ILogger<ContentRefreshTask> _logger;
    private readonly IContentRefreshService _contentRefreshService;

    /// <summary>
    /// Initializes a new instance of the <see cref="ContentRefreshTask"/> class.
    /// </summary>
    /// <param name="logger">The logger instance.</param>
    /// <param name="contentRefreshService">The content refresh service.</param>
    public ContentRefreshTask(
        ILogger<ContentRefreshTask> logger,
        IContentRefreshService contentRefreshService)
    {
        _logger = logger;
        _contentRefreshService = contentRefreshService;
    }

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

    /// <inheritdoc />
    public string Description => "Refreshes latest and trending content from SRF Play";

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

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

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

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

            if (!config.EnableLatestContent && !config.EnableTrendingContent)
            {
                _logger.LogInformation("Content refresh is disabled in configuration");
                progress?.Report(100);
                return;
            }

            // Refresh content for every business unit (one channel per unit).
            var units = System.Enum.GetValues<Configuration.BusinessUnit>();
            foreach (var unit in units)
            {
                var businessUnit = unit.ToLowerString();

                if (config.EnableLatestContent)
                {
                    _logger.LogInformation("Refreshing latest content for {BusinessUnit}", businessUnit);
                    progress?.Report(25);
                    await _contentRefreshService.RefreshLatestContentAsync(businessUnit, cancellationToken).ConfigureAwait(false);
                }

                if (config.EnableTrendingContent)
                {
                    _logger.LogInformation("Refreshing trending content for {BusinessUnit}", businessUnit);
                    progress?.Report(75);
                    await _contentRefreshService.RefreshTrendingContentAsync(businessUnit, cancellationToken).ConfigureAwait(false);
                }
            }

            progress?.Report(100);
            _logger.LogInformation("SRF Play content refresh task completed successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during SRF Play content refresh task");
            throw;
        }
    }

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

        // Run every X hours as configured
        return new[]
        {
            new TaskTriggerInfo
            {
                Type = TaskTriggerInfo.TriggerInterval,
                IntervalTicks = TimeSpan.FromHours(intervalHours).Ticks
            }
        };
    }
}
