---
title: "Architecture Overview"
format:
  html:
    code-fold: true
    code-summary: "Show code"
vignette: >
  %\VignetteIndexEntry{Architecture Overview}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
---

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

if (requireNamespace("micromort", quietly = TRUE)) {
  library(micromort)
} else {
  pkgload::load_all(quiet = TRUE)
}

# Shared safe_tar_read with RDS fallback (see inst/vignette_utils.R)
source(file.path(tryCatch(rprojroot::find_root(rprojroot::is_r_package),
  error = function(e) "."), "inst", "vignette_utils.R"))

# Helper: emit mermaid diagram as a script/div pair so pandoc cannot
# HTML-encode the arrows (-->) or wrap lines in <p> tags.
# caption and alt_text are HTML-escaped to prevent injection.
html_escape <- function(x) {
  x <- gsub("&", "&amp;", x, fixed = TRUE)
  x <- gsub("<", "&lt;", x, fixed = TRUE)
  x <- gsub(">", "&gt;", x, fixed = TRUE)
  x <- gsub('"', "&quot;", x, fixed = TRUE)
  x <- gsub("'", "&#39;", x, fixed = TRUE)
  x
}
emit_mermaid <- function(target_name, fallback_msg, caption = NULL, alt_text = NULL) {
  diagram <- safe_tar_read(target_name)
  if (!is.null(diagram)) {
    id <- gsub("[^a-z0-9]", "", target_name)
    if (!is.null(caption)) cat('<figure role="figure">\n')
    cat(sprintf('<pre class="mermaid" id="%s"', id))
    if (!is.null(alt_text)) cat(sprintf(' aria-label="%s"', html_escape(alt_text)))
    cat('></pre>\n')
    cat(sprintf('<script type="text/plain" data-mermaid="%s">\n', id))
    cat(diagram)
    cat("\n</script>\n")
    if (!is.null(caption)) {
      cat(sprintf('<figcaption>%s</figcaption>\n</figure>\n', html_escape(caption)))
    }
  } else {
    cat(paste0("*", fallback_msg, "*\n"))
  }
}
```

This page shows how the micromort package is organized: the data pipeline,
function hierarchy, user entry points, and development workflow.
All diagrams are auto-generated from package metadata via the
[targets pipeline](https://docs.ropensci.org/targets/).

```{=html}
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
mermaid.initialize({
  startOnLoad: false,
  securityLevel: 'loose',
  theme: 'dark',
  themeVariables: {
    background: '#000000',
    primaryColor: '#999999',
    lineColor: '#CC0000',
    primaryTextColor: '#000000'
  }
});
// Inject diagram text from <script> tags into their paired <pre> elements,
// then ask mermaid to render them. This avoids pandoc HTML-encoding arrows.
document.querySelectorAll('script[data-mermaid]').forEach(function(s) {
  var target = document.getElementById(s.getAttribute('data-mermaid'));
  if (target) {
    target.textContent = s.textContent;
  }
});
await mermaid.run({ querySelector: '.mermaid' });
</script>
```

## 1. Data Pipeline

The targets pipeline processes risk data through five stages.
Target counts update automatically when plan files change.

```{r pipeline, results='asis'}
emit_mermaid("vig_arch_pipeline_diagram",
             "Pipeline diagram requires `tar_make()` to render.",
             caption = "Figure 1: Data pipeline showing five processing stages from raw risk data through targets to vignette outputs.",
             alt_text = "Mermaid flowchart showing the five-stage targets data pipeline: raw data ingestion, cleaning, aggregation, modelling, and vignette export.")
```

## 2. Function Hierarchy

All exported functions grouped by category.
Click any function to view its documentation.

```{r concept, results='asis'}
emit_mermaid("vig_arch_concept_diagram",
             "Concept diagram requires `tar_make()` to render.",
             caption = "Figure 2: Exported functions grouped by category — risk data, conversion utilities, regional analysis, visualisation, and quiz.",
             alt_text = "Mermaid diagram showing all exported functions organised into five categories with links to their documentation pages.")
```

## 3. User Journey

Which function should you start with? Follow the decision tree below.

```{r journey, results='asis'}
emit_mermaid("vig_arch_user_journey_diagram",
             "User journey diagram requires `tar_make()` to render.",
             caption = "Figure 3: Decision tree guiding users from their question (compare risks, explore regions, convert units) to the appropriate function.",
             alt_text = "Mermaid decision tree flowchart with three entry points — compare risks, explore regions, convert units — leading to specific package functions.")
```

## 4. Developer Workflow

The 9-step workflow for contributing to this package.
Steps 4--5 follow the RED-GREEN TDD cycle.

```{r developer, results='asis'}
emit_mermaid("vig_arch_developer_diagram",
             "Developer diagram requires `tar_make()` to render.",
             caption = "Figure 4: Nine-step contributor workflow from issue creation through TDD (steps 4–5), documentation, CI checks, and PR merge.",
             alt_text = "Mermaid flowchart showing a nine-step development workflow: issue, branch, plan, RED test, GREEN implementation, refactor, document, check, and PR.")
```

## 5. Targets DAG

Auto-generated dependency graph of the full targets pipeline.

```{r visnetwork}
#| fig-cap: "Interactive dependency graph of the full targets pipeline. Nodes represent targets; edges show dependencies. Hover for details, drag to rearrange."
#| fig-alt: "Interactive visNetwork graph showing the directed acyclic graph (DAG) of approximately 40 targets with colour-coded nodes for data, function, and vignette targets."
show_target("vig_arch_tar_visnetwork")
```

## Pipeline Telemetry

### Dependency Graph

```{r telemetry-dep-graph}
#| echo: false
#| results: asis
#| fig-cap: "Target dependency graph showing data flow across the micromort pipeline. Nodes represent individual targets; edges show upstream dependencies. Built from targets::tar_network() edges."
#| fig-alt: "Directed graph of targets pipeline dependencies."
show_target("vig_pipeline_dependency_graph")
```

### Plans and Targets

```{r telemetry-plans-targets}
#| echo: false
#| results: asis
show_target("vig_pipeline_summary",
  caption = "Pipeline plans and target counts. Each plan file contributes a set of targets to the directed acyclic graph. Source: targets::tar_manifest().")
```

### Top 5 Targets by Storage Size

```{r telemetry-top-by-size}
#| echo: false
#| results: asis
show_target("vig_telemetry_top_by_size",
  caption = "Largest targets by serialised RDS size (bytes). Large targets may indicate opportunities for compression or lazy evaluation. Source: targets::tar_meta().")
```

### Top 5 Targets by Compute Time

```{r telemetry-top-by-time}
#| echo: false
#| results: asis
show_target("vig_telemetry_top_by_time",
  caption = "Slowest targets by wall-clock build time (seconds). Bottleneck targets are candidates for crew parallelisation. Source: targets::tar_meta().")
```

### Commit Velocity

```{r telemetry-commit-velocity}
#| echo: false
#| results: asis
#| fig-cap: "Weekly commit frequency over the last 26 weeks. Each bar represents commits merged in a calendar week. Source: gert::git_log()."
#| fig-alt: "Bar chart showing number of commits per week over the last 6 months."
show_target("vig_commit_velocity")
```

### Issues and Pull Requests

```{r telemetry-github-activity}
#| echo: false
#| results: asis
show_target("vig_github_activity",
  caption = "GitHub issues and pull requests summary. Open, closed, and merged counts. Source: gh::gh() API.")
```

### Codebase Metrics

```{r telemetry-codebase-metrics}
#| echo: false
#| results: asis
show_target("vig_codebase_metrics",
  caption = "Package codebase summary: R files, lines of code, exported functions, test files, and vignettes. Source: fs::dir_info() and NAMESPACE parsing.")
```

## Reproducibility

```{r architecture-session-info, eval=TRUE}
sessionInfo()
```
