app_directory <- Sys.getenv("CASCADE_APP_DIR", unset = normalizePath(file.path("..", "..")))
source(file.path(app_directory, "R", "query-state.R"), local = TRUE)

test_that("valid guided-view state decodes to one value per remaining selector", {
  state <- parse_app_query(
    paste0(
      "?sv=2&view=total-failure&density=D&metric=strength&threshold=2",
      "&density_view=extent&threshold_view=contrast&failure_view=steps"
    )
  )

  expect_equal(state$view, "total_failure")
  expect_equal(state$density, "Denser")
  expect_equal(state$metric, "strength")
  expect_equal(state$threshold, "0.20-0.40")
  expect_equal(state$density_view, "extent")
  expect_equal(state$threshold_view, "contrast")
  expect_equal(state$failure_view, "steps")
  expect_false("network" %in% names(state))
  expect_true(all(lengths(state) == 1L))
})

test_that("legacy graph-family URL parameters are ignored", {
  state <- parse_app_query(
    "?view=density&network=BA,WS&density=S,D&metric=degree&threshold=1,2"
  )

  expect_false("network" %in% names(state))
  expect_equal(state$view, "density")
  expect_equal(state$density, "Sparse")
  expect_equal(state$metric, "degree")
  expect_equal(state$threshold, "0.10-0.20")
  expect_equal(state$density_view, query_defaults$density_view)
  expect_equal(state$threshold_view, query_defaults$threshold_view)
  expect_equal(state$failure_view, query_defaults$failure_view)
})

test_that("invalid URL values fall back safely", {
  state <- parse_app_query("?view=unknown&network=DROP&threshold=99")

  expect_equal(state, query_defaults)
  expect_false("network" %in% names(query_defaults))
  expect_false("network" %in% names(query_maps))
})

test_that("guided snapshot state round trips without a graph-family selector", {
  input <- list(
    view = "centrality",
    density = "Sparse",
    metric = "betweenness",
    threshold = "0.40-0.60",
    density_view = "extent",
    threshold_view = "extent",
    failure_view = "steps"
  )
  query <- build_app_query(input)

  expect_false(grepl("network=", query, fixed = TRUE))
  expect_equal(parse_app_query(query), input)
})
