using System.Collections.Concurrent;

namespace SHH.MjpegPlayer;

/// <summary>
/// 任务状态信息载荷
/// </summary>
public record TaskMetadata(string Name, string Type, DateTime StartTime);

/// <summary>
/// 任务管理器：替代原 CoreTaskRun 功能
/// 职责：记录运行中的异步任务，支持状态检索和统一取消
/// </summary>
public static class TaskManager
{
    // 存储运行中的任务及其元数据
    public static readonly ConcurrentDictionary<string, TaskMetadata> RunningTasks = new();

    // 存储取消令牌，用于停止特定任务
    private static readonly ConcurrentDictionary<string, CancellationTokenSource> _tokens = new();

    /// <summary>
    /// 注册并运行一个受控任务
    /// </summary>
    public static void Run(string taskName, string taskType, Func<CancellationToken, Task> action)
    {
        var cts = new CancellationTokenSource();
        _tokens[taskName] = cts;

        var metadata = new TaskMetadata(taskName, taskType, DateTime.Now);
        RunningTasks[taskName] = metadata;

        // 启动异步任务
        Task.Run(async () =>
        {
            try
            {
                await action(cts.Token);
            }
            finally
            {
                // Optimized: 任务结束（无论正常还是异常）必须清理资源
                RunningTasks.TryRemove(taskName, out _);
                _tokens.TryRemove(taskName, out _);
            }
        }, cts.Token);
    }
}