## ----setup, include = FALSE---------------------------------------------------
fixture_dir <- "files-batches"
recording <- nzchar(Sys.getenv("FOUNDRY_RECORD_DOCS"))
have_fixtures <- dir.exists(fixture_dir) && length(list.files(fixture_dir)) > 0
run_api <- requireNamespace("httptest2", quietly = TRUE) &&
  (recording || have_fixtures)

# Attach foundryR before start_vignette(): httptest2 only sources the package's
# inst/httptest2/start-vignette.R (which sets replay placeholders) from attached
# packages.
library(foundryR)

if (run_api) {
  httptest2::start_vignette(fixture_dir)
}

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = run_api
)

## ----libraries, eval = TRUE---------------------------------------------------
library(foundryR)

## ----batch-jsonl, eval = TRUE-------------------------------------------------
survey <- data.frame(
  id = c("resp-001", "resp-002", "resp-003"),
  response = c(
    "The workshop was clear and practical.",
    "I liked the examples but wanted more time.",
    "The setup instructions were confusing."
  )
)

jsonl <- tempfile(fileext = ".jsonl")

request_file <- foundry_batch_requests(
  survey,
  input = "response",
  path = jsonl,
  model = "gpt-5-nano",
  custom_id = "id",
  body = list(
    instructions = "Classify the response sentiment as positive, neutral, or negative."
  )
)

request_file
head(readLines(jsonl), 2)

## ----upload-create, eval = FALSE----------------------------------------------
# file <- foundry_file_upload(jsonl, purpose = "batch")
# unlink(jsonl)
# 
# batch <- foundry_batch_create(
#   input_file_id = file$file_id,
#   endpoint = "/v1/responses"
# )

## ----poll-download, eval = FALSE----------------------------------------------
# batch <- foundry_batch_get(batch$batch_id)
# output_path <- tempfile(fileext = ".jsonl")
# 
# foundry_file_download(
#   file_id = batch$output_file_id,
#   path = output_path
# )

## ----output-shape, eval = FALSE-----------------------------------------------
# output_lines <- readLines(output_path, n = 2)
# head(output_lines)
# unlink(output_path)

## ----cleanup, include = FALSE, eval = TRUE------------------------------------
unlink(jsonl)
if (run_api) {
  httptest2::end_vignette()
}

