# ==============================================================================
# 223_Tese_Matriculas_Setor_Governos.R
#
# Crescimento das matriculas de graduacao por setor (Total, Privado, Publico),
# Brasil, 1992-2024, indexado a 1992 = 100, com a faixa de mandatos
# presidenciais. Figura do capitulo 3 (0302), pedida pelo autor em 2026-10-10
# para acompanhar as taxas liquida e bruta do 041O.
#
# HISTORICO: a primeira versao (commit 688d191, pacote final/matriculas-setor-
# governo/) mostrava o NIVEL em areas empilhadas; o autor pediu no mesmo dia o
# crescimento indexado. Equivale ao Painel B do 222 (Introducao), com base em
# 1992 em vez de 1980 e com a faixa de governos. A leitura dos dados e IDENTICA
# a do 222: mesma prioridade de fontes do educabr2 v6 e mesma imputacao do
# setor privado pela proporcao presencial quando falta o total privado.
#
# FONTE: data_tertiary_v6_clean.xlsx (educabr2).
# PROMOVER = TRUE grava o pacote em 6-images-tables/final/crescimento-matriculas-setor-governo/.
# ==============================================================================

suppressPackageStartupMessages({
  library(readxl)
  library(dplyr)
  library(tidyr)
  library(stringr)
  library(ggplot2)
  library(patchwork)
})

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

PROMOVER <- TRUE
ANO_INI <- 1992

# Planilha-fonte versionada no repositorio publico do pacote educabr2
# (data-raw/sources/tertiary_multisource/). Baixada uma vez para data-raw/.
CAMINHO_V6 <- here::here("data-raw", "educabr2", "data_tertiary_v6_clean.xlsx")
if (!file.exists(CAMINHO_V6)) {
  dir.create(dirname(CAMINHO_V6), showWarnings = FALSE, recursive = TRUE)
  download.file(
    paste0("https://raw.githubusercontent.com/mancano-tales/educabr2/main/",
           "data-raw/sources/tertiary_multisource/data_tertiary_v6_clean.xlsx"),
    CAMINHO_V6, mode = "wb", quiet = TRUE
  )
}
stopifnot(file.exists(CAMINHO_V6))

# ── Leitura: identica ao 222 ─────────────────────────────────────────────────
source_priority <- function(src) {
  case_when(
    str_starts(src, "CENSUP") ~ 1,
    str_starts(src, "Sinopse_CENSUP") ~ 2,
    str_starts(src, "educacao") ~ 3,
    str_detect(src, "Kang-Paese-Felix") ~ 4,
    str_detect(src, "MaduroJunior") ~ 5,
    str_detect(src, "Durham") ~ 6,
    TRUE ~ 7
  )
}

wide <- read_excel(CAMINHO_V6) |>
  filter(enrollment_type %in% c("Total", "Public", "Private", "Total_Presencial",
                                "Private_Presencial"),
         year_key >= 1980) |>
  mutate(src_p = source_priority(data_source)) |>
  arrange(src_p) |>
  distinct(year_key, enrollment_type, .keep_all = TRUE) |>
  select(year_key, enrollment_type, numbahs) |>
  pivot_wider(names_from = enrollment_type, values_from = numbahs) |>
  arrange(year_key) |>
  complete(year_key = full_seq(year_key, 1)) |>
  mutate(
    Total = if_else(is.na(Total), Total_Presencial, Total),
    prop_priv_presencial = Private_Presencial / Total_Presencial,
    Private = if_else(is.na(Private) & !is.na(prop_priv_presencial),
      Total * prop_priv_presencial, Private
    ),
    Public = if_else(is.na(Public), Total - Private, Public)
  )
stopifnot(all(abs(wide$Public + wide$Private - wide$Total) < 1, na.rm = TRUE))

serie <- wide |>
  filter(year_key >= ANO_INI, !is.na(Total)) |>
  select(year_key, Public, Private, Total)
stopifnot(!anyNA(serie), all(diff(serie$year_key) == 1))
ANO_FIM <- max(serie$year_key)

# ── Crescimento indexado, 1992 = 100 (pedido do autor, 2026-10-10) ───────────
# Mesma construcao do Painel B do 222, com base em ANO_INI no lugar de 1980.
NIVEIS <- c("Total", "Private", "Public")
base <- serie[serie$year_key == ANO_INI, ]
dados_indexado <- serie |>
  tidyr::pivot_longer(all_of(NIVEIS), names_to = "serie", values_to = "matriculas") |>
  mutate(indice = 100 * matriculas / unlist(base[serie]),
         serie = factor(serie, levels = NIVEIS))
stopifnot(all(abs(dados_indexado$indice[dados_indexado$year_key == ANO_INI] - 100) < 1e-9))

# ── Grafico ──────────────────────────────────────────────────────────────────
COR_PUBLICO <- PALETA_QUALITATIVA[4]
COR_PRIVADO <- PALETA_QUALITATIVA[1]
CORES <- c(Total = "grey35", Private = COR_PRIVADO, Public = COR_PUBLICO)
TIPOS <- c(Total = "22", Private = "solid", Public = "solid")

# Valor do ultimo ano ao lado do ponto final, como no 222 (so o numero; a
# identificacao das series fica na legenda externa).
fim_indexado <- dados_indexado |>
  filter(year_key == ANO_FIM) |>
  mutate(rotulo = sprintf("%.0f", indice))

escala_x <- scale_x_anos_tese(anos = ANO_INI:ANO_FIM, limits = c(ANO_INI, ANO_FIM),
                              expand = expansion(mult = c(0.015, 0.06)))

grafico <- ggplot(dados_indexado,
                  aes(year_key, indice, colour = serie, linetype = serie)) +
  geom_hline(yintercept = 100, linetype = "dotted", colour = COR_MEDIANA,
             linewidth = 0.3) +
  geom_line(linewidth = 0.7) +
  geom_point(data = fim_indexado, size = 1.2, show.legend = FALSE) +
  geom_text(data = fim_indexado, aes(label = rotulo), hjust = -0.35,
            size = 3.0, fontface = "bold", show.legend = FALSE) +
  scale_colour_manual(name = NULL, values = CORES) +
  scale_linetype_manual(name = NULL, values = TIPOS) +
  escala_x +
  scale_y_continuous(breaks = seq(0, 1000, 100),
                     expand = expansion(mult = c(0.02, 0.04))) +
  coord_cartesian(clip = "off") +
  labs(x = NULL, y = sprintf("Undergraduate enrollment (%d = 100)", ANO_INI)) +
  theme(panel.grid.minor = element_blank(),
        legend.position = "bottom",
        legend.margin = margin(t = 0))

faixa <- banner_governos(fim_dados = ANO_FIM, scale_x = escala_x)
figura <- faixa / grafico + plot_layout(heights = c(1, 12))

salvar_grafico(figura, "223_Matriculas_Setor_Governos")

if (PROMOVER) {
  finalizar_figura(
    plot = figura,
    fig_label = "crescimento-matriculas-setor-governo",
    fig_cap = sprintf("Undergraduate enrollment growth by sector, Brazil, %d–%d (%d = 100).",
                      ANO_INI, ANO_FIM, ANO_INI),
    nota = sprintf(paste0(
      "Total, private and public undergraduate enrollment, including distance ",
      "learning, each indexed to its own %d level (%d = 100); dotted line at 100. ",
      "Numbers at the end of each line give the %d index. Labels along the top ",
      "mark presidential terms."), ANO_INI, ANO_INI, ANO_FIM),
    fonte = sprintf(paste0(
      "INEP --- Censo da Educação Superior: microdata (2009--%d) and published ",
      "Sinopse tables (1995--2008); FGV/IBRE historical series (Kang, Paese and ",
      "Felix 2021) for total enrollment 1992--1994, and Maduro Júnior (2007) for ",
      "the public/private split in those years"), ANO_FIM),
    script_path = here::here("posts", "crescimento-matriculas-setor-governo", "plot.R")
  )
}
