# tests/testthat/test-cpy.R
# Test the generalized Cpy index.

test_that("Cpy equals 1.0 under normal when spec limits equal desirable limits", {
  d <- pci_dist_normal(mean = 60, sd = 1)

  # LDL = mu - 3*sigma = 57, UDL = mu + 3*sigma = 63
  # Both actual yield and desired yield are pnorm(63,60,1) - pnorm(57,60,1)
  result <- pci("Cpy", dist = d, LSL = 57, USL = 63, LDL = 57, UDL = 63)
  expect_equal(result, 1.0, tolerance = 1e-6)
})

test_that("Cpy > 1 when spec limits are wider than desirable limits", {
  d <- pci_dist_normal(mean = 60, sd = 1)

  # Wider spec: LSL=56, USL=64 vs desirable LDL=57, UDL=63
  result <- pci("Cpy", dist = d, LSL = 56, USL = 64, LDL = 57, UDL = 63)
  expect_true(result > 1.0)
})

test_that("Cpy < 1 when spec limits are narrower than desirable limits", {
  d <- pci_dist_normal(mean = 60, sd = 1)

  # Narrower spec: LSL=58, USL=62 vs desirable LDL=57, UDL=63
  result <- pci("Cpy", dist = d, LSL = 58, USL = 62, LDL = 57, UDL = 63)
  expect_true(result < 1.0)
})

test_that("Cpy with p0 auto-computes desirable limits correctly", {
  d <- pci_dist_normal(mean = 60, sd = 1)

  # p0 = pnorm(63,60,1) - pnorm(57,60,1) ~ 0.9973002
  p0_val <- stats::pnorm(63, 60, 1) - stats::pnorm(57, 60, 1)

  result <- pci("Cpy", dist = d, LSL = 57, USL = 63, p0 = p0_val)
  expect_equal(result, 1.0, tolerance = 0.01)
})

test_that("Cpy works with non-normal distribution (Weibull)", {
  d_weibull <- pci_dist(
    pdf    = function(x, shape, scale) stats::dweibull(x, shape = shape, scale = scale),
    cdf    = function(x, shape, scale) stats::pweibull(x, shape = shape, scale = scale),
    params = list(shape = 2, scale = 10),
    support = c(0, 50)
  )

  result <- pci("Cpy", dist = d_weibull, LSL = 2, USL = 20, p0 = 0.95)
  expect_true(is.numeric(result))
  expect_true(!is.na(result))
  expect_true(result > 0)
})

test_that("Cpy works when only pdf is supplied (CDF derived numerically)", {
  d_pdf_only <- pci_dist(
    pdf     = function(x, mean, sd) stats::dnorm(x, mean = mean, sd = sd),
    cdf     = NULL,
    params  = list(mean = 60, sd = 1),
    support = c(52, 68)
  )

  result <- pci("Cpy", dist = d_pdf_only, LSL = 57, USL = 63,
                LDL = 57, UDL = 63)
  expect_equal(result, 1.0, tolerance = 0.01)
})

test_that("cpy convenience wrapper works", {
  d <- pci_dist_normal(mean = 60, sd = 1)
  r1 <- cpy(d, LSL = 57, USL = 63, LDL = 57, UDL = 63)
  r2 <- pci("Cpy", dist = d, LSL = 57, USL = 63, LDL = 57, UDL = 63)
  expect_equal(r1, r2)
})
