# L0：纵轴题切词，不画图、不 render。任何平台可跑。
# 用法（仓库根或 test/ 下均可）：Rscript scripts/book-plot/test/Rscript/test-ylab-stack.R
# 中文字面量用 \u 转义，避免 Windows 代码页影响。

script_dir <- function() {
  arg <- grep("^--file=", commandArgs(trailingOnly = FALSE), value = TRUE)
  if (length(arg) == 0) {
    return(getwd())
  }
  dirname(normalizePath(sub("^--file=", "", arg[[1]])))
}

# 直接读 canonical，不另设镜像
r_dir <- normalizePath(file.path(script_dir(), "..", "..", "R"))
source(file.path(r_dir, "ylab-stack.R"), encoding = "UTF-8")

n_fail <- 0L
check <- function(label, got, want) {
  ok <- identical(got, want)
  cat(if (ok) "ok   " else "FAIL ", label, "\n", sep = "")
  if (!ok) {
    cat("  got: ", paste(got, collapse = " | "), "\n", sep = "")
    cat("  want:", paste(want, collapse = " | "), "\n", sep = "")
    n_fail <<- n_fail + 1L
  }
}
tokens <- function(s) strsplit(stack_ylab(s), "\n", fixed = TRUE)[[1]]

# RD资金投入（亿元）
u <- split_ylab_unit("RD\u8d44\u91d1\u6295\u5165\uff08\u4ebf\u5143\uff09")
check("full-width unit split: title", u$title, "RD\u8d44\u91d1\u6295\u5165")
check("full-width unit split: unit", u$unit, "\uff08\u4ebf\u5143\uff09")
check("RD kept as one token", tokens(u$title),
      c("RD", "\u8d44", "\u91d1", "\u6295", "\u5165"))

# 预算支出(亿元)：半角括号
u2 <- split_ylab_unit("\u9884\u7b97\u652f\u51fa(\u4ebf\u5143)")
check("half-width unit split", c(u2$title, u2$unit),
      c("\u9884\u7b97\u652f\u51fa", "(\u4ebf\u5143)"))

# 组均值效率：无括号则 unit 为空
u3 <- split_ylab_unit("\u7ec4\u5747\u503c\u6548\u7387")
check("no unit", u3$unit, "")

# R&D 长于 RD，优先整段
check("R&D before RD", tokens("R&D\u7ecf\u8d39")[1], "R&D")

# 未登记的拉丁词与小数整段保留
check("latin word and decimal", tokens("NDVI0.5\u503c"), c("NDVI", "0.5", "\u503c"))

# 项目追加保护块（含数字的缩写）
tok_pm <- strsplit(
  stack_ylab("PM2.5\u6d53\u5ea6", keep = c(ylab_keep, "PM2.5")), "\n", fixed = TRUE
)[[1]]
check("custom keep", tok_pm[1], "PM2.5")

check("empty string", stack_ylab(""), "")
check("theme_ylab_stack angle", theme_ylab_stack$axis.title.y$angle, 0)
check("geom_text size unit pt constant", ylab_text_size_pt, 11)

if (n_fail > 0L) {
  cat("L0 failed:", n_fail, "\n")
  quit(status = 1)
}
cat("L0 ok\n")
