using System.IO;
using ClaudeDo.Localization;
using ClaudeDo.Ui.Localization;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Modals.Settings;
using Xunit;

namespace ClaudeDo.Ui.Tests.ViewModels;

public class SessionSkillsSettingsTabViewModelTests
{
    public SessionSkillsSettingsTabViewModelTests()
    {
        var dir = AppContext.BaseDirectory;
        while (dir is not null && !Directory.Exists(Path.Combine(dir, "src", "ClaudeDo.Localization", "locales")))
            dir = Path.GetDirectoryName(dir);
        Loc.Current = new Localizer(
            LocaleStore.Load(Path.Combine(dir!, "src", "ClaudeDo.Localization", "locales")), "en");
    }

    private sealed class FakeWorker : StubWorkerClient
    {
        public List<SessionSkillDto> Installed = new();
        public string? InstallUrlReceived;
        public string? UpdatedSourceUrl;
        public string? RemovedSourceUrl;
        public Exception? InstallError;
        public TaskCompletionSource<List<string>>? InstallGate;
        public TaskCompletionSource? UpdateGate;

        public override Task<List<SessionSkillDto>> GetSessionSkillsAsync() => Task.FromResult(Installed);

        public override Task<List<string>> InstallSessionSkillAsync(string url)
        {
            if (InstallError is not null) throw InstallError;
            if (InstallGate is not null) return AwaitInstallGateAsync(url);
            InstallUrlReceived = url;
            Installed = Installed.Append(new SessionSkillDto("new-skill", "desc", url, "abc123", DateTimeOffset.UtcNow)).ToList();
            return Task.FromResult(new List<string> { "new-skill" });
        }

        private async Task<List<string>> AwaitInstallGateAsync(string url)
        {
            var installed = await InstallGate!.Task;
            InstallUrlReceived = url;
            return installed;
        }

        public override async Task UpdateSessionSkillAsync(string sourceUrl)
        {
            if (UpdateGate is not null) await UpdateGate.Task;
            UpdatedSourceUrl = sourceUrl;
        }

        public override Task RemoveSessionSkillAsync(string sourceUrl)
        {
            RemovedSourceUrl = sourceUrl;
            Installed = Installed.Where(s => s.SourceUrl != sourceUrl).ToList();
            return Task.CompletedTask;
        }
    }

    [Fact]
    public async Task LoadAsync_populates_skills_from_worker()
    {
        var w = new FakeWorker { Installed = new() { new SessionSkillDto("a", "desc-a", "url-a", "ref-a", DateTimeOffset.UtcNow) } };
        var vm = new SessionSkillsSettingsTabViewModel(w);

        await vm.LoadAsync();

        Assert.Single(vm.Skills);
        Assert.Equal("a", vm.Skills[0].Name);
    }

    [Fact]
    public async Task InstallAsync_installs_then_refreshes_and_sets_status()
    {
        var w = new FakeWorker();
        var vm = new SessionSkillsSettingsTabViewModel(w) { InstallUrl = "https://example.com/repo.git" };

        await vm.InstallCommand.ExecuteAsync(null);

        Assert.Equal("https://example.com/repo.git", w.InstallUrlReceived);
        Assert.Single(vm.Skills);
        Assert.Equal("new-skill", vm.Skills[0].Name);
        Assert.Contains("new-skill", vm.StatusMessage);
        Assert.Equal("", vm.InstallUrl);
    }

    [Fact]
    public async Task InstallAsync_surfaces_exception_message_on_failure()
    {
        // The worker actually throws a HubException on a name collision; any Exception with a
        // readable Message exercises the same catch-and-surface path in the view model.
        var w = new FakeWorker { InstallError = new InvalidOperationException("Skill 'foo' already installed from a different source.") };
        var vm = new SessionSkillsSettingsTabViewModel(w) { InstallUrl = "https://example.com/dup.git" };

        await vm.InstallCommand.ExecuteAsync(null);

        Assert.Contains("already installed", vm.StatusMessage);
        Assert.Empty(vm.Skills);
        Assert.False(vm.InstallOp.IsRunning);
        Assert.True(vm.InstallCommand.CanExecute(null));
    }

    [Fact]
    public async Task InstallAsync_does_nothing_for_blank_url()
    {
        var w = new FakeWorker();
        var vm = new SessionSkillsSettingsTabViewModel(w) { InstallUrl = "   " };

        await vm.InstallCommand.ExecuteAsync(null);

        Assert.Null(w.InstallUrlReceived);
    }

    [Fact]
    public async Task InstallAsync_WhileRunning_IsRunningTrue_AndCommandLocked()
    {
        var w = new FakeWorker { InstallGate = new TaskCompletionSource<List<string>>() };
        var vm = new SessionSkillsSettingsTabViewModel(w) { InstallUrl = "https://example.com/repo.git" };

        var execution = vm.InstallCommand.ExecuteAsync(null);

        Assert.True(vm.InstallOp.IsRunning);
        Assert.False(vm.InstallCommand.CanExecute(null));

        w.InstallGate.SetResult(new List<string> { "new-skill" });
        await execution;

        Assert.False(vm.InstallOp.IsRunning);
        Assert.True(vm.InstallCommand.CanExecute(null));
    }

    [Fact]
    public async Task UpdateAsync_WhileRunning_IsRunningTrue_AndCommandLocked()
    {
        var w = new FakeWorker
        {
            Installed = new() { new SessionSkillDto("a", "", "url-a", "ref-a", DateTimeOffset.UtcNow) },
            UpdateGate = new TaskCompletionSource(),
        };
        var vm = new SessionSkillsSettingsTabViewModel(w);
        await vm.LoadAsync();

        var execution = vm.UpdateCommand.ExecuteAsync("url-a");

        Assert.True(vm.UpdateOp.IsRunning);
        Assert.False(vm.UpdateCommand.CanExecute("url-a"));

        w.UpdateGate.SetResult();
        await execution;

        Assert.False(vm.UpdateOp.IsRunning);
        Assert.True(vm.UpdateCommand.CanExecute("url-a"));
    }

    [Fact]
    public async Task RemoveAsync_removes_then_refreshes()
    {
        var w = new FakeWorker { Installed = new() { new SessionSkillDto("a", "", "url-a", "ref-a", DateTimeOffset.UtcNow) } };
        var vm = new SessionSkillsSettingsTabViewModel(w);
        await vm.LoadAsync();

        await vm.RemoveCommand.ExecuteAsync("url-a");

        Assert.Equal("url-a", w.RemovedSourceUrl);
        Assert.Empty(vm.Skills);
    }

    [Fact]
    public async Task UpdateAsync_calls_worker_then_refreshes()
    {
        var w = new FakeWorker { Installed = new() { new SessionSkillDto("a", "", "url-a", "ref-a", DateTimeOffset.UtcNow) } };
        var vm = new SessionSkillsSettingsTabViewModel(w);
        await vm.LoadAsync();

        await vm.UpdateCommand.ExecuteAsync("url-a");

        Assert.Equal("url-a", w.UpdatedSourceUrl);
        Assert.NotEmpty(vm.StatusMessage);
    }

    [Fact]
    public async Task LoadAsync_marks_rows_selected_per_given_names()
    {
        var w = new FakeWorker
        {
            Installed = new()
            {
                new SessionSkillDto("a", "", "url-a", "ref", DateTimeOffset.UtcNow),
                new SessionSkillDto("b", "", "url-b", "ref", DateTimeOffset.UtcNow),
            },
        };
        var vm = new SessionSkillsSettingsTabViewModel(w);

        await vm.LoadAsync(new List<string> { "b" });

        Assert.False(vm.Skills.Single(s => s.Name == "a").IsSelected);
        Assert.True(vm.Skills.Single(s => s.Name == "b").IsSelected);
    }

    [Fact]
    public async Task SelectedSkillNames_round_trips_through_toggle()
    {
        var w = new FakeWorker { Installed = new() { new SessionSkillDto("a", "", "url-a", "ref", DateTimeOffset.UtcNow) } };
        var vm = new SessionSkillsSettingsTabViewModel(w);
        await vm.LoadAsync(null);

        Assert.Null(vm.SelectedSkillNames());

        vm.Skills.Single().IsSelected = true;

        Assert.Equal(new List<string> { "a" }, vm.SelectedSkillNames());
    }

    [Fact]
    public async Task RefreshAfterInstall_preserves_existing_selection()
    {
        // Install/Update/Remove call LoadAsync() with no explicit selection — that must not
        // reset the checkbox state of the skills that were already selected.
        var w = new FakeWorker { Installed = new() { new SessionSkillDto("a", "", "url-a", "ref", DateTimeOffset.UtcNow) } };
        var vm = new SessionSkillsSettingsTabViewModel(w) { InstallUrl = "https://example.com/repo.git" };
        await vm.LoadAsync(new List<string> { "a" });
        Assert.True(vm.Skills.Single(s => s.Name == "a").IsSelected);

        await vm.InstallCommand.ExecuteAsync(null);

        Assert.True(vm.Skills.Single(s => s.Name == "a").IsSelected);
        Assert.False(vm.Skills.Single(s => s.Name == "new-skill").IsSelected);
    }
}
