# ==============================================================================
# shared-pipeline/utils/traduzir_figura_pt.R
#
# Versao em portugues das figuras cujo script so desenha em ingles. Copia da
# rotina da dissertacao (4-DA-Code/utils/gerar_figuras_residuais_pt.R), que fez
# as figuras -pt depositadas: roda o gerador com FIG_IDIOMA=en, troca so o
# texto nos grobs finais e confere que a parte nao textual ficou identica.
# Nao muda dados, escalas nem geometrias. Legenda e nota vem do capitulo.
#
# Uso, no plot-pt.R de cada post:
#   source(here::here("shared-pipeline", "utils", "traduzir_figura_pt.R"))
#   traduzir_figura_pt(
#     gerador = here::here("posts", "<slug>", "plot.R"),
#     figuras = list(`<fig_label do gerador>` = list(caption = "...", nota = "...")),
#     script_path = here::here("posts", "<slug>", "plot-pt.R")
#   )
# Saida: output/figures/<fig_label>-pt/.
# ==============================================================================
invisible(Sys.setlocale("LC_CTYPE", if (.Platform$OS.type == "windows") "Portuguese_Brazil.utf8" else "C.UTF-8"))
suppressPackageStartupMessages({
  library(ggplot2)
  library(patchwork)
  library(here)
})
source(here::here("shared-pipeline", "utils", "plot_theme.R"), encoding = "UTF-8")

TRADUCOES <- c(
  "Year" = "Ano", "Private" = "Privada", "Public" = "P\u00fablica",
  "Mean income percentile" = "Percentil m\u00e9dio de renda",
  "Whole cohort (p50)" = "Coorte inteira (p50)",
  "Completed upper secondary" = "Concluiu o ensino m\u00e9dio",
  "Entered tertiary" = "Ingressou na educa\u00e7\u00e3o terci\u00e1ria",
  "Entered tertiary, among completers" = "Ingressou, entre concluintes",
  "Wagstaff index (W)" = "\u00cdndice de Wagstaff (W)",
  "Income decile (D1 = poorest \u2192 D10 = richest)" = "Decil de renda (D1 = mais pobres \u2192 D10 = mais ricos)",
  "Full period (1992\u20132023)" = "Per\u00edodo completo (1992\u20132023)",
  "Total change in access rate (pp over term)" = "Varia\u00e7\u00e3o total na taxa de acesso (p.p. no mandato)",
  "Gain (pp total)" = "Ganho (p.p. no total)",
  "Not significant (95% CI crosses 0)" = "N\u00e3o significativo (IC de 95% cruza 0)",
  "Entered within three years (%)" = "Ingressou em at\u00e9 tr\u00eas anos (%)",
  "Cohort of 2013" = "Coorte de 2013", "Cohort of 2020" = "Coorte de 2020",
  "Decile of per-capita family income (1 = poorest)" = "Decil de renda familiar per capita (1 = mais pobres)",
  "Distance learning (EaD)" = "Educa\u00e7\u00e3o a dist\u00e2ncia (EaD)",
  "In-person" = "Presencial",
  "Public, affirmative action" = "P\u00fablica, vaga reservada",
  "Public, open competition" = "P\u00fablica, ampla concorr\u00eancia",
  "Private, without subsidy" = "Privada, sem subs\u00eddio",
  "Millions" = "Milh\u00f5es", "Millions (log scale)" = "Milh\u00f5es (escala log)",
  "Upper secondary" = "Ensino m\u00e9dio", "Primary" = "Prim\u00e1rio",
  "Secondary" = "Secund\u00e1rio", "Tertiary" = "Terci\u00e1rio",
  "Enrollment ratio" = "Taxa de matr\u00edcula", "Brazil" = "Brasil",
  "Latin America" = "Am\u00e9rica Latina", "Advanced economies" = "Economias avan\u00e7adas",
  "Asia & Pacific" = "\u00c1sia e Pac\u00edfico", "Eastern Europe" = "Europa Oriental",
  "Middle East & N. Africa" = "Oriente M\u00e9dio e N. da \u00c1frica",
  "Sub-Saharan Africa" = "\u00c1frica Subsaariana",
  "R$ billion (2024 prices)" = "R$ bilh\u00f5es (pre\u00e7os de 2024)",
  "A. Federal universities, excluding retirees and pensions" = "A. Universidades federais, sem inativos e pens\u00f5es",
  "B. Subsidies to private-sector students" = "B. Subs\u00eddios a estudantes do setor privado",
  "Federal budget data (SIOP), same concept" = "Or\u00e7amento federal (SIOP), mesmo conceito",
  "Carvalho (2011), converted to 2024 prices" = "Carvalho (2011), em pre\u00e7os de 2024",
  "FIES student loans disbursed" = "Desembolsos do FIES",
  "ProUni tax expenditure" = "Ren\u00fancia fiscal do ProUni",
  "Undergraduate enrollment (% of population aged 18\u201324)" = "Matr\u00edculas na gradua\u00e7\u00e3o (% da popula\u00e7\u00e3o de 18 a 24 anos)",
  "Gross rate" = "Taxa bruta", "Net rate" = "Taxa l\u00edquida",
  "Undergraduate enrollment (1992 = 100)" = "Matr\u00edculas na gradua\u00e7\u00e3o (1992 = 100)",
  "Harmonized series" = "S\u00e9rie harmonizada",
  "Grey points: all competing sources" = "Pontos cinza: todas as fontes concorrentes",
  "10 thousand" = "10 mil", "100 thousand" = "100 mil",
  "1 million" = "1 milh\u00e3o", "10 million" = "10 milh\u00f5es",
  "Enrollments (log scale)" = "Matr\u00edculas (escala log)",
  "Enrollments (millions)" = "Matr\u00edculas (milh\u00f5es)",
  "Published total\n(in-person only)" = "Total publicado\n(apenas presencial)",
  "Reconstructed total\n(+ separately-tracked EAD)" = "Total reconstru\u00eddo\n(+ EaD registrada \u00e0 parte)",
  "Women" = "Mulheres", "Men" = "Homens",
  "Mean years of schooling" = "M\u00e9dia de anos de estudo",
  "Equal spending per student" = "Mesmo gasto por estudante",
  "Tertiary / primary spending per student (log scale)" = "Gasto por estudante: terci\u00e1rio / prim\u00e1rio (escala log)",
  "GDR6 ratio" = "Raz\u00e3o GDR6",
  "Academic reconstructions" = "Reconstru\u00e7\u00f5es acad\u00eamicas",
  "IBGE compilations" = "Compila\u00e7\u00f5es do IBGE",
  "INEP registers" = "Registros do INEP"
)
traduzir <- function(x, slug = NULL) {
  if (!is.character(x)) return(x)
  z <- unname(TRADUCOES[x])
  x[!is.na(z)] <- z[!is.na(z)]
  x <- sub("^Women overtake men ", "Mulheres ultrapassam homens ", x)
  x <- sub("^Widest gap ", "Maior hiato ", x)
  if (identical(slug, "wagstaff-transicao-condicional")) {
    x[x == "Ingressou na educa\u00e7\u00e3o terci\u00e1ria"] <- "Ingressou"
  }
  if (identical(slug, "delta-acesso-decil-governo")) {
    x[x == "Ganho (p.p. no total)"] <- "Ganho (p.p.)"
    x[x == "N\u00e3o significativo (IC de 95% cruza 0)"] <- "N\u00e3o significativo (IC 95%)"
  }
  if (identical(slug, "educabr2-source-coverage")) {
    x[x == "Compila\u00e7\u00f5es do IBGE"] <- "Compila\u00e7\u00f5es IBGE"
    x[x == "Registros do INEP"] <- "Registros INEP"
  }
  x
}
mapear_grob <- function(g, texto = identity, fonte = NULL) {
  if (inherits(g, "text")) {
    g$label <- texto(g$label)
    if (!is.null(fonte)) g$gp$fontfamily <- fonte
  }
  if (length(g$grobs)) g$grobs <- lapply(g$grobs, mapear_grob, texto, fonte)
  if (length(g$children)) {
    for (i in seq_along(g$children)) {
      g$children[[i]] <- mapear_grob(g$children[[i]], texto, fonte)
    }
  }
  g
}
sem_rotulos <- function(g) mapear_grob(g, function(x) rep("", length(x)))
finalizar_original <- finalizar_figura
# A rotina comum recebe aqui gtables prontos, ja com a fonte de cada device.
salvar_pt <- local({
  .forcar_fonte_plot <- function(plot, fonte) mapear_grob(plot, fonte = fonte)
  f <- finalizar_original
  environment(f) <- environment()
  f
})

traduzir_figura_pt <- function(gerador, figuras, script_path) {
  Sys.setenv(FIG_IDIOMA = "en", PROMOVER_FIGURA = "1")
  resultados <- list()
  env <- new.env(parent = globalenv())
  env$source <- function(file, ...) {
    if (basename(file) == "plot_theme.R") return(invisible(NULL))
    eval(parse(file = file, encoding = "UTF-8"), envir = env)
  }
  env$salvar_grafico <- function(...) invisible(NULL)
  env$write.csv <- function(...) invisible(NULL)
  env$finalizar_figura <- function(plot, fig_label, fig_cap, script_path_gerador = NULL,
                                   nota = NULL, fonte = NULL, apendice = NULL,
                                   largura = LARGURA_TEXTO, altura = ALTURA_PADRAO,
                                   unidades = "in", ...) {
    if (!fig_label %in% names(figuras)) return(invisible(NULL))
    s <- figuras[[fig_label]]
    p <- .forcar_fonte_plot(plot, FONTE_PDF)
    g <- if (inherits(p, "patchwork")) patchwork::patchworkGrob(p) else ggplot2::ggplotGrob(p)
    pt <- mapear_grob(g, function(x) traduzir(x, fig_label))
    stopifnot(identical(sem_rotulos(g), sem_rotulos(pt)))
    out <- salvar_pt(plot = pt, fig_label = paste0(fig_label, "-pt"),
                     fig_cap = s$caption, script_path = script_path,
                     nota = s$nota, fonte = NULL, apendice = NULL,
                     largura = largura, altura = altura, unidades = unidades, idioma = "pt")
    resultados[[fig_label]] <<- out
    cat("PT: ", fig_label, "; geometria nao textual identica\n", sep = "")
    invisible(out)
  }
  eval(parse(file = gerador, encoding = "UTF-8"), envir = env)
  faltam <- setdiff(names(figuras), names(resultados))
  if (length(faltam)) stop("Figuras nao geradas: ", paste(faltam, collapse = ", "))
  invisible(resultados)
}
