# Tests for briefing()

# --- Setup ---
scan_dir <- file.path(tempdir(), "test_briefing")
briefs_dir <- file.path(tempdir(), "test_briefs")
dir.create(scan_dir, showWarnings = FALSE)

# Create a project with DESCRIPTION
pkg_dir <- file.path(scan_dir, "demopkg")
dir.create(pkg_dir, showWarnings = FALSE)
writeLines(c(
    "Package: demopkg",
    "Title: Demo Package",
    "Version: 0.1.0",
    "Imports: stats"
), file.path(pkg_dir, "DESCRIPTION"))

# Create a git repo with a commit
system2("git", c("-C", pkg_dir, "init", "-q"), stdout = FALSE, stderr = FALSE)
system2("git", c("-C", pkg_dir, "config", "user.email", "test@test.com"),
        stdout = FALSE, stderr = FALSE)
system2("git", c("-C", pkg_dir, "config", "user.name", "Test"),
        stdout = FALSE, stderr = FALSE)
system2("git", c("-C", pkg_dir, "add", "-A"), stdout = FALSE, stderr = FALSE)
system2("git", c("-C", pkg_dir, "commit", "-q", "-m", "init"),
        stdout = FALSE, stderr = FALSE)

# --- briefing() returns invisible character, emits via message() ---
msgs <- capture.output(
    result <- briefing("demopkg", scan_dir = scan_dir, briefs_dir = briefs_dir),
    type = "message"
)
expect_true(is.character(result))
expect_true(grepl("Briefing: demopkg", result))
expect_true(any(grepl("Briefing: demopkg", msgs)))

# --- briefing includes DESCRIPTION metadata ---
expect_true(grepl("Demo Package", result))
expect_true(grepl("0.1.0", result))

# --- briefing includes git log ---
expect_true(grepl("Recent commits", result))
expect_true(grepl("init", result))

# --- briefing writes to file ---
outfile <- file.path(briefs_dir, "demopkg.md")
expect_true(file.exists(outfile))

# --- briefing no longer includes memory (moved to agent_context) ---
expect_false(grepl("## Memory", result))

# --- briefing handles missing project gracefully ---
result_missing <- briefing("nonexistent", scan_dir = scan_dir,
                           briefs_dir = briefs_dir)
expect_true(is.character(result_missing))
expect_true(grepl("Briefing: nonexistent", result_missing))

# --- briefing_git() does not leak a system2 warning on a non-repo (#33) ---
# A directory with an invalid .git (passes dir.exists() but `git log` fails
# with status 128) must return character(0) silently, not leak a warning.
fakegit <- file.path(scan_dir, "fakegit")
dir.create(file.path(fakegit, ".git"), recursive = TRUE, showWarnings = FALSE)
expect_silent(git_out <- saber:::briefing_git("fakegit", scan_dir))
expect_equal(git_out, character(0L))

# A plain non-git directory is likewise silent and empty.
plain <- file.path(scan_dir, "plaindir")
dir.create(plain, showWarnings = FALSE)
expect_silent(plain_out <- saber:::briefing_git("plaindir", scan_dir))
expect_equal(plain_out, character(0L))

# --- Cleanup ---
unlink(scan_dir, recursive = TRUE)
unlink(briefs_dir, recursive = TRUE)
