test_that("jgd_server_info() returns connected=TRUE with welcome metadata", {
  skip_on_os("windows")

  server = start_mock_server_local(send_welcome = TRUE)
  withr::defer(server$cleanup())

  jgd(width = 4, height = 3, dpi = 72, socket = server$socket_path)

  info = jgd_server_info()
  expect_type(info, "list")
  expect_true(info$connected)
  expect_identical(info$server_name, "jgd-mock")
  expect_identical(info$protocol_version, 1L)
  expect_identical(info$transport, "unix")
  expect_type(info$server_info, "character")
  expect_identical(info$server_info[["httpUrl"]], "http://127.0.0.1:9999/")

  dev.off()
  server$collect()
})

test_that("jgd_server_info() returns connected=TRUE over TCP", {
  server = start_mock_server_tcp(send_welcome = TRUE)
  withr::defer(server$cleanup())

  jgd(width = 4, height = 3, dpi = 72, socket = server$socket_url)

  info = jgd_server_info()
  expect_type(info, "list")
  expect_true(info$connected)
  expect_identical(info$server_name, "jgd-mock")
  expect_identical(info$protocol_version, 1L)
  expect_identical(info$transport, "tcp")
  expect_identical(info$server_info[["httpUrl"]], "http://127.0.0.1:9999/")

  dev.off()
  server$collect()
})

test_that("jgd_server_info() falls back to discovery file when no welcome", {
  skip_on_os("windows")

  server = start_mock_server_local(send_welcome = FALSE)
  withr::defer(server$cleanup())

  # Write a discovery file
  write_test_discovery(
    '{"serverName":"disc-server","socketPath":"unix:///tmp/test.sock","pid":999}'
  )

  jgd(width = 4, height = 3, dpi = 72, socket = server$socket_path)

  info = jgd_server_info()
  expect_type(info, "list")
  expect_false(info$connected)
  expect_identical(info$server_name, "disc-server")
  expect_identical(info$socket_path, "unix:///tmp/test.sock")
  expect_identical(info$pid, 999L)

  dev.off()
  server$collect()
})

test_that("jgd_server_info() returns NULL for non-jgd device with no discovery", {
  set_empty_discovery_env()

  pdf(tempfile(fileext = ".pdf"))
  withr::defer(dev.off())

  expect_null(jgd_server_info())
})

test_that("jgd_server_info() returns discovery fallback when not connected", {
  skip_on_os("windows")

  write_test_discovery(
    '{"serverName":"fallback","socketPath":"unix:///tmp/fb.sock","pid":42}'
  )

  expect_warning(
    jgd(socket = "unix:///nonexistent-jgd-info-test.sock"),
    "could not connect"
  )

  info = jgd_server_info()
  expect_type(info, "list")
  expect_false(info$connected)
  expect_identical(info$server_name, "fallback")

  dev.off()
})
