library(tidyverse)
count_data_fp <-"/mmfs1/gscratch/comdata/users/mjilg/mw-repo-lifecycles/case1/en-testing_0217_extensions_ve_weekly_commit_count_data.csv"
input_df <- read.csv(count_data_fp, header = TRUE)

library(rdd)

var(input_df$commit_count) # 1253.343
mean(input_df$commit_count) # 44.92381
median(input_df$commit_count) # 39.5

get_optimal_bandwidth <- function(df){
  bw <- tryCatch({
    IKbandwidth(df$relative_week, df$commit_count, cutpoint = 0, verbose = FALSE, kernel = "triangular")
  }, error = function(e) {
    NA
  })
}

optimal_bandwidth <- get_optimal_bandwidth(input_df)

window_num <- 8
input_df <- input_df |>
  filter(relative_week >= (- window_num) & relative_week <= (window_num)) |>
  mutate(nonbot_commit_count = commit_count - bot_commit_count)|>
  mutate(other_commit_count = nonbot_commit_count - mediawiki_dev_commit_count - wikia_commit_count - wikimedia_commit_count) |>
  mutate(wikimedia_commit_count = wikimedia_commit_count + mediawiki_dev_commit_count + wikia_commit_count) |>
  select(-mediawiki_dev_commit_count) |>
  select(-wikia_commit_count)

#library(MASS)

#simple_model <- glm.nb(commit_count~before_after*relative_week, data=input_df)
#summary(simple_model)

library(lme4)
library(dplyr)

#get into mlm format
long_df <- input_df |>
  pivot_longer(cols = c(other_commit_count, wikimedia_commit_count),
               names_to = "commit_type",
               values_to = "lengthened_commit_count")

long_df <- long_df |>
  mutate(commit_share = lengthened_commit_count / (nonbot_commit_count)) |>
  mutate(log_commits = log1p(lengthened_commit_count))

mlm <- glmer.nb(log_commits ~ before_after*relative_week + (before_after*relative_week|commit_type),
                control=glmerControl(optimizer="bobyqa",
                                     optCtrl=list(maxfun=2e5)), nAGQ=0,
                data=long_df)
summary(mlm)
ranefs <- ranef(mlm)
print(ranefs)
#saveRDS(mlm, "021525_core-ve_event_mlm.rda")

share_df <- input_df |>
  mutate(wikimedia_share = wikimedia_commit_count / nonbot_commit_count) |>
  mutate(other_share = other_commit_count / nonbot_commit_count)|>
  drop_na()

share_long <- share_df |>
  dplyr::select(relative_week, wikimedia_share, other_share, before_after) |>
  pivot_longer(cols = c(wikimedia_share, other_share), names_to = "category", values_to = "share")

share_mlm <- glmer.nb(share ~ before_after*relative_week + (before_after*relative_week|category),
                control=glmerControl(optimizer="bobyqa",
                                     optCtrl=list(maxfun=2e5)), nAGQ=0,
                data=share_long)
summary(share_mlm)
