using ClaudeDo.Data;
using ClaudeDo.Data.Git;
using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Config;
using ClaudeDo.Worker.External;
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;

/// <summary>
/// get_effective_run_config (ConfigMcpTools) must report exactly what TaskRunner actually
/// dispatches with — both go through EffectiveRunConfigResolver.Resolve, but this test proves
/// it end to end via TaskRunner's real CLI args instead of trusting the shared code path alone.
/// </summary>
public sealed class EffectiveRunConfigParityTests : IDisposable
{
    private readonly DbFixture _db = new();
    private readonly string _tempDir;
    private readonly WorkerConfig _cfg;

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

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

    [Fact]
    public async Task Reported_model_and_max_turns_match_what_TaskRunner_dispatches_with()
    {
        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", Model = "opus", MaxTurns = 999 });
            ctx.Tasks.Add(new TaskEntity
            {
                Id = "t1", ListId = "l1", Title = "Task", Status = TaskStatus.Idle, CreatedAt = DateTime.UtcNow,
            });
            await ctx.SaveChangesAsync();
        }

        var state = TaskStateServiceBuilder.Build(dbFactory).State;
        var wt = new WorktreeManager(new GitService(), dbFactory, _cfg, NullLogger<WorktreeManager>.Instance);
        IReadOnlyList<string>? capturedArgs = null;
        var fake = new FakeClaudeProcess((_, _, args, _, _) =>
        {
            capturedArgs = args;
            return Task.FromResult(new RunResult { ExitCode = 0, ResultMarkdown = "ok" });
        });
        var runner = new TaskRunner(fake, dbFactory, new HubBroadcaster(new CapturingHubContext()), wt,
            new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
            new AttachmentStore(), new FakeSessionSkillSeeder(), new FakeTranscriptUsageReader());

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

        var args = capturedArgs!.ToList();
        var actualModel = args[args.IndexOf("--model") + 1];
        var actualMaxTurns = args[args.IndexOf("--max-turns") + 1];

        using var reportCtx = _db.CreateContext();
        var tools = new ConfigMcpTools(
            new ListRepository(reportCtx), new TaskRepository(reportCtx),
            new HubBroadcaster(new CapturingHubContext()), dbFactory);
        var effective = await tools.GetEffectiveRunConfig("t1", CancellationToken.None);

        Assert.Equal(actualModel, effective.Model.Value);
        Assert.Equal(actualMaxTurns, effective.MaxTurns.Effective.ToString());
        Assert.Equal(999, effective.MaxTurns.Requested);
        Assert.True(effective.MaxTurns.Clamped);
    }
}
