---
title: "Practical Examples with Eunomia"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Practical Examples with Eunomia}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

## Introduction

This vignette shows realistic package usage against Eunomia without assuming any API
that the package does not expose. The examples use two cohort definitions already
available in a cohort table:

- target cohort `1`
- outcome cohort `2`

## Connect to Eunomia

```{r setup-common}
library(OdysseusSurvivalModule)
library(DatabaseConnector)
library(Eunomia)

connectionDetails <- Eunomia::getEunomiaConnectionDetails()
connection <- DatabaseConnector::connect(connectionDetails)

cdmDatabaseSchema <- Eunomia::getEunomiaCdmDatabaseSchema()
cohortDatabaseSchema <- Eunomia::getEunomiaResultsSchema()
```

## Example 1: Build a Survival Dataset

```{r example-build}
survivalData <- OdysseusSurvivalModule:::addCohortSurvival(
  connection = connection,
  cdmDatabaseSchema = cdmDatabaseSchema,
  cohortDatabaseSchema = cohortDatabaseSchema,
  targetCohortTable = "cohort",
  targetCohortId = 1,
  outcomeCohortTable = "cohort",
  outcomeCohortId = 2,
  followUpDays = 365,
  includeAge = TRUE,
  includeGender = TRUE
)

head(survivalData)
```

## Example 2: Overall Kaplan-Meier Summary

```{r example-km-overall}
kmOverall <- singleEventSurvival(
  survivalData = survivalData,
  timeScale = "days",
  model = "km"
)

kmOverall[["overall"]]$summary
head(kmOverall[["overall"]]$data)
```

## Example 3: Compare Gender Groups

```{r example-gender}
kmGender <- singleEventSurvival(
  survivalData = survivalData,
  timeScale = "days",
  model = "km",
  strata = "gender"
)

kmGender[["gender=Female"]]$summary
kmGender[["gender=Male"]]$summary
kmGender$logrank_test_gender
```

## Example 4: Compare Age Groups

```{r example-age}
kmAge <- singleEventSurvival(
  survivalData = survivalData,
  timeScale = "days",
  model = "km",
  strata = "age_group",
  ageBreaks = list(c(18, 49), c(50, 64), c(65, Inf))
)

kmAge[["age_group=18-49"]]$summary
kmAge[["age_group=50-64"]]$summary
kmAge[["age_group=65+"]]$summary
kmAge$logrank_test_age_group
```

## Example 5: Compare Model Families

```{r example-models}
modelNames <- c("km", "cox", "weibull", "lognormal")

fits <- lapply(modelNames, function(modelName) {
  singleEventSurvival(
    survivalData = survivalData,
    timeScale = "days",
    model = modelName,
    covariates = if (modelName == "km") NULL else c("age_years")
  )
})
names(fits) <- modelNames

summaryTable <- data.frame(
  model = names(fits),
  medianSurvival = vapply(fits, function(x) x[["overall"]]$summary$medianSurvival, numeric(1)),
  meanSurvival = vapply(fits, function(x) x[["overall"]]$summary$meanSurvival, numeric(1)),
  stringsAsFactors = FALSE
)

summaryTable
```

## Example 6: Produce a Simple Report Table

```{r example-report}
reportTable <- data.frame(
  group = c("Overall", "Female", "Male"),
  n = c(
    kmGender[["overall"]]$summary$n,
    kmGender[["gender=Female"]]$summary$n,
    kmGender[["gender=Male"]]$summary$n
  ),
  events = c(
    kmGender[["overall"]]$summary$events,
    kmGender[["gender=Female"]]$summary$events,
    kmGender[["gender=Male"]]$summary$events
  ),
  medianSurvival = c(
    kmGender[["overall"]]$summary$medianSurvival,
    kmGender[["gender=Female"]]$summary$medianSurvival,
    kmGender[["gender=Male"]]$summary$medianSurvival
  ),
  stringsAsFactors = FALSE
)

reportTable
```

## Example 7: Plot from Returned Data

```{r example-plot}
plot(
  kmGender[["gender=Female"]]$data$time,
  kmGender[["gender=Female"]]$data$survival,
  type = "s",
  col = "firebrick",
  xlab = "Time (days)",
  ylab = "Survival probability",
  ylim = c(0, 1),
  main = "Kaplan-Meier curve by gender"
)

lines(
  kmGender[["gender=Male"]]$data$time,
  kmGender[["gender=Male"]]$data$survival,
  type = "s",
  col = "steelblue"
)
```

## Cleanup

```{r cleanup-all}
DatabaseConnector::disconnect(connection)
```

## Summary

The practical Eunomia workflow is:

1. Connect to Eunomia.
2. Use prebuilt target and outcome cohorts.
3. Build a survival dataset with the internal helper.
4. Fit one or more models with `singleEventSurvival()`.
5. Read results from named list entries and their `data` and `summary` fields.
