---
title: "Discover tiles and coverage"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Discover tiles and coverage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4)
helper <- if (file.exists("vignettes/real-example-helpers.R")) {
  "vignettes/real-example-helpers.R"
} else {
  "real-example-helpers.R"
}
source(helper)
real_mode <- bt_real_examples_enabled()
```

`r if (real_mode) bt_real_example_label else bt_offline_note`

This example uses BlueTopo tiles covering New York Harbor. The workflow
demonstrates tile discovery, checksum-verified asset retrieval, and file-backed
raster access with `terra`.

Coverage is geometric tile-index coverage rather than a data-quality measure.

## Example area

```{r setup, include=FALSE, eval=bt_real_examples_enabled()}
real <- bt_real_example_setup()
real_aoi <- real$aoi
```

## Selected tiles

```{r discover, eval=bt_real_examples_enabled()}
tiles <- bluertopo_tiles(
  real_aoi,
  resolution = "native",
  coverage = "warn",
  quiet = TRUE
)
```

```{r selected-table, echo=FALSE, eval=bt_real_examples_enabled()}
bt_display_table(bt_tile_table(tiles, include_urls = TRUE))
```

## Coverage diagnostics

```{r coverage-table, echo=FALSE, eval=bt_real_examples_enabled()}
coverage <- attr(tiles, "coverage")
bt_display_table(bt_coverage_table(coverage))
```

## AOI and selected footprints

```{r footprint-figure, echo=FALSE, eval=bt_real_examples_enabled(), fig.cap="BlueTopo tile coverage for the New York Harbor example area.", fig.alt="BlueTopo tile footprints selected for the New York Harbor example area."}
bt_plot_locator_map(
  tiles,
  real_aoi,
  place_label = real$place,
  main = "New York Harbor AOI and BlueTopo tiles"
)
```

## Coverage fractions

```{r coverage-bars, echo=FALSE, eval=bt_real_examples_enabled(), fig.cap="Coverage fractions for the selected New York Harbor tiles.", fig.alt="Bar plot of published coverage, selected coverage, selected AOI fraction, and target coverage."}
coverage_values <- unlist(coverage[c(
  "published_coverage_fraction",
  "selected_coverage_fraction",
  "selected_aoi_fraction",
  "target_coverage"
)])
barplot(
  coverage_values,
  ylim = c(0, 1),
  col = c("#8ecae6", "#90be6d", "#f9c74f", "#d00000"),
  las = 2,
  ylab = "fraction",
  main = "Coverage diagnostics"
)
abline(h = coverage$target_coverage, col = "#d00000", lwd = 2, lty = 2)
```

The selected tile table includes shortened GeoTIFF and RAT URLs from the current
catalog records.
