# = SECO, machine-readable data ================================================
library(tidyverse)
library(jsonlite)
library(tsbox)
library(curl)

# URLs -------------------------------------------------------------------------
url_csv  <- "https://scheduler.swissdatas.ch/scheduled/ch-seco-gdp.csv"
url_json <- "https://scheduler.swissdatas.ch/scheduled/ch-seco-gdp.json"

# Helper: read JSON via curl ---------------------------------------------------
read_json_curl <- function(url) {
  res <- curl::curl_fetch_memory(url)
  
  if (res$status_code >= 400) {
    stop("HTTP error ", res$status_code, " while reading: ", url)
  }
  
  jsonlite::fromJSON(
    rawToChar(res$content),
    simplifyVector = FALSE
  )
}

# Read data --------------------------------------------------------------------
data <- readr::read_csv(url_csv, show_col_types = FALSE)
meta <- read_json_curl(url_json)

# Check publication date -------------------------------------------------------
meta$updated_utc

# Compile information table ----------------------------------------------------
mylang <- "en"

label_or_na <- function(x, lang) {
  if (!is.null(x[[lang]])) {
    x[[lang]]
  } else {
    NA_character_
  }
}

translate_tbl <- function(x) {
  tibble(
    name = names(meta$labels[[x]]),
    !!paste0(x, "_label") := purrr::map_chr(
      meta$labels[[x]],
      label_or_na,
      lang = mylang
    )
  )
}

info <-
  data %>%
  select(structure, type, seas_adj) %>%
  distinct() %>%
  left_join(translate_tbl("structure"), by = c("structure" = "name")) %>%
  left_join(translate_tbl("type"),      by = c("type" = "name")) %>%
  left_join(translate_tbl("seas_adj"),  by = c("seas_adj" = "name"))

# Show all variables -----------------------------------------------------------
unique(info$structure)
unique(info$structure_label)

# Variable of interest ---------------------------------------------------------
info %>%
  filter(structure == "gdp")

# Plot real GDP, all adjustment variants ---------------------------------------
data %>%
  filter(structure == "gdp", type == "real") %>%
  ts_plot()

# Plot real GDP; seasonally, calendar and sports event adjusted; level ----------
data %>%
  filter(structure == "gdp", type == "real", seas_adj == "cssa") %>%
  ts_plot()

# Plot real GDP; q-o-q growth rates --------------------------------------------
data %>%
  filter(structure == "gdp", type == "real", seas_adj == "cssa") %>%
  ts_pc() %>%
  ts_plot()

# Analyze GDP growth, expenditure approach -------------------------------------
v_comp <- c("cons", "inv", "exp", "imp")

y_act <-
  max(data$date, na.rm = TRUE) %>%
  format("%Y") %>%
  as.numeric()

data_comp <-
  data %>%
  filter(
    seas_adj == "csa",
    type == "gc_q",
    structure %in% v_comp
  ) %>%
  ts_span(start = y_act - 10)

data_gdp <-
  data %>%
  filter(
    seas_adj == "csa",
    type == "real",
    structure == "gdp"
  ) %>%
  ts_pc() %>%
  ts_span(start = y_act - 10)

ggplot(data_comp, aes(x = date, y = value)) +
  geom_col(aes(fill = structure), position = "stack") +
  geom_line(
    data = data_gdp,
    aes(x = date, y = value),
    linewidth = 0.8
  ) +
  labs(
    x = NULL,
    y = NULL,
    fill = NULL,
    title = "GDP growth and expenditure-side contributions"
  ) +
  theme_minimal()