# The 2026 spring clean up has made a fundamental change to the building
# of the results Table. These tests are included to ensure that they don't 
# cause trouble

library(GPArotation)

# Helper: a simple loading matrix for testing
A <- matrix(c(0.9, 0.8, 0.7, 0.1, 0.2, 0.1,
              0.1, 0.2, 0.1, 0.9, 0.8, 0.7),
            nrow = 6, ncol = 2)

# --- Test 1: Table has correct column names ---
res <- GPForth(A, method = "quartimax")
stopifnot(identical(colnames(res$Table), c("iter", "f", "log10(s)", "alpha")))

# --- Test 2: Table has no NA rows (trimming worked) ---
stopifnot(!anyNA(res$Table))

# --- Test 3: Table first column is sequential from 0 ---
stopifnot(res$Table[, 1] == 0:(nrow(res$Table) - 1))

# --- Test 4: Converged result has s < eps in final row ---
eps <- 1e-5
s_final <- 10^res$Table[nrow(res$Table), 3]
stopifnot(s_final < eps)

# --- Test 5: Non-converged case raises a warning ---
A_slow <- matrix(c(0.5, 0.4, 0.6, 0.3, 0.5, 0.4,
                   0.4, 0.5, 0.3, 0.5, 0.4, 0.6,
                   0.3, 0.6, 0.4, 0.5, 0.3, 0.5),
                 nrow = 6, ncol = 3)
res_nc <- suppressWarnings(GPForth(A_slow, method = "quartimax", maxit = 2))

if (res_nc$convergence)
  stop("Test 5 failed: expected non-convergence with maxit = 2")

if (nrow(res_nc$Table) != 3)
  stop("Test 5 failed: expected 3 rows in Table, got ", nrow(res_nc$Table))
  
# --- Test 6: Already-converged initial solution — Table has exactly 1 row ---
Tmat_exact <- diag(ncol(A))
res_exact <- GPForth(A, Tmat = Tmat_exact, method = "quartimax", maxit = 0)
stopifnot(nrow(res_exact$Table) >= 1)