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;

/// Regression test for the queue-claim badge bug: QueuePicker's raw-SQL Queued->Running claim
/// bypasses TaskStateService.StartRunningAsync (which normally broadcasts TaskUpdated), so
/// alreadyClaimed=true dispatches must broadcast it themselves — otherwise the UI task-list
/// badge stays on "Queued" until the run finishes instead of flipping live.
public sealed class QueueClaimTaskUpdatedBroadcastTests : IDisposable
{
    private readonly DbFixture _db = new();
    private readonly string _tempDir;
    private readonly WorkerConfig _cfg;
    private readonly CapturingHubContext _hubContext = new();

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

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

    private TaskRunner BuildRunner(IClaudeProcess claude)
    {
        var dbFactory = _db.CreateFactory();
        var state = TaskStateServiceBuilder.Build(dbFactory).State;
        var wt = new WorktreeManager(new GitService(), dbFactory, _cfg, NullLogger<WorktreeManager>.Instance);
        return new TaskRunner(claude, dbFactory, new HubBroadcaster(_hubContext), wt,
            new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
            new AttachmentStore(), new FakeSessionSkillSeeder(), new FakeTranscriptUsageReader());
    }

    [Fact]
    public async Task RunAsync_with_alreadyClaimed_broadcasts_TaskUpdated_before_the_run_finishes()
    {
        string listId = Guid.NewGuid().ToString(), taskId = Guid.NewGuid().ToString();
        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = listId, Name = "L", WorkingDir = null, CreatedAt = DateTime.UtcNow });
            // Mirrors what QueuePicker's raw SQL claim already did before dispatch.
            ctx.Tasks.Add(new TaskEntity
            {
                Id = taskId, ListId = listId, Title = "T", Status = TaskStatus.Running,
                StartedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
            });
            await ctx.SaveChangesAsync();
        }

        var processStarted = new TaskCompletionSource();
        var releaseProcess = new TaskCompletionSource();
        var fake = new FakeClaudeProcess(async (_, _, _, _, _) =>
        {
            processStarted.TrySetResult();
            await releaseProcess.Task;
            return new RunResult { ExitCode = 0, ResultMarkdown = "ok" };
        });
        var runner = BuildRunner(fake);

        Task runTask;
        using (var ctx = _db.CreateContext())
            runTask = runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync(taskId))!, "queue", CancellationToken.None, alreadyClaimed: true);

        await processStarted.Task;

        Assert.Contains(_hubContext.Proxy.Calls, c => c.Method == "TaskUpdated" && (string)c.Args[0]! == taskId);

        releaseProcess.TrySetResult();
        await runTask;
    }

    [Fact]
    public async Task ContinueAsync_with_alreadyClaimed_broadcasts_TaskUpdated_exactly_once_before_the_run_finishes()
    {
        string listId = Guid.NewGuid().ToString(), taskId = Guid.NewGuid().ToString();
        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = listId, Name = "L", WorkingDir = null, CreatedAt = DateTime.UtcNow });
            ctx.Tasks.Add(new TaskEntity
            {
                Id = taskId, ListId = listId, Title = "T", Status = TaskStatus.Running,
                StartedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
            });
            ctx.TaskRuns.Add(new TaskRunEntity
            {
                Id = Guid.NewGuid().ToString(), TaskId = taskId, RunNumber = 1, IsRetry = false,
                Prompt = "p", SessionId = "sess-1",
                StartedAt = DateTime.UtcNow.AddMinutes(-5), FinishedAt = DateTime.UtcNow.AddMinutes(-1),
                ExitCode = 0, ResultMarkdown = "ok",
            });
            await ctx.SaveChangesAsync();
        }

        var processStarted = new TaskCompletionSource();
        var releaseProcess = new TaskCompletionSource();
        var fake = new FakeClaudeProcess(async (_, _, _, _, _) =>
        {
            processStarted.TrySetResult();
            await releaseProcess.Task;
            return new RunResult { ExitCode = 0, ResultMarkdown = "ok" };
        });
        var runner = BuildRunner(fake);

        var runTask = runner.ContinueAsync(taskId, "follow up", "queue", CancellationToken.None, alreadyClaimed: true);

        await processStarted.Task;

        Assert.Single(_hubContext.Proxy.Calls, c => c.Method == "TaskUpdated" && (string)c.Args[0]! == taskId);

        releaseProcess.TrySetResult();
        await runTask;
    }

    [Fact]
    public async Task Creating_a_worktree_broadcasts_WorktreeUpdated()
    {
        string listId = Guid.NewGuid().ToString(), taskId = Guid.NewGuid().ToString();
        var repoDir = Path.Combine(_tempDir, "repo");
        Directory.CreateDirectory(repoDir);

        // A real git repo — Worker.Tests run real git by design.
        await RunGitAsync(repoDir, "init");
        await RunGitAsync(repoDir, "config user.email t@t.t");
        await RunGitAsync(repoDir, "config user.name t");
        await File.WriteAllTextAsync(Path.Combine(repoDir, "a.txt"), "hi");
        await RunGitAsync(repoDir, "add a.txt");
        await RunGitAsync(repoDir, "commit -m init");

        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = listId, Name = "L", WorkingDir = repoDir, CreatedAt = DateTime.UtcNow });
            ctx.Tasks.Add(new TaskEntity
            {
                Id = taskId, ListId = listId, Title = "T", Status = TaskStatus.Running,
                StartedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
            });
            await ctx.SaveChangesAsync();
        }

        var fake = new FakeClaudeProcess((_, _, _, _, _) =>
            Task.FromResult(new RunResult { ExitCode = 0, ResultMarkdown = "ok" }));
        var runner = BuildRunner(fake);

        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync(taskId))!, "queue",
                CancellationToken.None, alreadyClaimed: true);

        Assert.Contains(_hubContext.Proxy.Calls,
            c => c.Method == "WorktreeUpdated" && (string)c.Args[0]! == taskId);
    }

    private static async Task RunGitAsync(string dir, string args)
    {
        var psi = new System.Diagnostics.ProcessStartInfo("git", args)
        {
            WorkingDirectory = dir, RedirectStandardOutput = true, RedirectStandardError = true,
        };
        using var p = System.Diagnostics.Process.Start(psi)!;
        await p.WaitForExitAsync();
    }
}
