---
title: "Introduction to TaxResolveR"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to TaxResolveR}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Overview

**TaxResolveR** provides a reproducible workflow for preparing, resolving,
assessing, reviewing, summarising, and documenting scientific names used
in ecological and biodiversity datasets.

The package separates three related tasks: preparing scientific names for
taxonomic resolution, obtaining matches from an external taxonomic source,
and evaluating whether those matches should be accepted directly or
reviewed manually.

This distinction is important because successful taxonomic resolution does
not necessarily imply an exact species-level match.

## Loading TaxResolveR

```{r setup}
library(TaxResolveR)
```

For this introduction, consider a small vector containing valid species
names, a genus placeholder, an empty value, and a missing value.

```{r example-names}
scientific_names <- c(
  "Homo sapiens",
  "  Parastacus brasiliensis  ",
  "Chilina sp.",
  "",
  NA_character_
)

scientific_names
```

## Scientific-name preparation

TaxResolveR provides several functions for inspecting and preparing
scientific names before external taxonomic resolution.

### Cleaning names

`clean_scientific_names()` performs basic cleaning while preserving missing
and empty values.

```{r cleaning}
clean_scientific_names(scientific_names)
```

### Parsing names

`parse_scientific_names()` separates recognised components of scientific
names and identifies the detected rank or placeholder structure.

```{r parsing}
parse_scientific_names(scientific_names)
```

### Classifying names

`classify_scientific_names()` combines parsing information with a structural
classification of each input record.

```{r classification}
classify_scientific_names(scientific_names)
```

For example, a conventional binomial can be classified as
`valid_structure`, whereas `Chilina sp.` is recognised as a `placeholder`.
Empty and missing inputs remain explicitly distinguishable.

### Validating species-name structure

`validate_species_names()` provides simple structural indicators that are
useful when screening input data.

```{r validation}
validate_species_names(scientific_names)
```

Structural validation should not be interpreted as taxonomic resolution.
For example, a genus placeholder is not a binomial species name but can
still contain enough information to support a genus-level query.

### Standardising names

`standardize_scientific_names()` combines cleaned and parsed information
into a standardised representation.

```{r standardisation}
standardize_scientific_names(scientific_names)
```

### Preparing taxonomic queries

`prepare_taxonomic_queries()` determines which records contain sufficient
information for taxonomic resolution and constructs the corresponding
query names.

```{r query-preparation}
prepare_taxonomic_queries(scientific_names)
```

A placeholder such as `Chilina sp.` is therefore converted to the genus
query `Chilina`, whereas empty and missing records are marked as not ready
for querying.

## Taxonomic resolution

`resolve_taxonomy()` sends prepared names to an external taxonomic source.
GBIF is currently the implemented source.

A typical call is:

```{r resolution-example, eval=FALSE}
resolved <- resolve_taxonomy(
  c("Homo sapiens", "Homo sapens", "Chilina sp."),
  source = "gbif"
)
```

Because external taxonomic services require network access and can change
over time, live GBIF queries are not evaluated while this vignette is
built. This keeps package documentation reproducible and prevents temporary
network or service problems from causing vignette-build failures.

## Complete workflow with `taxresolve()`

For most users, `taxresolve()` is the main entry point. It combines
taxonomic resolution, match assessment, and review flagging.

For example:

```{r taxresolve-example, eval=FALSE}
results <- taxresolve(
  c(
    "Homo sapiens",
    "Homo sapens",
    "Chilina sp.",
    "Parastacus brasiliensis"
  ),
  source = "gbif"
)
```

The returned data frame contains the taxonomic information supplied by the
resolution stage together with fields describing resolution status, match
quality, acceptance status, and whether manual review is recommended.

## Reproducible offline example

The remainder of this vignette uses a fixed example representing a
taxonomic-resolution result. This allows the assessment, review, summary,
and reporting stages to be demonstrated without requiring network access.

The example includes an exact species match, a non-exact match, an exact
genus-level match, another exact species match, two non-queryable records,
and one unresolved query.

```{r offline-resolution}
resolved_example <- data.frame(
  source = rep("gbif", 7),
  query_name = c(
    "Homo sapiens",
    "Homo sapens",
    "Chilina",
    "Parastacus brasiliensis",
    NA_character_,
    NA_character_,
    "Xyzabc nonexistenttaxon"
  ),
  matched_name = c(
    "Homo sapiens",
    "Homo sapiens",
    "Chilina",
    "Parastacus brasiliensis",
    NA_character_, NA_character_, NA_character_
  ),
  accepted_name = c(
    "Homo sapiens",
    "Homo sapiens",
    "Chilina",
    "Parastacus brasiliensis",
    NA_character_, NA_character_, NA_character_
  ),
  taxonomic_status = c(
    "ACCEPTED", "ACCEPTED", "ACCEPTED", "ACCEPTED",
    NA_character_, NA_character_, NA_character_
  ),
  rank = c(
    "SPECIES", "SPECIES", "GENUS", "SPECIES",
    NA_character_, NA_character_, NA_character_
  ),
  kingdom = rep(NA_character_, 7),
  phylum = rep(NA_character_, 7),
  class = rep(NA_character_, 7),
  order = rep(NA_character_, 7),
  family = rep(NA_character_, 7),
  genus = rep(NA_character_, 7),
  taxon_id = c(
    2436436, 2436436, 3243720, 2224027,
    NA_real_, NA_real_, NA_real_
  ),
  match_type = c(
    "EXACT", "VARIANT", "EXACT", "EXACT",
    NA_character_, NA_character_, NA_character_
  ),
  match_confidence = c(
    99, 95, 94, 99, NA_real_, NA_real_, NA_real_
  ),
  resolution_success = c(
    TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE
  ),
  stringsAsFactors = FALSE
)

resolved_example[c(
  "query_name",
  "matched_name",
  "rank",
  "match_type",
  "match_confidence",
  "resolution_success"
)]
```

## Assessing taxonomic matches

`assess_taxonomic_match()` interprets the resolution output and adds three
fields: `resolution_status`, `match_quality`, and `accepted_status`.

```{r assessment}
assessed_example <- assess_taxonomic_match(resolved_example)

assessed_example[c(
  "query_name",
  "resolution_status",
  "match_quality",
  "accepted_status"
)]
```

A high-quality match should not automatically be interpreted as a
species-level identification. In this example, `Chilina` is an exact
genus-level match and is therefore distinct from an exact species-level
match.

## Flagging records for manual review

`flag_taxonomic_review()` adds `review_required` and `review_reason`.

```{r review}
reviewed_example <- flag_taxonomic_review(assessed_example)

reviewed_example[c(
  "query_name",
  "resolution_status",
  "match_quality",
  "review_required",
  "review_reason"
)]
```

This separates successful resolution from records that still warrant
attention. Non-exact matches, unresolved queries, and non-queryable inputs
can therefore be documented explicitly rather than silently discarded.

## Summarising results

`summarize_taxonomic_resolution()` returns a compact one-row summary of the
main resolution, match-quality, acceptance, and review counts.

```{r summary}
summary_example <- summarize_taxonomic_resolution(reviewed_example)
summary_example
```

## Detailed reporting

`taxonomic_resolution_report()` produces a structured report containing the
total summary together with category counts and proportions.

```{r report}
report_example <- taxonomic_resolution_report(reviewed_example)

report_example$total_summary
report_example$resolution_status
report_example$match_quality
report_example$review_reasons
```

The proportions in the detailed tables use the total number of input
records as their denominator.

## Exporting results

`export_taxonomic_results()` can write the complete reviewed data and
associated summary tables to CSV files.

A typical export is:

```{r export-example, eval=FALSE}
export_taxonomic_results(
  reviewed_example,
  path = "taxonomic_results"
)
```

The function creates five files: `taxonomic_results.csv`,
`taxonomic_summary.csv`, `resolution_status.csv`, `match_quality.csv`,
and `review_reasons.csv`. Existing managed output files are not overwritten
unless `overwrite = TRUE` is requested.

The export example is not evaluated while building this vignette because
documentation should not create persistent user-facing output directories
as a side effect.

## Handling problematic input

TaxResolveR is designed to retain problematic records rather than silently
remove them. Missing and empty inputs can remain in the workflow as
non-queryable records, while syntactically queryable names that cannot be
resolved can be retained as unresolved records.

Duplicate names can also be retained in the returned data so that row-level
correspondence with the original input is preserved.

This behaviour supports data auditing because unresolved or incomplete
taxonomic information remains visible in downstream summaries and review
flags.

## Recommended reproducible workflow

For routine use, a practical workflow is to:

1. retain the original scientific-name column;
2. inspect or clean names when necessary;
3. run `taxresolve()` using the intended taxonomic source;
4. inspect records for which `review_required` is `TRUE`;
5. document any manual taxonomic decisions;
6. summarise the resolution outcome; and
7. export and archive the results used in the analysis.

Because external taxonomies can change, the taxonomic source and date of
resolution should be retained as part of a reproducible biodiversity
workflow.

## Further documentation

Individual functions are documented through the standard R help system.
For example:

```{r help-example, eval=FALSE}
?taxresolve
?resolve_taxonomy
?assess_taxonomic_match
?flag_taxonomic_review
?taxonomic_resolution_report
```
