# Score two pregame forecasts for the home team on the same settled games.
# Run with base R: Rscript score-games.R basketball.csv

utc_seconds <- function(x, field) {
  parsed <- as.POSIXct(strptime(x, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"))
  rendered <- format(parsed, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
  if (anyNA(parsed) || !all(rendered == x)) {
    stop(field, " must contain UTC timestamps such as 2026-01-01T18:00:00Z.")
  }
  parsed
}

score_games <- function(path) {
  games <- read.csv(path, colClasses = "character", check.names = FALSE,
                    strip.white = TRUE, na.strings = "", row.names = NULL)
  required <- c("game_id", "forecast_utc", "tipoff_utc", "p_a", "p_b", "home_won")
  if (!nrow(games) || anyDuplicated(names(games)) || !all(required %in% names(games))) {
    stop("Supply at least one game and unique headers including ", paste(required, collapse = ", "), ".")
  }
  ids <- trimws(games$game_id)
  if (anyNA(ids) || any(ids == "") || anyDuplicated(ids)) stop("Each game needs a unique ID.")
  recorded <- utc_seconds(games$forecast_utc, "forecast_utc")
  tipoff <- utc_seconds(games$tipoff_utc, "tipoff_utc")
  if (any(recorded >= tipoff)) stop("Both forecasts must be recorded before tipoff.")
  if (!all(games$home_won %in% c("0", "1"))) stop("Complete each settled result with 0 or 1.")
  result <- as.integer(games$home_won)
  evaluate <- function(label, probability) {
    p <- suppressWarnings(as.numeric(probability))
    if (any(!is.finite(p) | p < 0 | p > 1)) stop(label, " probabilities must be between 0 and 1.")
    picked <- p != 0.5
    correct <- sum(picked & ((p > 0.5) == result))
    data.frame(model = label, games = length(p), picks = sum(picked),
               correct = correct, brier = mean((p - result)^2))
  }
  rbind(evaluate("Model A", games$p_a), evaluate("Model B", games$p_b),
        evaluate("Always 50%", rep(0.5, nrow(games))))
}

if (sys.nframe() == 0L) {
  args <- commandArgs(trailingOnly = TRUE)
  if (length(args) != 1L) stop("Usage: Rscript score-games.R basketball.csv")
  print(score_games(args[1L]), row.names = FALSE, digits = 5)
}
