# Empirical analysis — acqui-hire thesis
# two dialogs will open. Please select:
#   1) the hand-coded classification file 
#   2) the Gautier database 

# packages
if (!requireNamespace("readxl", quietly = TRUE)) install.packages("readxl")

# ---- 1. File pickers -----------------------------------------------------
pick <- function(caption) {
  message(caption)
  f <- tryCatch(file.choose(), error = function(e) NA)
  if (length(f) == 0 || is.na(f) || !nzchar(f)) stop("No file selected.")
  f
}
coded_path   <- pick("Select the hand-coded classification file (v3.1 .xlsx)")
gautier_path <- pick("Select the Gautier database (.xlsx)")

# ---- 2. Read both files --------------------------------------------------
# Keep target, stage flags, and final coding from the hadn-coded dataset file.
coded <- readxl::read_excel(coded_path, sheet = "Summary", skip = 4)
coded <- coded[!is.na(coded$`Final coding`) &
               coded$`Final coding` %in% c("Acqui-hire", "Indeterminate", "Non-acqui-hire"),
               c("Target", "Stage 1", "Stage 2", "Counter-evidence", "Final coding")]
names(coded) <- c("target", "stage1", "stage2", "ce", "final")

gautier <- readxl::read_excel(gautier_path, sheet = "Working Sample")
names(gautier) <- trimws(names(gautier))
names(gautier)[names(gautier) == "Company name"]    <- "target"
names(gautier)[names(gautier) == "Age (in years)"]  <- "age"
names(gautier)[names(gautier) == "Foundation year"] <- "found_year"
names(gautier)[names(gautier) == "Funding rounds"]  <- "rounds"
names(gautier)[names(gautier) == "Total funding"]   <- "funding"
names(gautier)[names(gautier) == "Continuation"]    <- "cont_old"     # original 2-category
names(gautier)[names(gautier) == "Contiuation 23"]  <- "cont"         # paper's 4-category (typo in source)
names(gautier)[names(gautier) == "US or non US"]    <- "country"

# Some columns contain the literal string "NA" instead of empty cells, convert.
for (col in c("rounds", "funding", "age", "found_year", "country", "cont", "cont_old", "Acquirer", "Cluster")) {
  if (col %in% names(gautier)) {
    gautier[[col]][gautier[[col]] == "NA"] <- NA
  }
}
gautier$rounds     <- suppressWarnings(as.numeric(gautier$rounds))
gautier$funding    <- suppressWarnings(as.numeric(gautier$funding))
gautier$age        <- suppressWarnings(as.numeric(gautier$age))
gautier$found_year <- suppressWarnings(as.numeric(gautier$found_year))
gautier$target     <- trimws(as.character(gautier$target))

# ---- 3. Merge classification onto Gautier firm data ----------------------
# A few hand-coded names differ from the Gautier database spelling.
norm <- function(x) {
  x <- tolower(x)
  x <- gsub("[().,\\-_/&]", " ", x)
  x <- gsub("\\s+", " ", x)
  trimws(x)
}
override <- c(
  "Silicon Valley Data Science (SVDS)" = "silicon valley data science",
  "Curious AI Company"                 = "curious ai",
  "Lattice Data"                       = "lattice",
  "Init.ai"                            = "init ai",
  "IKinema"                            = "ikinema",
  "Tuplejump"                          = "tuplejump",
  "Faceshift"                          = "faceshift",
  "BlueTalon"                          = "blue talon",
  "Confirm.io"                         = "confirm",
  "Umbra 3D (Umbra Software Oy)"       = "umbrad 3d",
  "SensoMotoric Instruments"           = "sensomotoric instruments smi",
  "DataSense (BrightBytes)"            = "datasense belonged to bright bytes"
)
coded$key   <- ifelse(coded$target %in% names(override),
                      override[coded$target], norm(coded$target))
gautier$key <- norm(gautier$target)

gautier_slim <- gautier[, c("key", "age", "found_year", "rounds", "funding",
                            "cont", "country", "Acquirer", "Cluster")]
df <- merge(coded, gautier_slim, by = "key", all.x = TRUE)

cat("\nHand-coded:", nrow(coded),
    "| matched to Gautier:", sum(!is.na(df$age)),
    "| unmatched:", sum(is.na(df$age)), "\n")
if (any(is.na(df$age))) {
  cat("Unmatched targets:\n"); print(df$target[is.na(df$age)])
}

# Country availability — needed for the chi-square and probit Spec 3
cat("\nCountry data availability in the 60-deal sample:\n")
print(table(df$country, useNA = "always"))
if (any(is.na(df$country))) {
  cat("Targets with missing country (excluded from country-related tests):\n")
  print(df$target[is.na(df$country)])
}

# ==========================================================================
# Section 5.4 — Within-sample descriptive statistics
# ==========================================================================

cat("\n--- Table 5.1: final classification ---\n")
print(table(df$final))

cat("\n--- Table 5.2: acquirer x final ---\n")
print(addmargins(table(df$Acquirer, df$final)))

cat("\n--- Indeterminate sub-type breakdown ---\n")
ind <- df[df$final == "Indeterminate", ]
ind$sub <- with(ind, ifelse(stage1 == "No"  & stage2 == "Yes" & ce == "No",  "Team migration only",
                     ifelse(stage1 == "No"  & stage2 == "Yes" & ce == "Yes", "Team migration only + CE",
                     ifelse(stage1 == "Yes" & stage2 == "No"  & ce == "No",  "Talent motive only",
                     ifelse(stage1 == "Yes" & stage2 == "No"  & ce == "Yes", "Talent motive only + CE",
                     ifelse(stage1 == "Yes" & stage2 == "Yes" & ce == "Yes", "Conflicting evidence",
                                                                              "Other"))))))
print(table(ind$sub))

cat("\n--- Table 5.3: target characteristics by class ---\n")
desc <- function(d) c(
  n            = nrow(d),
  age_mean     = round(mean(d$age,     na.rm = TRUE), 2),
  age_median   = median(d$age,         na.rm = TRUE),
  foundy_mean  = round(mean(d$found_year, na.rm = TRUE), 1),
  rounds_mean  = round(mean(d$rounds,  na.rm = TRUE), 2),
  fund_mean_M  = round(mean(d$funding, na.rm = TRUE) / 1e6, 1),
  fund_med_M   = round(median(d$funding, na.rm = TRUE) / 1e6, 1)
)
by_class <- do.call(rbind, lapply(
  split(df, df$final)[c("Acqui-hire", "Indeterminate", "Non-acqui-hire")],
  desc
))
print(by_class)

cat("\n--- Non-parametric tests ---\n")
cat("Kruskal-Wallis (3 classes):\n")
print(kruskal.test(age      ~ final, data = df))
print(kruskal.test(rounds   ~ final, data = df))
print(kruskal.test(funding  ~ final, data = df))

df$is_acqh <- as.integer(df$final == "Acqui-hire")
cat("\nMann-Whitney (Acqui-hire vs rest):\n")
print(wilcox.test(age     ~ is_acqh, data = df, exact = FALSE))
print(wilcox.test(rounds  ~ is_acqh, data = df, exact = FALSE))
print(wilcox.test(funding ~ is_acqh, data = df, exact = FALSE))

# Chi-square US/non-US x Acqui-hire — explicitly drop NA country observations
df_country <- df[!is.na(df$country), ]
cat(sprintf("\nChi-square US/non-US x Acqui-hire (excluding %d obs with missing country):\n",
            nrow(df) - nrow(df_country)))
print(suppressWarnings(chisq.test(table(df_country$is_acqh, df_country$country))))

cat("\nChi-square Acquirer x Final:\n")
print(suppressWarnings(chisq.test(table(df$Acquirer, df$final))))

# ==========================================================================
# Section 5.5 — Comparison with the broader GAFAM AI population
# ==========================================================================

# Section 5.5: Population comparison uses the paper's 4-category continuation
# (column "Contiuation 23", with the typo preserved from the source file).
# Stage 0 eligibility = "not active" OR "Announced" (the two discontinuation categories
# in Argentesi et al. / Gautier-Maitry 2024). The other two ("Active", "Integrated")
# mean the product is still offered post-acquisition and is not an acqui-hire candidate.
ai      <- gautier[grepl("Artificial intelligence", gautier$Cluster, ignore.case = TRUE), ]
ai_disc <- ai[ai$cont %in% c("not active", "Announced"), ]
ai_run  <- ai[ai$cont %in% c("Active", "active", "Integrated"), ]   # lowercase 'active' = typo for 'Active' (Workflow / Apple)

pop <- function(d, lab) data.frame(
  group       = lab,
  n           = nrow(d),
  age_mean    = round(mean(d$age, na.rm = TRUE), 2),
  age_med     = median(d$age, na.rm = TRUE),
  fund_mean_M = round(mean(d$funding, na.rm = TRUE) / 1e6, 1),
  fund_med_M  = round(median(d$funding, na.rm = TRUE) / 1e6, 1),
  rounds_mean = round(mean(d$rounds, na.rm = TRUE), 2)
)

# "Other AI/discontinued in sample" = indeterminate + non-acqui-hire from the 60
other_in_sample <- df[df$final != "Acqui-hire", ]
acqh_only       <- df[df$final == "Acqui-hire", ]

cat("\n--- Table 5.4: population comparison ---\n")
print(rbind(
  pop(acqh_only,        "Confirmed acqui-hires (subset of sample)"),
  pop(other_in_sample,  "Other AI/discontinued in sample (Indet. + Non)"),
  pop(ai_disc,          "All AI/discontinued (Gautier)"),
  pop(ai_run,           "All AI/running (Gautier)"),
  pop(gautier,          "All GAFAM (Gautier)")
))

# Right-skew check: top deals in AI/running, and mean without the largest
top_run <- ai_run[order(-ai_run$funding), c("target", "funding", "Acquirer")]
top_run <- top_run[!is.na(top_run$funding), ]
cat("\nTop 5 AI/running deals by total funding:\n")
print(head(top_run, 5))
cat("AI/running mean funding ($M):\n")
cat("  full:                ", round(mean(ai_run$funding, na.rm = TRUE) / 1e6, 1), "\n")
cat("  excluding the largest:", round(mean(
  ai_run$funding[ai_run$funding < max(ai_run$funding, na.rm = TRUE)],
  na.rm = TRUE) / 1e6, 1), "\n")

# Confirmed acqui-hires vs other AI/discontinued
acqh_keys <- df$key[df$final == "Acqui-hire"]
ai_disc$is_acqh <- as.integer(ai_disc$key %in% acqh_keys)
cat("\nMann-Whitney: confirmed acqui-hires vs other AI/discontinued (age):\n")
print(wilcox.test(age ~ is_acqh, data = ai_disc, exact = FALSE))
cat("Same, on funding:\n")
print(wilcox.test(funding ~ is_acqh, data = ai_disc, exact = FALSE))

# ==========================================================================
# Section 5.6 — Probit regression
# ==========================================================================
# With 13 events on 60 observations the events-per-variable ratio is small,
# so these specifications are exploratory.

# Funding imputation diagnostics
fund_med <- median(df$funding, na.rm = TRUE)
n_imp    <- sum(is.na(df$funding))
cat(sprintf("\nFunding imputation: %d missing values imputed at sample median $%sM.\n",
            n_imp, round(fund_med / 1e6, 2)))
df$fund_imp <- ifelse(is.na(df$funding), fund_med, df$funding)
df$log_fund <- log1p(df$fund_imp)
df$non_us   <- as.integer(df$country == "NON-US")
# leave non_us as NA where country is missing — Spec 3 will drop those rows

m1 <- glm(is_acqh ~ age,                       data = df, family = binomial("probit"))
m2 <- glm(is_acqh ~ age + log_fund,            data = df, family = binomial("probit"))
m3 <- glm(is_acqh ~ age + log_fund + non_us,   data = df, family = binomial("probit"))

mcfadden <- function(m) 1 - as.numeric(logLik(m)) /
                            as.numeric(logLik(update(m, . ~ 1)))

cat("\n--- Probit Spec 1: age ---\n");                 print(summary(m1))
cat("McFadden R^2:", round(mcfadden(m1), 4), "\n")

cat("\n--- Probit Spec 2: age + log funding ---\n");   print(summary(m2))
cat("McFadden R^2:", round(mcfadden(m2), 4), "\n")

cat(sprintf("\n--- Probit Spec 3: age + log funding + non-US (excludes %d obs with missing country) ---\n",
            sum(is.na(df$non_us))))
print(summary(m3))
cat("McFadden R^2:", round(mcfadden(m3), 4), "\n")

# Average marginal effects (delta-method SE). Works without extra packages.
ame <- function(model) {
  X      <- model.matrix(model)
  betas  <- coef(model)
  ses    <- sqrt(diag(vcov(model)))
  mean_phi <- mean(dnorm(X %*% betas))
  data.frame(
    AME = round(mean_phi * betas, 4),
    SE  = round(mean_phi * ses,   4),
    p   = round(2 * pnorm(-abs(mean_phi * betas / (mean_phi * ses))), 4)
  )
}
cat("\nAverage marginal effects, Spec 1:\n"); print(ame(m1))
cat("\nAverage marginal effects, Spec 2:\n"); print(ame(m2))
cat("\nAverage marginal effects, Spec 3:\n"); print(ame(m3))
