using ClaudeDo.Data;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Islands;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Ui.Tests.ViewModels;

public class DetailsIslandPrepModeTests : IDisposable
{
    private readonly string _dbPath;

    public DetailsIslandPrepModeTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_prep_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 DetailsIslandViewModel NewDetailsVm(StubWorkerClient stub)
    {
        var factory = new TestDbFactory(NewContext);
        return new DetailsIslandViewModel(factory, stub, new NullServiceProvider(), new ClaudeDo.Ui.Services.MergeCoordinator());
    }


    [Fact]
    public void PrepLine_event_appends_to_PrepLog()
    {
        var stub = new DefaultStub();
        var vm = NewDetailsVm(stub);

        stub.RaisePrepLine("{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"hi\"}]}}");

        Assert.NotEmpty(vm.Prep.PrepLog);
    }

    [Fact]
    public void ShowPrep_sets_prep_mode_and_hides_the_task_detail()
    {
        var vm = NewDetailsVm(new DefaultStub());
        vm.ShowPrep();

        Assert.True(vm.IsPrepMode);
        Assert.False(vm.IsTaskDetailVisible);
    }

    [Fact]
    public async Task ShowPrep_loads_persisted_log_when_empty()
    {
        var stub = new DefaultStub { LastPrepLog = "{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"restored\"}]}}" };
        var vm = NewDetailsVm(stub);

        vm.ShowPrep();
        await vm.Prep.LoadLastPrepLogIfEmptyAsync();

        Assert.NotEmpty(vm.Prep.PrepLog);
    }

    [Fact]
    public async Task PlanDayCommand_calls_worker()
    {
        var stub = new DefaultStub();
        var vm = NewDetailsVm(stub);
        await vm.Prep.PlanDayCommand.ExecuteAsync(null);
        Assert.Equal(1, stub.RunDailyPrepNowCalls);
    }

    [Fact]
    public void ShowPrepEmptyState_true_when_empty_and_not_running()
    {
        var vm = NewDetailsVm(new DefaultStub());
        Assert.True(vm.Prep.ShowPrepEmptyState);
    }
}
