## ----mapping-setup------------------------------------------------------------
# Load the reference catalogue and mapping functions.
library(form.model)
# Locate the survey files bundled with the installed package.
resources_directory <- system.file("examples", "survey", package = "form.model")
# Read the source catalogue configuration, which uses technical IDs.
source_references_configuration <- read_reference_configuration(
  file.path(resources_directory, "references-source.yaml"))
# Read the target configuration, which supplies the survey model's codes.
target_references_configuration <- read_reference_configuration(
  file.path(resources_directory, "references.yaml"))
# Bind both configurations to the names used in mapping.yaml.
references_configurations <- list(
  source = source_references_configuration,
  target = target_references_configuration)
# Load the source station and observer tables into a temporary cache.
source_tables <- get_reference_tables(
  c("stations", "observers"), source_references_configuration$catalogues$code_lists$source)
# Load the target station and observer tables into a separate temporary cache.
target_tables <- get_reference_tables(
  c("stations", "observers"), target_references_configuration$catalogues$code_lists$source)

## ----mapping-station-tables---------------------------------------------------
# Display the source stations and their technical IDs.
knitr::kable(source_tables$data$stations, caption = "Source stations")
# Display the corresponding target stations and their survey codes.
knitr::kable(target_tables$data$stations, caption = "Target stations")

## ----mapping-observer-tables--------------------------------------------------
# Display the source observers, including the deliberate data issues.
knitr::kable(source_tables$data$observers, caption = "Source observers")
# Display the target observer names and codes used by the survey model.
knitr::kable(target_tables$data$observers, caption = "Target observers")

## ----mapping-prepare----------------------------------------------------------
# Read the mapping declarations and resolve their lookup defaults and file paths.
mapping_configuration <- read_mapping_configuration(file.path(resources_directory, "mapping.yaml"))
# Prepare lookup indexes and correspondences using the cached catalogue data.
mapping_references <- prepare_mapping_references(mapping_configuration, references_configurations, offline = TRUE)

## ----mapping-direct-----------------------------------------------------------
# Resolve the station through the CSV and display the four summary columns.
map_reference_values(mapping_references, "stations", "station-north")[, 1:4]

## ----mapping-rebound----------------------------------------------------------
# Find the source observer by ID, then match its name in the target catalogue.
map_reference_values(mapping_references, "observers", "person-alice", source_lookup = "id")[, 1:4]

## ----mapping-unchanged--------------------------------------------------------
# Send the supplied name directly to the target observer lookup.
map_reference_values(mapping_references, "observers", "Alice Example", source_lookup = "name")[, 1:4]

## ----mapping-source-alias-----------------------------------------------------
# Resolve the former source ID through its catalogue alias before reading the name.
map_reference_values(mapping_references, "observers", "former-alice", source_lookup = "id")[, 1:4]

## ----mapping-target-alias-----------------------------------------------------
# Translate the CSV value OLD-STATION through the target catalogue's code alias.
map_reference_values(mapping_references, "stations", "station-legacy")[, 1:4]

## ----mapping-csv-exact--------------------------------------------------------
# Show that a source alias and an uppercase variant are not exact CSV keys.
map_reference_values(mapping_references, "stations", c("former-north", "STATION-NORTH"))[, 1:4]

## ----mapping-unchanged-source-alias-------------------------------------------
# Show that an alias belonging only to the source is unknown to the target lookup.
map_reference_values(mapping_references, "observers", "A. Example", source_lookup = "name")[, 1:4]

## ----mapping-ignore-case------------------------------------------------------
# Resolve the uppercase ID using the source lookup's ignore_case setting.
map_reference_values(mapping_references, "observers", "PERSON-BOB", source_lookup = "id")[, 1:4]

## ----mapping-rebound-normalized-----------------------------------------------
# Match the source name Example, Alice after normalizing punctuation and word order.
map_reference_values(mapping_references, "observers", "person-alice-formatted", source_lookup = "id")[, 1:4]

## ----mapping-normalized-not-fuzzy---------------------------------------------
# Compare a normalized match with a misspelling that remains unresolved.
map_reference_values(mapping_references, "observers", c("Example, Alice", "Alic Example"), source_lookup = "name")[, 1:4]

## ----mapping-missing-input----------------------------------------------------
# Show the missing_input result for each supported representation of absent input.
map_reference_values(mapping_references, "stations", list(NULL, NA_character_, ""))[, 1:4]

## ----mapping-missing-source---------------------------------------------------
# Report a missing source record without attempting a target lookup.
map_reference_values(mapping_references, "observers", "person-absent", source_lookup = "id")[, 1:4]

## ----mapping-missing-property-------------------------------------------------
# Report that the source observer exists but its required name is empty.
map_reference_values(mapping_references, "observers", "person-no-name", source_lookup = "id")[, 1:4]

## ----mapping-missing-correspondence-------------------------------------------
# Report that the supplied station ID has no entry in the correspondence CSV.
map_reference_values(mapping_references, "stations", "station-unmapped")[, 1:4]

## ----mapping-no-fallback------------------------------------------------------
# Show that an absent CSV key does not fall back to a direct target code lookup.
map_reference_values(mapping_references, "stations", "001")[, 1:4]

## ----mapping-missing-target---------------------------------------------------
# Report that the CSV's target value 999 is absent from the target catalogue.
map_reference_values(mapping_references, "stations", "station-absent")[, 1:4]

## ----mapping-unlisted-person--------------------------------------------------
# Report that the source observer's name has no target match.
map_reference_values(mapping_references, "observers", "person-unlisted", source_lookup = "id")[, 1:4]

## ----mapping-ambiguous-source-------------------------------------------------
# Retain both source row indexes when a technical ID identifies two observers.
map_reference_values(mapping_references, "observers", "person-duplicate", source_lookup = "id")[
  c("source_value", "target_value", "status", "stage", "source_rows")]

## ----mapping-ambiguous-csv----------------------------------------------------
# Display both conflicting correspondence values without choosing a target.
map_reference_values(mapping_references, "stations", "station-conflict")[
  c("source_value", "target_value", "status", "stage", "correspondence_values")]

## ----mapping-repeated-input---------------------------------------------------
# Preserve input order and repeated result rows while deduplicating identical CSV pairs.
map_reference_values(mapping_references, "stations", c("station-south", "station-north", "station-north"))[, 1:4]

## ----mapping-selection-error--------------------------------------------------
# Display the selector error as text so the remaining examples can continue.
tryCatch(map_reference_values(mapping_references, "observers", "person-alice"), error = conditionMessage)

## ----mapping-selected-target--------------------------------------------------
# Prepare only the target station table and its correspondence CSV.
mapping_station_references <- prepare_mapping_references(
  mapping_configuration, references_configurations, targets = "stations", offline = TRUE)
# Resolve a station using that smaller prepared selection.
map_reference_values(mapping_station_references, "stations", "station-north")[, 1:4]

## ----mapping-provenance-------------------------------------------------------
# Retain a complete mapping result, including its provenance attribute.
result <- map_reference_values(mapping_references, "stations", "station-north")
# Extract the provenance recorded during preparation and resolution.
provenance <- attr(result, "provenance")
# Display the selected source table, lookup, correspondence file and target property.
provenance$mapping
# Display the target table identity and its published data version.
provenance$target_catalogue$table[c("id", "version")]
# Display the checksum identifying the correspondence file used for this result.
provenance$correspondence$sha256

## ----mapping-cleanup----------------------------------------------------------
# Visit both source and target configurations.
for (references_configuration in references_configurations) {
  # Visit each catalogue configured on that side of the mapping.
  for (catalogue in references_configuration$catalogues) {
    # Remove its temporary cache after all examples have finished.
    unlink(catalogue$source$cache, recursive = TRUE)
  }
}

