using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Hub;
using ClaudeDo.Worker.Tests.Infrastructure;
using Xunit;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Worker.Tests.Hub;

public sealed class TaskUsageHubTests : IDisposable
{
    private readonly DbFixture _db = new();

    public void Dispose() => _db.Dispose();

    private WorkerHub CreateHub()
    {
        var broadcaster = new HubBroadcaster(new CapturingHubContext());
        var hub = new WorkerHub(
            null!, null!, null!, null!, broadcaster, _db.CreateFactory(),
            null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!, null!,
            null!, new ClaudeDo.Worker.Online.OnlineInboxConfig(), new ClaudeDo.Worker.OnlineRefreshTokenStore(new ClaudeDo.Worker.DpapiTokenStore("unused.token")),
            new ClaudeDo.Worker.Runner.PendingQuestionRegistry(), null!);
        hub.Clients = new FakeHubCallerClients(new RecordingClientProxy());
        hub.Context = new FakeHubCallerContext();
        return hub;
    }

    private async Task<string> SeedListAsync(string name = "L")
    {
        using var ctx = _db.CreateContext();
        var listId = Guid.NewGuid().ToString();
        await new ListRepository(ctx).AddAsync(new ListEntity
        {
            Id = listId, Name = name, CreatedAt = DateTime.UtcNow,
        });
        return listId;
    }

    private async Task<string> SeedTaskAsync(string listId, string title = "T")
    {
        using var ctx = _db.CreateContext();
        var taskId = Guid.NewGuid().ToString();
        await new TaskRepository(ctx).AddAsync(new TaskEntity
        {
            Id = taskId, ListId = listId, Title = title, Status = TaskStatus.Done,
            CreatedAt = DateTime.UtcNow, CommitType = "feat",
        });
        return taskId;
    }

    private async Task SeedRunAsync(
        string taskId, DateTime startedAt, int? tokensIn, int? tokensOut, string? model, int runNumber = 1)
    {
        using var ctx = _db.CreateContext();
        await new TaskRunRepository(ctx).AddAsync(new TaskRunEntity
        {
            Id = Guid.NewGuid().ToString(),
            TaskId = taskId,
            RunNumber = runNumber,
            IsRetry = false,
            Prompt = "p",
            StartedAt = startedAt,
            TokensIn = tokensIn,
            TokensOut = tokensOut,
            Model = model,
        });
    }

    [Fact]
    public async Task Groups_multiple_runs_for_same_task_and_sums_tokens()
    {
        var listId = await SeedListAsync();
        var taskId = await SeedTaskAsync(listId, "Task A");
        var day = new DateTime(2026, 8, 1);
        await SeedRunAsync(taskId, day, 100, 50, "sonnet", 1);
        await SeedRunAsync(taskId, day.AddHours(1), 200, 75, "sonnet", 2);
        await SeedRunAsync(taskId, day.AddHours(2), 300, 25, "sonnet", 3);

        var hub = CreateHub();
        var rows = await hub.GetTaskUsage(DateOnly.FromDateTime(day), DateOnly.FromDateTime(day));

        var row = Assert.Single(rows);
        Assert.Equal(taskId, row.TaskId);
        Assert.Equal(3, row.Runs);
        Assert.Equal(600, row.TokensIn);
        Assert.Equal(150, row.TokensOut);
    }

    [Fact]
    public async Task Sorts_descending_by_total_tokens()
    {
        var listId = await SeedListAsync();
        var smallTask = await SeedTaskAsync(listId, "Small");
        var bigTask = await SeedTaskAsync(listId, "Big");
        var day = new DateTime(2026, 8, 1);
        await SeedRunAsync(smallTask, day, 10, 10, "haiku");
        await SeedRunAsync(bigTask, day, 1000, 1000, "opus");

        var hub = CreateHub();
        var rows = await hub.GetTaskUsage(DateOnly.FromDateTime(day), DateOnly.FromDateTime(day));

        Assert.Equal(2, rows.Count);
        Assert.Equal(bigTask, rows[0].TaskId);
        Assert.Equal(smallTask, rows[1].TaskId);
    }

    [Fact]
    public async Task Respects_date_range()
    {
        var listId = await SeedListAsync();
        var taskId = await SeedTaskAsync(listId);
        var inRange = new DateTime(2026, 8, 5);
        var outOfRange = new DateTime(2026, 8, 1);
        await SeedRunAsync(taskId, inRange, 100, 100, "sonnet", 1);
        await SeedRunAsync(taskId, outOfRange, 999, 999, "sonnet", 2);

        var hub = CreateHub();
        var rows = await hub.GetTaskUsage(DateOnly.FromDateTime(inRange), DateOnly.FromDateTime(inRange));

        var row = Assert.Single(rows);
        Assert.Equal(1, row.Runs);
        Assert.Equal(100, row.TokensIn);
    }

    [Fact]
    public async Task Null_token_values_are_counted_as_zero_not_excluded()
    {
        var listId = await SeedListAsync();
        var taskId = await SeedTaskAsync(listId);
        var day = new DateTime(2026, 8, 1);
        await SeedRunAsync(taskId, day, null, null, null);

        var hub = CreateHub();
        var rows = await hub.GetTaskUsage(DateOnly.FromDateTime(day), DateOnly.FromDateTime(day));

        var row = Assert.Single(rows);
        Assert.Equal(1, row.Runs);
        Assert.Equal(0, row.TokensIn);
        Assert.Equal(0, row.TokensOut);
    }

    [Fact]
    public async Task Caps_at_100_rows()
    {
        var listId = await SeedListAsync();
        var day = new DateTime(2026, 8, 1);
        for (var i = 0; i < 105; i++)
        {
            var taskId = await SeedTaskAsync(listId, $"Task {i}");
            await SeedRunAsync(taskId, day, i, 0, "sonnet");
        }

        var hub = CreateHub();
        var rows = await hub.GetTaskUsage(DateOnly.FromDateTime(day), DateOnly.FromDateTime(day));

        Assert.Equal(100, rows.Count);
        // Highest token counts (100..4) survive the cap; the lowest (0..3) are dropped.
        Assert.All(rows, r => Assert.True(r.TokensIn >= 5));
    }
}
