using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Islands;
using Microsoft.EntityFrameworkCore;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Ui.Tests.ViewModels;

// Covers the Reset & Retry gate: it discards the branch/uncommitted work and queues an
// autonomous run into the same worktree, so it must stay off while an interactive ConPTY
// pane is open on the task (mirrors TaskRowViewModel.CanSendToQueue's HasInteractiveSession gate).
public class DetailsIslandResetAndRetryTests : IDisposable
{
    private readonly string _dbPath;

    public DetailsIslandResetAndRetryTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_reset_retry_test_{Guid.NewGuid():N}.db");
        using var ctx = NewContext();
        ctx.Database.EnsureCreated();
    }

    public void Dispose()
    {
        try { File.Delete(_dbPath); } catch { }
        try { File.Delete(_dbPath + "-wal"); } catch { }
        try { File.Delete(_dbPath + "-shm"); } catch { }
    }

    private ClaudeDoDbContext NewContext()
    {
        var opts = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={_dbPath}")
            .Options;
        return new ClaudeDoDbContext(opts);
    }




    private sealed class RecordingWorkerClient : StubWorkerClient
    {
        public override bool IsConnected => true;
    }

    private DetailsIslandViewModel BuildVm(StubWorkerClient worker)
    {
        var factory = new TestDbFactory(NewContext);
        return new DetailsIslandViewModel(
            factory, worker, new NullServiceProvider(), new ClaudeDo.Ui.Services.MergeCoordinator());
    }

    [Fact]
    public void ResetAndRetry_IsDisabled_WhileTaskHasInteractiveSession()
    {
        var vm = BuildVm(new RecordingWorkerClient());
        var row = new TaskRowViewModel { Id = "task-reset-1", Status = TaskStatus.Failed, HasInteractiveSession = true };
        vm.Bind(row);
        vm.Monitor.ApplyState(TaskStatus.Failed);

        Assert.True(vm.ShowResetAndRetry);
        Assert.False(vm.ResetAndRetryCommand.CanExecute(null));
    }

    [Fact]
    public void ResetAndRetry_ReEnables_WhenInteractiveSessionCloses()
    {
        var vm = BuildVm(new RecordingWorkerClient());
        var row = new TaskRowViewModel { Id = "task-reset-2", Status = TaskStatus.Failed, HasInteractiveSession = true };
        vm.Bind(row);
        vm.Monitor.ApplyState(TaskStatus.Failed);

        Assert.False(vm.ResetAndRetryCommand.CanExecute(null));

        var canExecuteChangedRaised = false;
        vm.ResetAndRetryCommand.CanExecuteChanged += (_, _) => canExecuteChangedRaised = true;

        // The row is the same instance Mission Control flips when a ConPTY pane closes —
        // the command's CanExecute must react without the bound Task itself changing.
        row.HasInteractiveSession = false;

        Assert.True(canExecuteChangedRaised);
        Assert.True(vm.ResetAndRetryCommand.CanExecute(null));
    }

    [Fact]
    public void ResetAndRetry_IsEnabled_ForTerminalTaskWithoutInteractiveSession()
    {
        var vm = BuildVm(new RecordingWorkerClient());
        var row = new TaskRowViewModel { Id = "task-reset-3", Status = TaskStatus.Cancelled };
        vm.Bind(row);
        vm.Monitor.ApplyState(TaskStatus.Cancelled);

        Assert.True(vm.ResetAndRetryCommand.CanExecute(null));
    }

    [Fact]
    public void ResetAndRetry_StaysDisabled_AfterSwitchingToAnotherInteractiveTask()
    {
        var vm = BuildVm(new RecordingWorkerClient());
        var firstRow = new TaskRowViewModel { Id = "task-reset-4", Status = TaskStatus.Failed };
        vm.Bind(firstRow);
        vm.Monitor.ApplyState(TaskStatus.Failed);
        Assert.True(vm.ResetAndRetryCommand.CanExecute(null));

        var secondRow = new TaskRowViewModel { Id = "task-reset-5", Status = TaskStatus.Failed, HasInteractiveSession = true };
        vm.Bind(secondRow);
        vm.Monitor.ApplyState(TaskStatus.Failed);

        Assert.False(vm.ResetAndRetryCommand.CanExecute(null));

        // Flipping the old (unsubscribed) row must not resurrect the command for the new task.
        firstRow.HasInteractiveSession = true;
        Assert.False(vm.ResetAndRetryCommand.CanExecute(null));
    }
}
