test_that("Distribution definition and moments work properly", {
  dist_norm <- dist_normal(mean = 10, sd = 2)
  expect_s3_class(dist_norm, "gpci_dist")
  
  moments <- compute_theoretical_moments(dist_norm)
  expect_equal(moments$mean, 10)
  expect_equal(moments$var, 4)
})

test_that("Uncensored data fitting and GPCI capability calculation work without NAs", {
  set.seed(123)
  x_data <- rnorm(50, mean = 10, sd = 1.5)
  dist_n <- dist_normal()
  
  fitted_d <- fit_distribution(x_data, dist_n)
  expect_true(is.list(fitted_d$params))
  expect_gt(fitted_d$params$sd, 0)
  
  cap_res <- capability(
    data = x_data, distribution = dist_n,
    USL = 15, LSL = 5, target = 10,
    indices = c("Cpy", "Cp", "Cpk", "Cpm", "Cpmk", "CpTk", "Spmk", "Cpc", "CNpmc")
  )
  
  expect_type(cap_res, "double")
  expect_false(any(is.na(cap_res)))
  expect_false(any(is.nan(cap_res)))
  expect_gt(cap_res["Cpy"], 0)
})

test_that("Importance Sampling engine generates parameter and GPCI chains correctly", {
  set.seed(456)
  x_data <- rnorm(40, mean = 10, sd = 1)
  
  fit_imp <- impsam_gpci(
    data = x_data,
    distribution = dist_normal(),
    chain_length = 300,
    burn_in = 50,
    thinning = 1,
    USL = 13, LSL = 7, target = 10,
    indices = c("Cpy", "Cp", "Cpk", "Cpm", "Cpmk", "CNpmc")
  )
  
  expect_s3_class(fit_imp, "gpciImpSam")
  expect_equal(nrow(fit_imp$gpci_chain), 300)
  expect_false(any(is.na(as.matrix(fit_imp$gpci_chain))))
  expect_false(any(is.nan(as.matrix(fit_imp$gpci_chain))))
  
  sum_df <- summary(fit_imp)
  expect_s3_class(sum_df, "data.frame")
  expect_true(all(c("Point_Estimate", "Bias", "MSE", "Risk_Value",
                    "HPD90_Lower", "HPD90_Upper",
                    "HPD95_Lower", "HPD95_Upper",
                    "HPD99_Lower", "HPD99_Upper",
                    "HW_Stat", "HW_Pvalue", "HW_Passed", "Convergence_Prob") %in% colnames(sum_df)))
  
  expect_false(any(is.na(sum_df$Bias)))
  expect_false(any(is.na(sum_df$MSE)))
  expect_false(any(is.na(sum_df$Risk_Value)))
  expect_false(any(is.na(sum_df$HPD95_Lower)))
  expect_false(any(is.na(sum_df$Convergence_Prob)))
})

test_that("High-level user interface gpci_impsam works with custom user functions", {
  set.seed(789)
  x_data <- rnorm(30, mean = 10, sd = 1)
  
  res_user <- gpci_impsam(
    data = x_data,
    pdf = function(x, mean = 0, sd = 1) dnorm(x, mean, sd),
    cdf = function(x, mean = 0, sd = 1) pnorm(x, mean, sd),
    chain_length = 200, burn_in = 40,
    USL = 13, LSL = 7
  )
  
  expect_s3_class(res_user, "gpciImpSam")
  sum_res <- summary(res_user)
  expect_gt(nrow(sum_res), 0)
  expect_false(any(is.na(sum_res$Point_Estimate)))
})
