test_that("read_close_series reads toy CSV fixture", {
  csv_path <- testthat::test_path("testdata", "toy_prices.csv")

  px <- read_close_series(csv_path, close_col = "close")

  expect_type(px, "double")
  expect_equal(length(px), 25L)
  expect_true(all(is.finite(px)))
  expect_equal(px[1], 100.00, tolerance = 1e-12)
  expect_equal(px[25], 104.50, tolerance = 1e-12)
})

test_that("compute_log_returns works on fixture prices", {
  csv_path <- testthat::test_path("testdata", "toy_prices.csv")

  px <- read_close_series(csv_path, close_col = "close")
  ret <- compute_log_returns(px)

  expect_type(ret, "double")
  expect_equal(length(ret), length(px) - 1L)
  expect_true(all(is.finite(ret)))
})

test_that("run_kronx works end-to-end from toy CSV fixture", {
  skip_on_cran()

  csv_path <- testthat::test_path("testdata", "toy_prices.csv")

  res <- run_kronx(
    file = csv_path,
    close_col = "close",
    K = 2L,
    n_starts = 1L,
    max_iter = 8L,
    tol = 1e-4,
    tail_alpha = 0.10,
    ruin_horizon = 10L,
    verbose = FALSE,
    output_dir = NULL
  )

  expect_type(res, "list")
  expect_true(is.numeric(res$close_px))
  expect_equal(length(res$close_px), 25L)
  expect_equal(length(res$ret), 24L)
  expect_equal(res$K, 2L)
  expect_equal(dim(res$A_t), c(2L, 2L))
  expect_true(is.numeric(res$ruin_bound))
  expect_true(length(res$ruin_bound) == 1L)
  expect_true(is.finite(res$ruin_bound))
  expect_gte(res$ruin_bound, 0)
  expect_lte(res$ruin_bound, 1)
  expect_identical(res$output_files, NULL)
  expect_identical(res$input_source, csv_path)
})

test_that("run_kronx can find Close with different capitalization", {
  tmp <- tempfile(fileext = ".csv")
  on.exit(unlink(tmp), add = TRUE)

  dat <- data.frame(
    date = sprintf("2026-02-%02d", 1:20),
    Close = c(
      100.0, 100.2, 100.1, 100.5, 100.4,
      100.8, 101.0, 100.9, 101.3, 101.1,
      101.6, 101.5, 101.9, 102.0, 101.8,
      102.2, 102.4, 102.3, 102.7, 102.9
    )
  )

  utils::write.csv(dat, tmp, row.names = FALSE)

  px <- read_close_series(tmp, close_col = "Close")
  expect_equal(length(px), 20L)

  skip_on_cran()

  res <- run_kronx(
    file = tmp,
    close_col = "Close",
    K = 2L,
    n_starts = 1L,
    max_iter = 6L,
    tol = 1e-4,
    tail_alpha = 0.10,
    ruin_horizon = 10L,
    verbose = FALSE,
    output_dir = NULL
  )

  expect_equal(length(res$close_px), 20L)
  expect_equal(length(res$ret), 19L)
})