# demo/platevision_workflow.R

# ==============================================================================
# PlateVision: Standard Workflow Demo
# ==============================================================================
# This demo simulates a typical analysis pipeline:
# 1. Planning reagents
# 2. Importing raw machine data (Excel) + Metadata (CSV)
# 3. Visual QC of the plate
# 4. Statistical Analysis (-ddCt method)
# 5. Visualization (Bar & Volcano plots)
# ==============================================================================

library(PlateVision)
library(dplyr)
library(ggplot2)

# --- STEP 1: LOCATE DEMO DATA ---
# These files are included with the package.
# system.file() finds them on your specific machine.
raw_file <- system.file("extdata", "experiment_data.xlsx", package = "PlateVision")
map_file <- system.file("extdata", "plate_map.csv", package = "PlateVision")

message("Using raw file: ", raw_file)


# --- STEP 2: PRE-LAB UTILITIES ---
# Scenario: You are setting up a new experiment with 2 samples and 2 genes.
message("\n--- Generating Master Mix Recipe ---")
recipe <- calculate_reagents(n_samples = 2, n_genes = 2)
print(recipe)


# --- STEP 3: DATA IMPORT ---
message("\n--- Importing Data ---")
df <- import_plate(raw_file = raw_file, map_file = map_file)
print(head(df))


# --- STEP 4: VISUAL QC (THE "GIMMICK") ---
# Check the physical layout of your plate.
# Look for 'Edge Effects' or pipette errors.
message("\n--- Generating Plate Map ---")
# Tip: Set interactive = TRUE for a hoverable plotly graph
p_map <- view_plate(df, fill_var = "Ct", interactive = FALSE)
print(p_map)


# --- STEP 5: REPLICATE QUALITY CONTROL ---
# Automatically flag wells where technical replicates disagree (SD > 0.5)
message("\n--- Running QC Check ---")
# Note: The demo data intentionally contains a "bad" replicate in Well B6
bad_wells <- check_replicates(df, sd_threshold = 0.5)
print(bad_wells)


# --- STEP 6: STATISTICAL ANALYSIS (-ddCt) ---
message("\n--- Calculating Fold Change ---")
results <- calculate_ddct(
  data = df,
  ref_gene = "GAPDH",       # Your housekeeping gene
  control_group = "WT"      # Your calibrator group
)

# Preview the math
print(results %>% select(Sample, Gene, dd_ct, fold_change, p_val))


# --- STEP 7: PUBLICATION PLOTS ---
message("\n--- Plotting Final Results ---")

# A. Bar Chart with Error Bars
p_bar <- plot_bars(results)
print(p_bar)

# B. Volcano Plot (Significance vs Fold Change)
p_volc <- plot_volcano(results)
print(p_volc)

message("\nDone! Analysis complete.")
