# ============================================================
# build_munichvisitors.R
# Run this entire script once from any R session.
# It will create the complete munichvisitors package in the
# folder specified by `pkg_path` below, download the data,
# write all source files, document, and check the package.
#
# Prerequisites — install once if not already present:
#   install.packages(c("usethis", "devtools", "roxygen2",
#                      "ggplot2", "readr", "janitor",
#                      "testthat", "knitr", "rmarkdown"))
# ============================================================

pkg_path <- "~/munichvisitors"   # <- change this if you want it somewhere else

# ============================================================
# 0. Install dependencies if missing
# ============================================================

needed <- c("usethis", "devtools", "roxygen2",
            "ggplot2", "dplyr", "scales", "readr", "janitor",
            "testthat", "knitr", "rmarkdown")
to_install <- needed[!sapply(needed, requireNamespace, quietly = TRUE)]
if (length(to_install) > 0) install.packages(to_install)

# ============================================================
# 1. Create package scaffold
# ============================================================

usethis::create_package(pkg_path, open = FALSE)

# Explicitly set the active project to the new folder.
# create_package() can reset usethis to a pre-existing package it detects
# nearby — this overrides that and makes sure every subsequent usethis::
# call targets the right folder.
usethis::proj_set(pkg_path)
setwd(pkg_path)

# Confirm both usethis and the working directory are pointing at the right place.
# These two paths should match. If they don't, stop and check before continuing.
stopifnot(
  "usethis active project is wrong folder" =
    normalizePath(usethis::proj_get()) == normalizePath(pkg_path),
  "working directory is wrong folder" =
    normalizePath(getwd()) == normalizePath(pkg_path)
)
message("✔ Active project confirmed: ", normalizePath(pkg_path))

# ============================================================
# 2. DESCRIPTION — overwrite with complete metadata
# ============================================================

writeLines(
  paste0(
    'Package: munichvisitors
Title: Monthly Visitor Counts for Munich Museums
Version: 0.0.0.9000
Authors@R:
    person("First", "Last", , "you@example.com", role = c("aut", "cre"))
Description: Provides tidy monthly visitor statistics for Munich\'s museums
    from Munich Open Data (Statistisches Amt München), with a helper
    plot function for exploring trends over time.
License: MIT + file LICENSE
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: ', packageVersion("roxygen2"), '
LazyData: true
Imports:
    dplyr,
    ggplot2,
    scales
Suggests:
    janitor,
    readr,
    testthat (>= 3.0.0),
    knitr,
    rmarkdown
Config/testthat/edition: 3
VignetteBuilder: knitr'),
  "DESCRIPTION"
)

# ============================================================
# 3. Licence
# ============================================================

usethis::use_mit_license()

# ============================================================
# 4. README.Rmd
# ============================================================

# Matches Exercise 1.3: students run usethis::use_readme_rmd() then write
# by hand. Here we call it first (adds README.Rmd to .Rbuildignore), then
# overwrite the template with the complete solution content.
usethis::use_readme_rmd(open = FALSE)

writeLines(
  '---
output: github_document
---

<!-- README.md is generated from README.Rmd. Please edit that file. -->

# munichvisitors

The `munichvisitors` package provides tidy monthly visitor counts for
Munich\'s public museums, sourced from Munich Open Data (Statistisches
Amt München). It includes a ready-to-use plot function so you can
explore trends with a single line of code.

## Installation

``` r
# install.packages("devtools")
devtools::install_github("your-username/munichvisitors")
```

## What\'s included

- `museum_visitors` — a data frame of monthly visitor counts per museum,
  with year-on-year comparison figures
- `plot_museums()` — a line chart of visitor trends over time

## Example

``` r
library(munichvisitors)
plot_museums()
```

## Data source

Landeshauptstadt München (2017). Monatszahlen Museen. Statistisches Amt München.
Lizenz: [Datenlizenz Deutschland Namensnennung 2.0](https://www.govdata.de/dl-de/by-2-0).
<https://datengartln.de/datasets/detail/bfb4a286-bea5-4bfe-82ce-b9bd354284a5/>',
  "README.Rmd"
)

# ============================================================
# 5. data-raw script  [Exercise 2.1 + 2.2]
# ============================================================

# Exercise 2.1: usethis::use_data_raw() creates the data-raw/ folder,
# adds it to .Rbuildignore, and opens the script template for editing.
usethis::use_data_raw("museum-visitors", open = FALSE)

# In the practical, students also run:
#   usethis::use_package("readr", type = "Suggests")
#   usethis::use_package("janitor", type = "Suggests")
# We skip those here because both are already written into Suggests above.

# Exercise 2.2: overwrite the template with the complete solution script:
writeLines(
  '## code to prepare `museum_visitors` dataset goes here

url <- paste0(
  "https://opendata.muenchen.de/dataset/bfb4a286-bea5-4bfe-82ce-b9bd354284a5/",
  "resource/6c6a809e-91ee-4f3e-9268-a8b7bc38311c/download/",
  "monatszahlen2603_museen_16_03_26.csv"
)

museum_visitors_raw <- readr::read_csv(url)

museum_visitors <- museum_visitors_raw |>
  janitor::clean_names()   # WERT -> wert, AUSPRAEGUNG -> auspraegung, ...

usethis::use_data(museum_visitors, overwrite = TRUE)

# Source this entire script to download and save the data:
# use Ctrl+Shift+Enter or click Source in the RStudio editor pane.',
"data-raw/museum-visitors.R"
)

# Run the data-raw script now to download and save the data:
source("data-raw/museum-visitors.R")

# ============================================================
# 6. R/data.R — dataset documentation  [Exercise 2.4]
# ============================================================

# In the practical, students run usethis::use_r("data") to create this file.
# Here we write it directly with the complete solution content:
writeLines(
  '#\' Monthly visitor counts for Munich museums
#\'
#\' Monthly visitor statistics for Munich\'s public museums, sourced from
#\' Munich Open Data (Statistisches Amt München). Data covers all major
#\' municipal museums with year-on-year comparison figures.
#\'
#\' @format A data frame with one row per museum per month:
#\' \\describe{
#\'   \\item{monatszahl}{Category label (always "Besucher*innen")}
#\'   \\item{auspraegung}{Museum name}
#\'   \\item{jahr}{Year}
#\'   \\item{monat}{Year-month code (YYYYMM format)}
#\'   \\item{wert}{Visitor count for that month}
#\'   \\item{vorjahreswert}{Visitor count in the same month of the prior year}
#\'   \\item{veraend_vormonat_prozent}{Percentage change vs. previous month}
#\'   \\item{veraend_vorjahresmonat_prozent}{Percentage change vs. same month prior year}
#\'   \\item{zwoelf_monate_mittelwert}{12-month rolling average}
#\' }
#\' @source Landeshauptstadt München (2017). Monatszahlen Museen.
#\'   Statistisches Amt München. Lizenz: Datenlizenz Deutschland
#\'   Namensnennung 2.0 (dl-by-de).
#\'   <https://datengartln.de/datasets/detail/bfb4a286-bea5-4bfe-82ce-b9bd354284a5/>
"museum_visitors"',
  "R/data.R"
)

# ============================================================
# 7. R/plot_museums.R — plot function  [Exercise 3.1]
# ============================================================

# In the practical, students run:
#   usethis::use_r("plot_museums")
#   usethis::use_package("ggplot2")
# We skip those here — ggplot2 is already in DESCRIPTION above.
writeLines(
  '#\' Annual visitor counts per Munich museum
#\'
#\' Plots annual visitor totals for each museum in the bundled
#\' \\code{museum_visitors} dataset, using the yearly summary rows
#\' (where \\code{monat == "Summe"}).
#\'
#\' @return A \\code{ggplot2} plot object.
#\' @export
#\' @examples
#\' plot_museums()
plot_museums <- function() {
  museum_visitors |>
    dplyr::filter(
      monat == "Summe"
    ) |>
    ggplot2::ggplot(ggplot2::aes(x = jahr, y = wert, colour = auspraegung)) +
    ggplot2::geom_line() +
    ggplot2::labs(x = "Year", y = "Visitors", colour = "Museum") +
    ggplot2::ggtitle("Annual Visitors to Museums in Munich") +
    ggplot2::scale_y_continuous(labels = scales::label_number())
}',
  "R/plot_museums.R"
)

# ============================================================
# 8. R/utils.R — silence R CMD check NOTE for tidy eval columns
# ============================================================

writeLines(
  '# Suppress R CMD check NOTE: "no visible binding for global variable"
# These are column names used via tidy evaluation in dplyr and ggplot2,
# plus the dataset name referenced directly inside plot_museums()
utils::globalVariables(c("museum_visitors", "monat", "wert", "auspraegung", "jahr"))',
  "R/utils.R"
)

# ============================================================
# 9. Tests  [Exercise 3.4]
# ============================================================

usethis::use_testthat()

writeLines(
  'test_that("plot_museums returns a ggplot object", {
  result <- plot_museums()
  expect_s3_class(result, "gg")
})

test_that("museum_visitors has expected columns", {
  expect_true(all(c("auspraegung", "jahr", "monat", "wert") %in%
                    names(museum_visitors)))
})',
  "tests/testthat/test-plot_museums.R"
)

# ============================================================
# 10. Vignette  [Exercise 5.1]
# ============================================================

# In the practical, students run usethis::use_vignette("munichvisitors").
# Here we call it the same way, then overwrite the template:
usethis::use_vignette("munichvisitors")

vignette_lines <- c(
  '---',
  'title: "Getting started with munichvisitors"',
  'output: rmarkdown::html_vignette',
  'vignette: >',
  '  %\\VignetteIndexEntry{Getting started with munichvisitors}',
  '  %\\VignetteEngine{knitr::rmarkdown}',
  '  %\\VignetteEncoding{UTF-8}',
  '---',
  '',
  '```{r setup, include = FALSE}',
  'knitr::opts_chunk$set(collapse = TRUE, comment = "#>")',
  '```',
  '',
  '## Overview',
  '',
  "Munich's public museums publish monthly visitor counts as open data",
  'through the city\'s open data portal. The `munichvisitors` package bundles',
  'this data in a tidy, ready-to-use format and provides a quick plot',
  'function for exploring trends.',
  '',
  '## Installation',
  '',
  '```{r eval = FALSE}',
  'devtools::install_github("your-username/munichvisitors")',
  '```',
  '',
  '```{r}',
  'library(munichvisitors)',
  '```',
  '',
  '## The data',
  '',
  'The `museum_visitors` dataset contains one row per museum per month.',
  '',
  '```{r}',
  'head(museum_visitors)',
  '```',
  '',
  'Key columns:',
  '',
  '- `auspraegung` \u2014 the museum name',
  '- `jahr` \u2014 the year',
  '- `monat` \u2014 year-month as YYYYMM integer (e.g. `202301` = January 2023)',
  '- `wert` \u2014 visitor count for that month',
  '- `vorjahreswert` \u2014 visitor count in the same month of the prior year',
  '',
  '## Visualising trends',
  '',
  '`plot_museums()` draws one line per museum:',
  '',
  '```{r fig.width = 8, fig.height = 5}',
  'plot_museums()',
  '```',
  '',
  'The returned object is a standard `ggplot2` plot, so you can customise it:',
  '',
  '```{r fig.width = 8, fig.height = 5}',
  'plot_museums() +',
  '  ggplot2::theme_minimal() +',
  '  ggplot2::labs(title = "Monthly visitors to Munich museums")',
  '```',
  '',
  '## Data source',
  '',
  'Data published by Statistisches Amt \u00fcnchen under Datenlizenz Deutschland',
  'Namensnennung 2.0. Available at the',
  '[Munich Open Data portal](https://datengartln.de/datasets/detail/bfb4a286-bea5-4bfe-82ce-b9bd354284a5/).'
)
writeLines(vignette_lines, "vignettes/munichvisitors.Rmd")

# ============================================================
# 11. .Rbuildignore additions
# ============================================================

# data-raw and README.Rmd are already added to .Rbuildignore by
# use_data_raw() and use_readme_rmd() above. Just add this build script:
usethis::use_build_ignore("^build_munichvisitors\\.R$")

# ============================================================
# 12. Document (generates man/ .Rd files and NAMESPACE)
# ============================================================

devtools::document()

# ============================================================
# 13. Load and sanity check
# ============================================================

devtools::load_all()

cat("\n--- museum_visitors preview ---\n")
print(head(museum_visitors))

cat("\n--- glimpse ---\n")
dplyr::glimpse(museum_visitors)

cat("\n--- plot_museums() ---\n")
print(plot_museums())

# ============================================================
# 14. Run tests
# ============================================================

cat("\n--- Running tests ---\n")
devtools::test()

# ============================================================
# 15. Full R CMD check
# ============================================================

cat("\n--- Running devtools::check() ---\n")
devtools::check()

cat("\n\nDone! Package is at:", normalizePath(pkg_path), "\n")
