price_adjustment <- function(trade_data_processed, var2024, var2025){
  var2024 <- ensym(var2024)
  var2025 <- ensym(var2025)
  
  trade_data_processed <-trade_data_processed %>%
    group_by(hs02) %>%
    mutate(
      across(c(!!var2024, !!var2025, calc_2024, calc_2025), as.numeric),
      var2025_adjusted = (!!var2025)/(calc_2025/calc_2024),
      cumsum_2024 = cumsum(!!var2024),
      real_cumsum_2025 = cumsum(var2025_adjusted),
      ytd_compare = real_cumsum_2025/cumsum_2024 -1,
      month = factor(month, levels = month.name))
  return(trade_data_processed)
}

IM_data_priceadjusted <- price_adjustment(IM_data_processed, cifval_2024, cifval_2025)
EX_data_priceadjusted <- price_adjustment(EX_data_processed, expval_2024, expval_2025)


# To make further comparison (aggregate by HTS chapters?), here we select only the latest month (July)
sum_price_adjusted_data <- function(price_adjusted_data){
  price_adjusted_data %>%
    filter(month == "July")%>%
    select(hs02, month, hts_chapters, cumsum_2024, real_cumsum_2025) %>%
    left_join(
      tariff_rev %>% mutate(hs02 = as.character(hs02)),
      by = c("hs02"))%>%
    left_join(
      hts_chapters_map %>% select(hts_chapters, hts_chapters_name),
      by = c("hts_chapters")
    ) %>%
    #sum by HTS chapters, and then compare the cumulative trade value with 2024 same period
    group_by(hts_chapters_name) %>%
    summarise(
      cumsum_2024 = sum(cumsum_2024, na.rm = TRUE),
      real_cumsum_2025 = sum(real_cumsum_2025, na.rm = TRUE),
      ytd_compare = real_cumsum_2025/cumsum_2024 -1,
      cald_sum_24 = sum(cumsum_cald_24, na.rm = TRUE),
      cifval_sum_24 = sum(cumsum_cifval_24, na.rm = TRUE),
      cald_sum_25 = sum(cumsum_cald_25, na.rm = TRUE),
      cifval_sum_25 = sum(cumsum_cifval_25, na.rm = TRUE),
      
      tariff_rev_2024 = cald_sum_24/cifval_sum_24,
      tariff_rev_2025 = cald_sum_25/cifval_sum_25,
      tariff_rev_diff = tariff_rev_2025 - tariff_rev_2024,
      .groups = "drop")

}

IM_finaldata_bychapters <- sum_price_adjusted_data(IM_data_priceadjusted)
EX_finaldata_bychapters <- sum_price_adjusted_data(EX_data_priceadjusted)
