// <copyright file="CacheDecorator.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

#pragma warning disable CA1826 // Do not use Enumerable methods on indexable collections

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Jellyfin.MediaEncoding.Hls.Extractors;
using Jellyfin.MediaEncoding.Keyframes;
using MediaBrowser.Controller.Persistence;
using Microsoft.Extensions.Logging;

namespace Jellyfin.MediaEncoding.Hls.Cache;

/// <inheritdoc />
public partial class CacheDecorator : IKeyframeExtractor
{
    private readonly IKeyframeRepository _keyframeRepository;
    private readonly IKeyframeExtractor _keyframeExtractor;
    private readonly ILogger<CacheDecorator> _logger;
    private readonly string _keyframeExtractorName;

    /// <summary>
    /// Initializes a new instance of the <see cref="CacheDecorator"/> class.
    /// </summary>
    /// <param name="keyframeRepository">An instance of the <see cref="IKeyframeRepository"/> interface.</param>
    /// <param name="keyframeExtractor">An instance of the <see cref="IKeyframeExtractor"/> interface.</param>
    /// <param name="logger">An instance of the <see cref="ILogger{CacheDecorator}"/> interface.</param>
    public CacheDecorator(IKeyframeRepository keyframeRepository, IKeyframeExtractor keyframeExtractor, ILogger<CacheDecorator> logger)
    {
        ArgumentNullException.ThrowIfNull(keyframeRepository);
        ArgumentNullException.ThrowIfNull(keyframeExtractor);

        _keyframeRepository = keyframeRepository;
        _keyframeExtractor = keyframeExtractor;
        _logger = logger;
        _keyframeExtractorName = keyframeExtractor.GetType().Name;
    }

    /// <inheritdoc />
    public bool IsMetadataBased => _keyframeExtractor.IsMetadataBased;

    /// <inheritdoc />
    public bool TryExtractKeyframes(Guid itemId, string filePath, [NotNullWhen(true)] out KeyframeData? keyframeData)
    {
        // Note: This method is synchronous by interface design, but repository is async.
        // Using GetAwaiter().GetResult() here is acceptable as this is called during media scanning
        // which is not performance-critical. Consider making IKeyframeExtractor async in future.
        keyframeData = _keyframeRepository.GetKeyframeDataAsync(itemId, CancellationToken.None)
            .GetAwaiter()
            .GetResult()
            .FirstOrDefault();

        if (keyframeData is null)
        {
            if (!_keyframeExtractor.TryExtractKeyframes(itemId, filePath, out var result))
            {
                LogKeyframeExtractionFailed(_logger, _keyframeExtractorName);
                return false;
            }

            LogKeyframeExtractionSucceeded(_logger, _keyframeExtractorName);
            keyframeData = result;
            _keyframeRepository.SaveKeyframeDataAsync(itemId, keyframeData, CancellationToken.None)
                .GetAwaiter()
                .GetResult();
        }

        return true;
    }

    [LoggerMessage(Level = LogLevel.Debug, Message = "Failed to extract keyframes using {ExtractorName}")]
    private static partial void LogKeyframeExtractionFailed(ILogger logger, string extractorName);

    [LoggerMessage(Level = LogLevel.Debug, Message = "Successfully extracted keyframes using {ExtractorName}")]
    private static partial void LogKeyframeExtractionSucceeded(ILogger logger, string extractorName);
}
