using ClaudeDo.Worker.Skills;
using ClaudeDo.Worker.Tests.Infrastructure;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

namespace ClaudeDo.Worker.Tests.Skills;

public sealed class SessionSkillSeederTests : IDisposable
{
    private readonly string _rootDir;
    private readonly string _skillsRoot;
    private readonly string _workingDir;

    public SessionSkillSeederTests()
    {
        _rootDir = Path.Combine(Path.GetTempPath(), $"claudedo_seeder_test_{Guid.NewGuid():N}");
        _skillsRoot = Path.Combine(_rootDir, "session-skills");
        _workingDir = Path.Combine(_rootDir, "workdir");
        Directory.CreateDirectory(_skillsRoot);
        Directory.CreateDirectory(_workingDir);
    }

    public void Dispose()
    {
        try { Directory.Delete(_rootDir, recursive: true); } catch { /* best effort */ }
    }

    private SessionSkillSeeder CreateSeeder() => new(NullLogger<SessionSkillSeeder>.Instance, _skillsRoot);

    private void WriteInstalledSkill(string name, string fileName = "SKILL.md", string content = "# body")
    {
        var dir = Path.Combine(_skillsRoot, name);
        Directory.CreateDirectory(dir);
        File.WriteAllText(Path.Combine(dir, fileName), content);
    }

    [Fact]
    public async Task SeedAsync_copies_skill_files_into_dot_claude_skills()
    {
        const string skillName = "ponytail";
        WriteInstalledSkill(skillName);
        var seeder = CreateSeeder();

        await seeder.SeedAsync(_workingDir, [skillName], isWorktree: false, CancellationToken.None);

        var destFile = Path.Combine(_workingDir, ".claude", "skills", skillName, "SKILL.md");
        Assert.True(File.Exists(destFile));
        Assert.Equal("# body", File.ReadAllText(destFile));
    }

    [Fact]
    public async Task SeedAsync_empty_list_creates_no_dot_claude_dir()
    {
        var seeder = CreateSeeder();

        await seeder.SeedAsync(_workingDir, [], isWorktree: false, CancellationToken.None);

        Assert.False(Directory.Exists(Path.Combine(_workingDir, ".claude")));
    }

    [Fact]
    public async Task SeedAsync_missing_source_skill_logs_warning_and_does_not_throw()
    {
        var seeder = CreateSeeder();

        await seeder.SeedAsync(_workingDir, ["does-not-exist"], isWorktree: false, CancellationToken.None);

        Assert.False(Directory.Exists(Path.Combine(_workingDir, ".claude", "skills", "does-not-exist")));
    }

    [Fact]
    public async Task SeedAsync_re_seeding_is_idempotent_and_overwrites()
    {
        const string skillName = "ponytail";
        WriteInstalledSkill(skillName, content: "v1");
        var seeder = CreateSeeder();
        await seeder.SeedAsync(_workingDir, [skillName], isWorktree: false, CancellationToken.None);

        WriteInstalledSkill(skillName, content: "v2");
        await seeder.SeedAsync(_workingDir, [skillName], isWorktree: false, CancellationToken.None);

        var destFile = Path.Combine(_workingDir, ".claude", "skills", skillName, "SKILL.md");
        Assert.Equal("v2", File.ReadAllText(destFile));
    }

    [Fact]
    public async Task SeedAsync_non_worktree_does_not_touch_git_exclude()
    {
        // _workingDir is a plain directory (no .git), so a git call would throw if attempted.
        WriteInstalledSkill("ponytail");
        var seeder = CreateSeeder();

        await seeder.SeedAsync(_workingDir, ["ponytail"], isWorktree: false, CancellationToken.None);

        // No exception means git rev-parse was correctly skipped for isWorktree=false.
        Assert.True(Directory.Exists(Path.Combine(_workingDir, ".claude", "skills", "ponytail")));
    }

    [Fact]
    public async Task SeedAsync_worktree_appends_exclude_line_once()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;

        using var repo = new GitRepoFixture();
        WriteInstalledSkill("ponytail");
        var seeder = CreateSeeder();

        await seeder.SeedAsync(repo.RepoDir, ["ponytail"], isWorktree: true, CancellationToken.None);

        var excludeFile = Path.Combine(repo.RepoDir, ".git", "info", "exclude");
        Assert.True(File.Exists(excludeFile));
        var lines = await File.ReadAllLinesAsync(excludeFile);
        Assert.Single(lines, l => l.Trim() == "/.claude/skills/ponytail/");

        // Re-seed: exclude line must not be duplicated.
        await seeder.SeedAsync(repo.RepoDir, ["ponytail"], isWorktree: true, CancellationToken.None);
        var linesAfter = await File.ReadAllLinesAsync(excludeFile);
        Assert.Single(linesAfter, l => l.Trim() == "/.claude/skills/ponytail/");
    }

    [Fact]
    public async Task SeedAsync_worktree_seeded_skill_path_is_ignored_by_git_status()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;

        using var repo = new GitRepoFixture();
        WriteInstalledSkill("ponytail");
        var seeder = CreateSeeder();

        await seeder.SeedAsync(repo.RepoDir, ["ponytail"], isWorktree: true, CancellationToken.None);

        var status = GitRepoFixture.RunGit(repo.RepoDir, "status", "--porcelain");
        Assert.Equal(string.Empty, status.Trim());
    }
}
