using ClaudeDo.Data.Git;
using ClaudeDo.Worker.Tests.Infrastructure;

namespace ClaudeDo.Worker.Tests.Runner;

public class GitServiceMergeTests : IDisposable
{
    private readonly List<GitRepoFixture> _repos = new();

    private GitRepoFixture NewRepo()
    {
        var r = new GitRepoFixture();
        _repos.Add(r);
        return r;
    }

    public void Dispose()
    {
        foreach (var r in _repos) try { r.Dispose(); } catch { }
    }

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

        var repo = NewRepo();
        var git = new GitService();

        var branch = await git.GetCurrentBranchAsync(repo.RepoDir);

        Assert.False(string.IsNullOrWhiteSpace(branch));
        // Default branch is either "main" or "master" depending on git config.
        Assert.True(branch == "main" || branch == "master",
            $"Expected main or master, got '{branch}'");
    }

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

        var repo = NewRepo();
        GitRepoFixture.RunGit(repo.RepoDir, "branch", "feature/x");

        var git = new GitService();
        var branches = await git.ListLocalBranchesAsync(repo.RepoDir);

        Assert.Contains("feature/x", branches);
        Assert.Contains(branches, b => b == "main" || b == "master");
    }

    [Fact]
    public async Task IsMidMergeAsync_FreshRepo_ReturnsFalse()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var git = new GitService();

        Assert.False(await git.IsMidMergeAsync(repo.RepoDir));
    }

    [Fact]
    public async Task IsMidMergeAsync_MergeHeadPresent_ReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        // Simulate a mid-merge state by dropping a MERGE_HEAD file.
        var mergeHead = Path.Combine(repo.RepoDir, ".git", "MERGE_HEAD");
        File.WriteAllText(mergeHead, "0000000000000000000000000000000000000000\n");

        var git = new GitService();
        Assert.True(await git.IsMidMergeAsync(repo.RepoDir));
    }

    [Fact]
    public async Task MergeNoFfAsync_DivergedNonConflicting_ReturnsZero_AndCreatesMergeCommit()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        // Create a feature branch with one new file.
        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/merge");
        File.WriteAllText(Path.Combine(repo.RepoDir, "feature.txt"), "hello\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "feat: add feature.txt");

        // Back to default and add a non-overlapping file so history diverges.
        string defaultBranch;
        try { defaultBranch = GitRepoFixture.RunGit(repo.RepoDir, "symbolic-ref", "--short", "refs/remotes/origin/HEAD").Trim().Replace("origin/", ""); }
        catch { defaultBranch = "main"; }
        if (string.IsNullOrEmpty(defaultBranch)) defaultBranch = "main";
        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", defaultBranch); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); defaultBranch = "master"; }
        File.WriteAllText(Path.Combine(repo.RepoDir, "other.txt"), "other\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "chore: add other.txt");

        var git = new GitService();
        var (exitCode, stderr) = await git.MergeNoFfAsync(repo.RepoDir, "feature/merge", "Merge feature/merge");

        Assert.Equal(0, exitCode);
        // Confirm merge commit exists (two parents on HEAD).
        var parents = GitRepoFixture.RunGit(repo.RepoDir, "rev-list", "--parents", "-n", "1", "HEAD").Trim();
        Assert.True(parents.Split(' ').Length >= 3, $"Expected merge commit (3 tokens), got: '{parents}'");
    }

    [Fact]
    public async Task MergeNoFfAsync_Conflict_ReturnsNonZero()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        // Both branches modify README.md — guaranteed conflict.
        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/conflict");
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# feature side\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "feat: feature edit");

        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "main"); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); }
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# main side\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "chore: main edit");

        var git = new GitService();
        var (exitCode, _) = await git.MergeNoFfAsync(repo.RepoDir, "feature/conflict", "merge");

        Assert.NotEqual(0, exitCode);
    }

    [Fact]
    public async Task MergeAbortAsync_AfterConflict_ClearsMergeState()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/abort");
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# feat side\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "edit");

        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "main"); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); }
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# main side\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "edit");

        var git = new GitService();
        await git.MergeNoFfAsync(repo.RepoDir, "feature/abort", "merge"); // will conflict

        Assert.True(await git.IsMidMergeAsync(repo.RepoDir));
        await git.MergeAbortAsync(repo.RepoDir);
        Assert.False(await git.IsMidMergeAsync(repo.RepoDir));
    }

    [Fact]
    public async Task CheckoutBranchAsync_ExistingBranch_SwitchesBranch()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        GitRepoFixture.RunGit(repo.RepoDir, "branch", "feature/checkout-test");

        var git = new GitService();
        await git.CheckoutBranchAsync(repo.RepoDir, "feature/checkout-test");

        var current = await git.GetCurrentBranchAsync(repo.RepoDir);
        Assert.Equal("feature/checkout-test", current);
    }

    [Fact]
    public async Task HasChangesAsync_UntrackedFileOnly_DefaultReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        File.WriteAllText(Path.Combine(repo.RepoDir, "untracked.txt"), "new\n");

        var git = new GitService();
        Assert.True(await git.HasChangesAsync(repo.RepoDir));
    }

    [Fact]
    public async Task HasChangesAsync_UntrackedFileOnly_IncludeUntrackedFalse_ReturnsFalse()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        File.WriteAllText(Path.Combine(repo.RepoDir, "untracked.txt"), "new\n");

        var git = new GitService();
        Assert.False(await git.HasChangesAsync(repo.RepoDir, includeUntracked: false));
    }

    [Fact]
    public async Task HasChangesAsync_ModifiedTrackedFile_IncludeUntrackedFalse_StillReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "changed\n");

        var git = new GitService();
        Assert.True(await git.HasChangesAsync(repo.RepoDir, includeUntracked: false));
    }

    [Fact]
    public async Task ListConflictedFilesAsync_MidConflict_ReturnsConflictedFile()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/cflist");
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# feat\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "edit");

        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "main"); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); }
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# main\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "edit");

        var git = new GitService();
        await git.MergeNoFfAsync(repo.RepoDir, "feature/cflist", "merge");

        var files = await git.ListConflictedFilesAsync(repo.RepoDir);
        Assert.Contains("README.md", files);

        await git.MergeAbortAsync(repo.RepoDir);
    }

    [Fact]
    public async Task IsMidRevertAsync_FreshRepo_ReturnsFalse()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var git = new GitService();

        Assert.False(await git.IsMidRevertAsync(repo.RepoDir));
    }

    [Fact]
    public async Task IsMidRevertAsync_RevertHeadPresent_ReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var revertHead = Path.Combine(repo.RepoDir, ".git", "REVERT_HEAD");
        File.WriteAllText(revertHead, "0000000000000000000000000000000000000000\n");

        var git = new GitService();
        Assert.True(await git.IsMidRevertAsync(repo.RepoDir));
    }

    [Fact]
    public async Task RevertMergeCommitAsync_CleanMerge_ReturnsZero_AndUndoesMergedChange()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/revert");
        File.WriteAllText(Path.Combine(repo.RepoDir, "feature.txt"), "hello\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "feat: add feature.txt");

        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "main"); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); }

        var git = new GitService();
        var (mergeExit, _) = await git.MergeNoFfAsync(repo.RepoDir, "feature/revert", "Merge feature/revert");
        Assert.Equal(0, mergeExit);
        var mergeSha = (await git.RevParseHeadAsync(repo.RepoDir)).Trim();
        Assert.True(File.Exists(Path.Combine(repo.RepoDir, "feature.txt")));

        var (revertExit, _) = await git.RevertMergeCommitAsync(repo.RepoDir, mergeSha);

        Assert.Equal(0, revertExit);
        Assert.False(File.Exists(Path.Combine(repo.RepoDir, "feature.txt")));
        Assert.False(await git.IsMidRevertAsync(repo.RepoDir));
        // History stays intact — both the merge and the new revert commit are reachable.
        var log = GitRepoFixture.RunGit(repo.RepoDir, "log", "--oneline");
        Assert.Contains(mergeSha[..7], log);
    }

    [Fact]
    public async Task RevertMergeCommitAsync_ConflictingSubsequentEdit_ReturnsNonZero_AndAbortCleansUp()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();

        GitRepoFixture.RunGit(repo.RepoDir, "checkout", "-b", "feature/revert-conflict");
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# test repo\nfeature\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "feat: append feature line");

        try { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "main"); }
        catch { GitRepoFixture.RunGit(repo.RepoDir, "checkout", "master"); }

        var git = new GitService();
        var (mergeExit, _) = await git.MergeNoFfAsync(repo.RepoDir, "feature/revert-conflict", "Merge feature/revert-conflict");
        Assert.Equal(0, mergeExit);
        var mergeSha = (await git.RevParseHeadAsync(repo.RepoDir)).Trim();

        // A direct edit on main to the same line the merge introduced makes the revert conflict.
        File.WriteAllText(Path.Combine(repo.RepoDir, "README.md"), "# test repo\npost-merge edit\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "chore: edit the same line");
        var headBefore = GitRepoFixture.RunGit(repo.RepoDir, "rev-parse", "HEAD").Trim();

        var (revertExit, _) = await git.RevertMergeCommitAsync(repo.RepoDir, mergeSha);

        Assert.NotEqual(0, revertExit);
        Assert.True(await git.IsMidRevertAsync(repo.RepoDir));
        var conflicted = await git.ListConflictedFilesAsync(repo.RepoDir);
        Assert.Contains("README.md", conflicted);

        await git.RevertAbortAsync(repo.RepoDir);

        Assert.False(await git.IsMidRevertAsync(repo.RepoDir));
        Assert.Equal(headBefore, GitRepoFixture.RunGit(repo.RepoDir, "rev-parse", "HEAD").Trim());
        Assert.True(string.IsNullOrWhiteSpace(GitRepoFixture.RunGit(repo.RepoDir, "status", "--porcelain")));
    }

    [Fact]
    public async Task IsAncestorAsync_EarlierCommit_ReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var first = repo.BaseCommit;

        File.WriteAllText(Path.Combine(repo.RepoDir, "second.txt"), "second\n");
        GitRepoFixture.RunGit(repo.RepoDir, "add", "-A");
        GitRepoFixture.RunGit(repo.RepoDir, "commit", "-m", "chore: second commit");

        var git = new GitService();
        var head = (await git.RevParseHeadAsync(repo.RepoDir)).Trim();

        Assert.True(await git.IsAncestorAsync(repo.RepoDir, first, head));
        Assert.False(await git.IsAncestorAsync(repo.RepoDir, head, first));
    }

    [Fact]
    public async Task IsAncestorAsync_SameCommit_ReturnsTrue()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var git = new GitService();
        var head = (await git.RevParseHeadAsync(repo.RepoDir)).Trim();

        Assert.True(await git.IsAncestorAsync(repo.RepoDir, head, head));
    }

    [Fact]
    public async Task IsAncestorAsync_UnknownCommit_ReturnsNull()
    {
        if (!GitRepoFixture.IsGitAvailable()) return;
        var repo = NewRepo();
        var git = new GitService();
        var head = (await git.RevParseHeadAsync(repo.RepoDir)).Trim();
        var bogus = new string('a', 40);

        Assert.Null(await git.IsAncestorAsync(repo.RepoDir, bogus, head));
    }
}
