using ClaudeDo.Data;
using ClaudeDo.Data.Git;
using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.Hub;
using ClaudeDo.Worker.Runner;
using ClaudeDo.Worker.Tests.Infrastructure;
using Microsoft.Extensions.Logging.Abstractions;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
using Xunit;

namespace ClaudeDo.Worker.Tests.Runner;

// Slice 4 of the task-numbers feature: the curated WorkerLog business events must say "#<Number>"
// so a user who knows a task by its number (not its GUID) can find it in the worker-log strip.
public sealed class WorkerLogTaskNumberTests : IDisposable
{
    private readonly DbFixture _db = new();
    private readonly string _tempDir;
    private readonly WorkerConfig _cfg;

    public WorkerLogTaskNumberTests()
    {
        _tempDir = Path.Combine(Path.GetTempPath(), $"cd_wlnum_{Guid.NewGuid():N}");
        Directory.CreateDirectory(_tempDir);
        _cfg = new WorkerConfig { SandboxRoot = _tempDir, LogRoot = _tempDir };
    }

    public void Dispose() { _db.Dispose(); try { Directory.Delete(_tempDir, true); } catch { } }

    [Fact]
    public async Task RunAsync_Success_BroadcastsWorkerLog_ContainingTaskNumber()
    {
        var dbFactory = _db.CreateFactory();
        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = "l1", Name = "L", WorkingDir = null, CreatedAt = DateTime.UtcNow });
            ctx.Tasks.Add(new TaskEntity { Id = "solo", ListId = "l1", Title = "Solo", Number = 123,
                Status = TaskStatus.Running, CreatedAt = DateTime.UtcNow });
            await ctx.SaveChangesAsync();
        }
        var fake = new FakeClaudeProcess((_, _, _, _, _) =>
            Task.FromResult(new RunResult { ExitCode = 0, ResultMarkdown = "done" }));
        var hub = new CapturingHubContext();
        var state = TaskStateServiceBuilder.Build(dbFactory).State;
        var wt = new WorktreeManager(new GitService(), dbFactory, _cfg, NullLogger<WorktreeManager>.Instance);
        var runner = new TaskRunner(fake, dbFactory, new HubBroadcaster(hub), wt,
            new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
            new AttachmentStore(), new FakeSessionSkillSeeder(), new FakeTranscriptUsageReader());

        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync("solo"))!, "slot-1", default, alreadyClaimed: true);

        Assert.Contains(hub.Proxy.Calls, c => c.Method == "WorkerLog"
            && c.Args[0] is string s && s.Contains("#123"));
    }

    [Fact]
    public async Task RunAsync_Failure_BroadcastsWorkerLog_ContainingTaskNumber()
    {
        var dbFactory = _db.CreateFactory();
        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = "l1", Name = "L", WorkingDir = null, CreatedAt = DateTime.UtcNow });
            ctx.Tasks.Add(new TaskEntity { Id = "fail1", ListId = "l1", Title = "Boom", Number = 456,
                Status = TaskStatus.Running, CreatedAt = DateTime.UtcNow });
            await ctx.SaveChangesAsync();
        }
        var fake = new FakeClaudeProcess((_, _, _, _, _) =>
            Task.FromResult(new RunResult { ExitCode = 1, ErrorMarkdown = "nope" }));
        var hub = new CapturingHubContext();
        var state = TaskStateServiceBuilder.Build(dbFactory).State;
        var wt = new WorktreeManager(new GitService(), dbFactory, _cfg, NullLogger<WorktreeManager>.Instance);
        var runner = new TaskRunner(fake, dbFactory, new HubBroadcaster(hub), wt,
            new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
            new AttachmentStore(), new FakeSessionSkillSeeder(), new FakeTranscriptUsageReader());

        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync("fail1"))!, "slot-1", default, alreadyClaimed: true);

        Assert.Contains(hub.Proxy.Calls, c => c.Method == "WorkerLog"
            && c.Args[0] is string s && s.Contains("(failed)") && s.Contains("#456"));
    }
}
