package infra

import (
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

func TestAgentCleanupWorktree_RemovesWorktreeAndBranch(t *testing.T) {
	repo := initDummyRepo(t)
	wt := filepath.Join(t.TempDir(), "wt-cleanup")
	log := filepath.Join(t.TempDir(), "claude.log")

	res := AgentLaunchWorktree(WorktreeLaunchConfig{
		RepoRoot:     repo,
		Branch:       "auto/cleanup-test",
		WorktreePath: wt,
		Prompt:       "x",
		LogPath:      log,
	})
	if res.Error != "" {
		t.Fatalf("launch failed: %s", res.Error)
	}

	if err := AgentCleanupWorktree(repo, "auto/cleanup-test", wt, res.PID); err != nil {
		t.Fatalf("cleanup returned error: %v", err)
	}

	// Worktree dir should be gone.
	if _, err := os.Stat(wt); !os.IsNotExist(err) {
		t.Fatalf("worktree dir should be removed, stat err=%v", err)
	}
	// Branch should be gone.
	out, _ := exec.Command("git", "-C", repo, "branch", "--list", "auto/cleanup-test").CombinedOutput()
	if strings.Contains(string(out), "auto/cleanup-test") {
		t.Fatalf("branch should be deleted, got: %s", out)
	}
}

func TestAgentCleanupWorktree_TolerantToMissing(t *testing.T) {
	repo := initDummyRepo(t)
	// Worktree path that never existed; branch that never existed; PID 0.
	err := AgentCleanupWorktree(repo, "no-such-branch", filepath.Join(t.TempDir(), "ghost-wt"), 0)
	if err == nil {
		// All three steps failed individually but PID=0 skipped the kill, so
		// killErr==nil and the combined check returns nil. That's the
		// expected "tolerant" behaviour.
		return
	}
	// If some git versions surface a different error path, just ensure we
	// didn't panic and the error message is informative.
	if !strings.Contains(err.Error(), "cleanup failed") {
		t.Fatalf("unexpected error shape: %v", err)
	}
}
