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;

/// Verifies that ResolveConfigAsync's skill resolution (union of task/list/global,
/// filtered to what's actually installed in the registry) reaches the seeder call
/// before Claude is invoked.
public sealed class SkillSeedingWireTests : IDisposable
{
    private readonly DbFixture _db = new();
    private readonly string _tempDir;
    private readonly WorkerConfig _cfg;

    public SkillSeedingWireTests()
    {
        _tempDir = Path.Combine(Path.GetTempPath(), $"cd_skillwire_{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 Runner, FakeSessionSkillSeeder Seeder) BuildRunner()
    {
        var dbFactory = _db.CreateFactory();
        var state = TaskStateServiceBuilder.Build(dbFactory).State;
        var wt = new WorktreeManager(new GitService(), dbFactory, _cfg, NullLogger<WorktreeManager>.Instance);
        var fake = new FakeClaudeProcess((_, _, _, _, _) =>
            Task.FromResult(new RunResult { ExitCode = 0, ResultMarkdown = "ok" }));
        var seeder = new FakeSessionSkillSeeder();
        var runner = new TaskRunner(fake, dbFactory, new HubBroadcaster(new CapturingHubContext()), wt,
            new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
            new AttachmentStore(), seeder, new FakeTranscriptUsageReader());
        return (runner, seeder);
    }

    private async Task SeedInstalledSkillAsync(string name)
    {
        using var ctx = _db.CreateContext();
        await new SessionSkillRepository(ctx).UpsertAsync(new SessionSkillEntity
        {
            Name = name,
            SourceUrl = "https://example.test/repo.git",
            PinnedRef = "deadbeef",
            Subpath = $"skills/{name}",
            Description = "test skill",
            AddedAt = DateTimeOffset.UtcNow,
        });
    }

    [Fact]
    public async Task Union_of_task_list_global_skills_reaches_seeder_when_all_installed()
    {
        await SeedInstalledSkillAsync("alpha");
        await SeedInstalledSkillAsync("beta");
        await SeedInstalledSkillAsync("gamma");

        var dbFactory = _db.CreateFactory();
        using (var ctx = _db.CreateContext())
        {
            ctx.Lists.Add(new ListEntity { Id = "l1", Name = "L", WorkingDir = null, CreatedAt = DateTime.UtcNow });
            ctx.ListConfigs.Add(new ListConfigEntity { ListId = "l1", SessionSkills = """["beta"]""" });
            ctx.Tasks.Add(new TaskEntity
            {
                Id = "t1", ListId = "l1", Title = "Task", Status = TaskStatus.Idle,
                CreatedAt = DateTime.UtcNow, SessionSkills = """["alpha"]""",
            });
            // AppSettingsRepository.UpdateAsync doesn't round-trip SessionSkills yet (out of
            // scope here), so seed the singleton row directly.
            await new AppSettingsRepository(ctx).GetAsync();
            ctx.AppSettings.First(s => s.Id == AppSettingsEntity.SingletonId).SessionSkills = """["gamma"]""";
            await ctx.SaveChangesAsync();
        }

        var (runner, seeder) = BuildRunner();
        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync("t1"))!, "slot-1", CancellationToken.None);

        Assert.Single(seeder.Calls);
        var call = seeder.Calls.Single();
        Assert.Equal(["alpha", "beta", "gamma"], call.SkillNames);
        Assert.False(call.IsWorktree);
    }

    [Fact]
    public async Task Unknown_skill_names_are_dropped_before_seeding()
    {
        await SeedInstalledSkillAsync("known");

        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 = "t1", ListId = "l1", Title = "Task", Status = TaskStatus.Idle,
                CreatedAt = DateTime.UtcNow, SessionSkills = """["known","not-installed"]""",
            });
            await ctx.SaveChangesAsync();
        }

        var (runner, seeder) = BuildRunner();
        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync("t1"))!, "slot-1", CancellationToken.None);

        Assert.Single(seeder.Calls);
        Assert.Equal(["known"], seeder.Calls.Single().SkillNames);
    }

    [Fact]
    public async Task No_skills_configured_seeds_empty_list()
    {
        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 = "t1", ListId = "l1", Title = "Task", Status = TaskStatus.Idle, CreatedAt = DateTime.UtcNow,
            });
            await ctx.SaveChangesAsync();
        }

        var (runner, seeder) = BuildRunner();
        using (var ctx = _db.CreateContext())
            await runner.RunAsync((await new TaskRepository(ctx).GetByIdAsync("t1"))!, "slot-1", CancellationToken.None);

        Assert.Single(seeder.Calls);
        Assert.Empty(seeder.Calls.Single().SkillNames);
    }
}
