# ==============================================================================
# posts/portas-renda-coortes-anuais/plot.R
#
# Vias de ingresso no ensino superior por decil de renda per capita, coorte a
# coorte, de 2012 a 2021. Estende os posts portas-renda-coortes-empilhado e
# portas-renda-coortes-ead (so 2013 e 2020) e conta os inscritos no ENEM,
# inclusive ausentes, como essas comparacoes de duas coortes
# (ver shared-pipeline/sedap/portas-anuais/020_Extrair_Coortes_Anuais.R).
#
# Renda per capita e decis: mesmos pontos medios e mesma regra de 052/055
# (celulas faixa x grupo de moradores ordenadas por renda per capita e
# cortadas em decis dentro de cada coorte, celulas na fronteira divididas
# proporcionalmente).
#
# Figuras (cada uma em ingles, -en, e portugues, -pt):
#   fig-vias       probabilidade de ingresso em ate 3 anos, total e por via
#   fig-modalidade probabilidade de ingresso em EaD e presencial
#   fig-cobertura  parcela da coorte com CPF e inscrita no ENEM
# thumbnail.png e a fig-vias em ingles.
#
# Le data/ (redistribuido) ou, se existir, a reextracao em data-raw/.
# ==============================================================================

suppressPackageStartupMessages({
  library(dplyr)
  library(tidyr)
  library(ggplot2)
  library(here)
})

source(here::here("shared-pipeline", "utils", "plot_theme.R"))
theme_set(thesis_theme())

POST <- here::here("posts", "portas-renda-coortes-anuais")
DIR_DATA <- file.path(POST, "data")
COORTES <- 2012:2021
POPULACAO <- Sys.getenv("POPULACAO", "inscritos")
source(here::here("shared-pipeline", "sedap", "portas-anuais", "dados-populacao.R"))
snapshot <- resolver_dados_coortes(here::here(), POPULACAO, COORTES)
# Sensitivity runs must not overwrite the published registered-student figure.
DIR_FIG <- if (POPULACAO == "inscritos") POST else
  here::here("output", "figures", "portas-renda-coortes-anuais", POPULACAO)
DIR_TABELAS <- if (POPULACAO == "inscritos") DIR_DATA else file.path(DIR_FIG, "data")
dir.create(DIR_FIG, recursive = TRUE, showWarnings = FALSE)
dir.create(DIR_TABELAS, recursive = TRUE, showWarnings = FALSE)

# Record the exact aggregates used alongside the figure for offline replication.
if (normalizePath(snapshot$diretorio) != normalizePath(DIR_TABELAS)) {
  stopifnot(all(file.copy(file.path(snapshot$diretorio, snapshot$arquivos),
                         DIR_TABELAS, overwrite = TRUE)))
}
write.csv(data.frame(populacao = POPULACAO),
          file.path(DIR_TABELAS, "populacao.csv"), row.names = FALSE)

SM_17 <- c(
  A = 0, B = 0.5, C = 1.25, D = 1.75, E = 2.25, F = 2.75, G = 3.5,
  H = 4.5, I = 5.5, J = 6.5, K = 7.5, L = 8.5, M = 9.5, N = 11,
  O = 13.5, P = 17.5, Q = 25
)
MOR_MEDIO <- c("1_2" = 1.8, "3_4" = 3.5, "5_6" = 5.4, "7_mais" = 7.8)

ler <- function(nome) {
  arq <- file.path(snapshot$diretorio, nome)
  if (nome == "sondagem_bas.csv") {
    arq <- here::here("data-raw", "sedap", "portas-anuais", nome)
    if (!file.exists(arq)) arq <- file.path(DIR_DATA, nome)
  }
  if (!file.exists(arq)) stop("Arquivo ausente: ", nome, ". Rode shared-pipeline/sedap/portas-anuais/.")
  read.csv(arq, stringsAsFactors = FALSE)
}

# Celulas faixa x moradores -> decis de renda per capita (regra de 051/052).
por_decil <- function(m, k = 10) {
  cel <- m |>
    mutate(COD = as.character(COD), rpc = unname(SM_17[FAIXA_RENDA]) / unname(MOR_MEDIO[MORADORES_GRUPO])) |>
    pivot_wider(
      id_cols = c(FAIXA_RENDA, MORADORES_GRUPO, rpc), names_from = COD,
      values_from = N, values_fill = 0, names_prefix = "c"
    )
  if (anyNA(cel$rpc)) stop("Celula sem renda per capita (faixa ou grupo de moradores fora do mapa).")
  cel <- cel |>
    mutate(n_cel = rowSums(across(starts_with("c")))) |>
    arrange(rpc, desc(unname(MOR_MEDIO[MORADORES_GRUPO])))
  tot <- sum(cel$n_cel)
  ini <- c(0, cumsum(cel$n_cel)[-nrow(cel)]) / tot
  fim <- cumsum(cel$n_cel) / tot
  cortes <- seq(0, 1, length.out = k + 1)
  cods <- grep("^c[0-9]$", names(cel), value = TRUE)
  bind_rows(lapply(seq_len(k), function(d) {
    w <- pmax(0, pmin(fim, cortes[d + 1]) - pmax(ini, cortes[d])) / pmax(fim - ini, .Machine$double.eps)
    n_d <- sum(w * cel$n_cel)
    data.frame(
      decil = d, n = n_d, cod = sub("^c", "", cods),
      p = 100 * vapply(cods, function(cc) sum(w * cel[[cc]]), numeric(1)) / n_d,
      row.names = NULL
    )
  }))
}

vias <- bind_rows(lapply(COORTES, function(a) por_decil(ler(sprintf("matriz_%d_porta.csv", a))) |> mutate(coorte = a)))
modal <- bind_rows(lapply(COORTES, function(a) por_decil(ler(sprintf("matriz_%d_modalidade.csv", a))) |> mutate(coorte = a)))
stopifnot(all(vias$p >= 0 & vias$p <= 100), all(modal$p >= 0 & modal$p <= 100))

# Total = soma das vias (cod 1-5); cod 0 = nao ingressou.
vias_tot <- vias |>
  filter(cod != "0") |>
  group_by(coorte, decil) |>
  summarise(p = sum(p), .groups = "drop") |>
  mutate(cod = "T")
vias <- bind_rows(vias |> filter(cod != "0"), vias_tot)

# Tabela de saida com os numeros da figura, para conferencia.
write.csv(
  bind_rows(vias |> mutate(tipo = "via"), modal |> filter(cod != "0") |> mutate(tipo = "modalidade")) |>
    select(tipo, coorte, decil, cod, p) |> mutate(p = round(p, 2)),
  file.path(DIR_TABELAS, "probabilidades_por_decil.csv"),
  row.names = FALSE
)

# ------------------------------------------------------------------------------
# Rotulos
# ------------------------------------------------------------------------------
TXT <- list(
  en = list(
    vias = c(
      T = "Total entry", `1` = "Public, affirmative action", `2` = "Public, open competition",
      `3` = "ProUni", `4` = "FIES", `5` = "Private, without subsidy"
    ),
    modal = c(`1` = "Distance learning", `2` = "In-person"),
    x = "Secondary-school cohort (entry within the next three years)",
    y = "Probability of entry", decil = "Income decile",
    decis = c("1st", "2nd", "3rd", paste0(4:10, "th")),
    cob = c(cpf = "With CPF (linkable)", enem = if (POPULACAO == "inscritos") "Registered for ENEM" else "Present at all four ENEM tests"),
    ycob = "Share of the final-year cohort",
    sep = "."
  ),
  pt = list(
    vias = c(
      T = "Ingresso total", `1` = "Pública, vaga reservada", `2` = "Pública, ampla concorrência",
      `3` = "ProUni", `4` = "FIES", `5` = "Privada, sem subsídio"
    ),
    modal = c(`1` = "Educação a distância", `2` = "Presencial"),
    x = "Coorte do ensino médio (ingresso nos três anos seguintes)",
    y = "Probabilidade de ingresso", decil = "Decil de renda",
    decis = paste0(1:10, "º"),
    cob = c(cpf = "Com CPF (vinculável)", enem = if (POPULACAO == "inscritos") "Inscrito no ENEM" else "Presente nas quatro provas do ENEM"),
    ycob = "Parcela da coorte da série final",
    sep = ","
  )
)

CORES_DECIL <- rev(.paleta_sequencial_hcl(12)[1:10]) # claro = mais pobre

grafico_decis <- function(d, rot, L, ncol) {
  d <- d |> mutate(
    painel = factor(rot[cod], levels = rot),
    decil_f = factor(decil, levels = 1:10, labels = L$decis)
  )
  ggplot(d, aes(coorte, p / 100, colour = decil_f, group = decil_f)) +
    geom_line(linewidth = 0.45) +
    geom_point(size = 0.7) +
    facet_wrap(~painel, ncol = ncol, scales = "free_y") +
    scale_colour_manual(
      values = CORES_DECIL, name = L$decil,
      guide = guide_legend(nrow = 1, label.position = "bottom", keywidth = unit(11, "pt"))
    ) +
    scale_x_continuous(breaks = seq(2012, 2021, 3), minor_breaks = NULL) +
    scale_y_continuous(labels = scales::percent_format(accuracy = 1, decimal.mark = L$sep)) +
    expand_limits(y = 0) +
    labs(x = L$x, y = L$y) +
    theme(legend.position = "top")
}

# Cobertura: BAS (sondagem) e N presente no ENEM (soma da matriz da coorte).
bas <- ler("sondagem_bas.csv") |> filter(ano %in% COORTES)
n_enem <- vapply(COORTES, function(a) sum(ler(sprintf("matriz_%d_porta.csv", a))$N), numeric(1))
cob <- bas |>
  transmute(coorte = ano, cpf = N_COM_CPF / N_SERIE_FINAL, enem = n_enem[match(ano, COORTES)] / N_SERIE_FINAL) |>
  pivot_longer(c(cpf, enem), names_to = "serie", values_to = "s")
write.csv(cob |> mutate(s = round(100 * s, 2)), file.path(DIR_TABELAS, "cobertura.csv"), row.names = FALSE)

salvar <- function(p, nome, altura) {
  ggsave(file.path(DIR_FIG, nome), p, width = LARGURA_TEXTO, height = altura, dpi = 300, bg = "white")
}

# ------------------------------------------------------------------------------
# Barras empilhadas por coorte: o desenho dos posts portas-renda-coortes-
# empilhado (052) e portas-renda-coortes-ead (055), um painel por coorte.
# ------------------------------------------------------------------------------
# Ordem de empilhamento da 052: o primeiro nivel fica no topo da barra.
ORDEM_VIAS <- c("1", "4", "3", "2", "5")
COR_VIAS <- setNames(
  c(PALETA_QUALITATIVA[[1]], PALETA_QUALITATIVA[[5]], PALETA_QUALITATIVA[[3]], PALETA_QUALITATIVA[[4]], PALETA_QUALITATIVA[[2]]),
  ORDEM_VIAS
)
COR_MODAL <- setNames(c(PALETA_QUALITATIVA[[5]], PALETA_QUALITATIVA[[2]]), c("1", "2"))
TAM_ROTULO <- 1.9
LIMIAR_ROTULO <- 6 # pontos percentuais de altura; segmentos menores ficam sem rotulo

cor_texto <- function(hex) {
  rgb <- grDevices::col2rgb(hex) / 255
  ifelse(0.299 * rgb[1, ] + 0.587 * rgb[2, ] + 0.114 * rgb[3, ] > 0.55, "#222222", "white")
}

TXT_BARRAS <- list(
  en = list(x = "Decile of per-capita family income (1 = poorest)", y = "Entered within three years (%)", coorte = "Cohort of %d"),
  pt = list(x = "Decil de renda familiar per capita (1 = mais pobres)", y = "Ingressou em até três anos (%)", coorte = "Coorte de %d")
)

barras_vias <- function(L, B) {
  d <- vias |>
    filter(cod %in% ORDEM_VIAS) |>
    mutate(via = factor(cod, levels = ORDEM_VIAS))
  # y do rotulo na ordem de position_stack (ultimo nivel embaixo), antes de filtrar.
  rot <- d |>
    arrange(coorte, decil, desc(as.integer(via))) |>
    group_by(coorte, decil) |>
    mutate(share = 100 * p / sum(p), y_mid = cumsum(p) - p / 2) |>
    ungroup() |>
    filter(p >= LIMIAR_ROTULO) |>
    mutate(cor = cor_texto(COR_VIAS[as.character(via)]), rotulo = sprintf("%.0f%%", share))
  ggplot(d, aes(factor(decil), p, fill = via)) +
    geom_col(position = "stack", width = 0.8) +
    geom_text(data = rot, aes(y = y_mid, label = rotulo, colour = cor), size = TAM_ROTULO, fontface = "bold", show.legend = FALSE) +
    scale_colour_identity() +
    facet_wrap(~coorte, ncol = 2, labeller = as_labeller(function(x) sprintf(B$coorte, as.integer(x)))) +
    scale_fill_manual(name = NULL, values = COR_VIAS, labels = L$vias[ORDEM_VIAS]) +
    scale_y_continuous(expand = expansion(mult = c(0, 0.06))) +
    guides(fill = guide_legend(nrow = 2)) +
    labs(x = B$x, y = B$y) +
    theme(
      panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),
      legend.position = "bottom", legend.key.size = unit(0.7, "lines")
    )
}

barras_modal <- function(L, B) {
  d <- modal |>
    filter(cod %in% c("1", "2")) |>
    mutate(m = factor(cod, levels = c("1", "2")))
  rot <- d |>
    group_by(coorte, decil) |>
    summarise(share = 100 * sum(p[cod == "1"]) / sum(p), topo = sum(p), .groups = "drop") |>
    mutate(rotulo = sprintf("%.0f%%", share))
  ggplot(d, aes(factor(decil), p, fill = m)) +
    geom_col(position = "stack", width = 0.75) +
    geom_text(data = rot, aes(factor(decil), topo, label = rotulo), inherit.aes = FALSE, vjust = -0.5, size = TAM_ROTULO, fontface = "bold") +
    facet_wrap(~coorte, ncol = 2, labeller = as_labeller(function(x) sprintf(B$coorte, as.integer(x)))) +
    scale_fill_manual(name = NULL, values = COR_MODAL, labels = L$modal) +
    scale_y_continuous(expand = expansion(mult = c(0, 0.14))) +
    labs(x = B$x, y = B$y) +
    theme(
      panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(),
      legend.position = "bottom", legend.key.size = unit(0.7, "lines")
    )
}

for (lg in c("en", "pt")) {
  L <- TXT[[lg]]
  f1 <- grafico_decis(vias, L$vias, L, ncol = 2)
  f2 <- grafico_decis(modal |> filter(cod != "0"), L$modal, L, ncol = 2)
  f3 <- ggplot(cob, aes(coorte, s, colour = serie)) +
    geom_line(linewidth = 0.6) +
    geom_point(size = 1.2) +
    scale_colour_manual(values = unname(PALETA_QUALITATIVA[1:2]), labels = L$cob, name = NULL) +
    scale_x_continuous(breaks = COORTES, minor_breaks = NULL) +
    scale_y_continuous(labels = scales::percent_format(accuracy = 1, decimal.mark = L$sep), limits = c(0, 1)) +
    labs(x = NULL, y = L$ycob) +
    theme(legend.position = "top")
  salvar(f1, sprintf("fig-vias-%s.png", lg), 7.6)
  salvar(f2, sprintf("fig-modalidade-%s.png", lg), 3.6)
  salvar(f3, sprintf("fig-cobertura-%s.png", lg), 3.0)
  salvar(barras_vias(L, TXT_BARRAS[[lg]]), sprintf("fig-barras-vias-%s.png", lg), 9.6)
  salvar(barras_modal(L, TXT_BARRAS[[lg]]), sprintf("fig-barras-modalidade-%s.png", lg), 9.6)
}
file.copy(file.path(DIR_FIG, "fig-vias-en.png"), file.path(DIR_FIG, "thumbnail.png"), overwrite = TRUE)

cat("\n[OK] figuras gravadas em posts/portas-renda-coortes-anuais/\n")
