## Study 3 — clean: data/data_raw/raw_study3_(297841).csv -> data/data_cleaned/study3_clean_(297841).Rds
## Keeps all valid-condition rows: real participants (incl. incomplete) + AI respondent rows
## (id "AI-…", which hold the AI's selected news sources + opening argument). Derives the
## preregistered Weight-of-Advice DV and the pre/post uncertainty SDs. The manuscript QMD applies
## the inclusion criteria (real participants, matched + completed).
source(here::here("R", "_helpers.R"))
suppressWarnings(suppressMessages(library(jsonlite)))

raw <- read.csv(path_raw("raw_study3_(297841).csv"), stringsAsFactors = FALSE)
raw$is_ai          <- grepl("^AI-", raw$id)
raw$completed_flag <- tolower(trimws(as.character(raw$completed))) %in% c("1", "true", "t", "yes")
raw$condition      <- unname(COND_LABELS[raw$treatment])

d <- raw[raw$condition %in% COND_ORDER, , drop = FALSE]
d$initial <- suppressWarnings(as.numeric(d$initial_forecast))
d$revised <- suppressWarnings(as.numeric(d$revised_forecast))

# GenAI estimate fixed 3pp from Initial toward the consensus (2.9); denominator +/-3 (NA at 2.9).
denom <- 3 * sign(CONSENSUS - d$initial)
d$genai <- d$initial + denom
d$woa   <- ifelse(denom != 0, (d$revised - d$initial) / denom, NA_real_)
d$dist  <- abs(d$initial - CONSENSUS)

# Forecast-uncertainty SD from the 7 draggable bars, pre and post chat.
d$sd_pre  <- vapply(d$uncertainty_initial, dist_sd, numeric(1))
d$sd_post <- vapply(d$uncertainty_revised, dist_sd, numeric(1))

d$Baseline  <- as.integer(d$condition == "Baseline")
d$Optimized <- as.integer(d$condition == "Optimized")
d$condition <- factor(d$condition, levels = COND_ORDER)

dir.create(here::here("data", "data_cleaned"), showWarnings = FALSE, recursive = TRUE)
saveRDS(d, path_clean("study3_clean_(297841).Rds"))
message(sprintf("study3_clean_(297841).Rds: %d rows (%d real, %d AI); analysis-eligible real = %d",
  nrow(d), sum(!d$is_ai), sum(d$is_ai),
  sum(!d$is_ai & d$pair_status == "AI_PAIR_SUCCESS" & d$completed_flag)))
