---
title: "API endpoints reference"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{API endpoints reference}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

This vignette provides a *generated* mapping between exported `tceper`
functions and their underlying TCE-PE API endpoints, based on the package
code and the built-in catalog.

The table below is generated locally **from the built-in catalog** — no
API call is made, so it builds anywhere regardless of network access.
The example block at the end of the vignette is shown but not executed
(the API is only reachable from Brazilian IP addresses).

```{r mapping, eval = TRUE}
library(tceper)

# Catalog with endpoint metadata
catalog <- tce_catalog()

# Discover exported wrappers and extract the endpoint used internally.
# We look for calls of the form: tce_cached("Endpoint") or tce_request("Endpoint")
exports <- getNamespaceExports("tceper")

# Keep likely "wrapper" functions
skip <- c(
  "tce_request", "tce_catalog", "tce_endpoint", "tce_params", "tce_fields",
  "tce_cache_info", "tce_cache_clear"
)
wrappers <- setdiff(exports, skip)

extract_endpoint <- function(fn) {
  f <- get(fn, envir = asNamespace("tceper"))
  txt <- paste(deparse(body(f)), collapse = "\n")
  m <- regexpr('tce_(?:cached|request)\\("([^"]+)"', txt, perl = TRUE)
  if (m[1] == -1) return(NA_character_)
  hit <- regmatches(txt, m)
  sub('^tce_(?:cached|request)\\("([^"]+)".*$', "\\1", hit)
}

endpoint <- vapply(wrappers, extract_endpoint, character(1))

mappings <- tibble::tibble(
  r_function = paste0("`", wrappers, "()`"),
  endpoint   = endpoint
) |>
  dplyr::filter(!is.na(endpoint)) |>
  dplyr::left_join(
    catalog |> dplyr::select(endpoint, group, title),
    by = "endpoint"
  ) |>
  dplyr::arrange(group, endpoint, r_function)

mappings
```

## How to use this reference

- Use `tce_catalog(search = "...")` to locate an endpoint of interest.
- Use `tce_params("Endpoint")` to discover available query parameters.
- Use `tce_fields("Endpoint")` to see the output schema.
- Then call the corresponding wrapper function (as listed above) or call
  `tce_request("Endpoint", ...)` directly with API parameter names.

### Example: inspect and query `Contratos`

```{r example, eval = FALSE, purl = FALSE}
tce_params("Contratos")
tce_fields("Contratos")

tce_contracts(codigo_efisco_ug = "510101", ano_contrato = "2025")
```
