#!/usr/bin/env Rscript
# ==============================================================================
# Chapter 13: R for Next Gen Biologist
# Script: r13_reproducible_quarto_notebook.R
# Description: Capstone: Reproducible Multi-Omics Reports with Quarto & R Markdown:
#              Automated generation of parameterized Quarto/Rmd computational notebooks,
#              literate programming, and pipeline provenance with sessionInfo().
# Usage: Rscript r13_reproducible_quarto_notebook.R
# ==============================================================================

cat("\n=======================================================\n")
cat(" OMICS.CO.IN - R FOR NEXT GEN BIOLOGIST: CHAPTER 13\n")
cat(" Reproducible Multi-Omics Research with Quarto & Rmd\n")
cat("=======================================================\n\n")

temp_dir <- tempdir()
cat(sprintf("Output workspace: %s\n", temp_dir))

# 1. Generating a Complete, Standalone Quarto Notebook (.qmd)
cat("[Step 1] Generating Automated Quarto Notebook (.qmd)...\n")
qmd_path <- file.path(temp_dir, "genomic_analysis_report.qmd")

qmd_content <- '---
title: "Precision Oncology Multi-Omics Transcriptomic Report"
author: "Computational Biology Core, Omics Portal"
date: today
format:
  html:
    toc: true
    toc-depth: 3
    theme: cosmo
    code-fold: show
    code-tools: true
    self-contained: true
params:
  cohort: "Non-Small Cell Lung Cancer (NSCLC)"
  padj_cutoff: 0.01
  log2fc_cutoff: 1.5
---

## Executive Summary

This computational notebook documents the reproducible statistical analysis of gene expression in **`r params$cohort`** patients.

## 1. Environment & Setup

```{r setup, message=FALSE, warning=FALSE}
library(knitr)
set.seed(42)

# Verify analytical thresholds
cat("Significance Threshold (FDR) :", params$padj_cutoff, "\n")
cat("Effect Size Threshold (|log2FC|):", params$log2fc_cutoff, "\n")
```

## 2. Differential Expression Filtering

```{r filter_hits}
# Load differential results
genes <- c("EGFR", "KRAS", "TP53", "ALK", "ROS1", "MET", "RET", "BRAF")
log2FC <- c(2.8, -1.9, 3.4, 4.1, 0.4, 2.1, -0.3, 1.8)
padj <- c(1.2e-7, 4.5e-4, 8.9e-11, 2.1e-9, 0.42, 3.1e-5, 0.78, 1.1e-3)

de_table <- data.frame(
  Gene = genes,
  log2FoldChange = log2FC,
  padj = padj,
  stringsAsFactors = FALSE
)

# Apply cohort filter
de_table$Significant <- (de_table$padj < params$padj_cutoff) & 
                        (abs(de_table$log2FoldChange) >= params$log2fc_cutoff)

kable(de_table, caption = "Candidate Oncogenic Drivers in Cohort")
```

## 3. Session Provenance & Environment Lock

```{r session_provenance}
sessionInfo()
```
'

writeLines(qmd_content, qmd_path)
cat(sprintf("Generated Quarto Notebook: %s\n", qmd_path))

# 2. Inspecting Environment Provenance
cat("\n[Step 2] Capturing Pipeline Environment Provenance (sessionInfo)...\n")
s_info <- sessionInfo()
cat(sprintf("R Version Installed  : %s\n", s_info$R.version$version.string))
cat(sprintf("Platform Architecture: %s\n", s_info$platform))
cat(sprintf("Base Packages Loaded : %s\n", paste(s_info$basePkgs, collapse = ", ")))

# 3. Best Practices for Production R Workflows in Genomics
cat("\n[Step 3] Computational Biology Reproducibility Checklist:\n")
cat("  [x] 1. Version Control: Track R scripts, templates, and Nextflow code in Git.\n")
cat("  [x] 2. Environment Management: Lock package versions using renv (renv::snapshot / renv::restore).\n")
cat("  [x] 3. Data Integrity: Store raw sequencing counts immutably; never overwrite source BAMs/FASTQs.\n")
cat("  [x] 4. Random Seeds: Explicitly set set.seed() before any stochastic algorithm (UMAP, k-means, bootstrapping).\n")
cat("  [x] 5. Parameterised Notebooks: Separate input cohort paths from analytical logic.\n")

cat("\n[SUCCESS] Chapter 13 reproducible research script executed successfully.\n")
