## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  fig.alt = "Figura generada por la viñeta; ver texto para detalles.",
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  warning = FALSE,
  message = FALSE
)

# Load required packages
library(cowfootR)
library(ggplot2)
library(dplyr)

## ----eval=FALSE---------------------------------------------------------------
# # Install from CRAN (when available)
# install.packages("cowfootR")
# 
# # Or install development version from GitHub
# # devtools::install_github("yourusername/cowfootR")

## -----------------------------------------------------------------------------
library(cowfootR)

## -----------------------------------------------------------------------------
# Define farm-gate boundaries (most common approach)
boundaries <- set_system_boundaries("farm_gate")
boundaries

## -----------------------------------------------------------------------------
# Farm characteristics
farm_data <- list(
  # Herd composition
  dairy_cows = 100,
  heifers = 30,
  calves = 25,

  # Production
  milk_litres = 600000, # Annual milk production
  milk_yield_per_cow = 6000, # kg/cow/year

  # Farm area
  total_area_ha = 120,
  productive_area_ha = 110,

  # Inputs
  concentrate_kg = 180000, # Annual concentrate use
  n_fertilizer_kg = 1500, # Nitrogen fertilizer
  diesel_litres = 8000, # Annual diesel consumption
  electricity_kwh = 35000 # Annual electricity use
)

farm_data

## -----------------------------------------------------------------------------
# Calculate enteric methane emissions
enteric_emissions <- calc_emissions_enteric(
  n_animals = farm_data$dairy_cows,
  cattle_category = "dairy_cows",
  avg_milk_yield = farm_data$milk_yield_per_cow,
  tier = 2, # Use Tier 2 for more accurate results
  boundaries = boundaries
)

enteric_emissions

## -----------------------------------------------------------------------------
# Calculate manure management emissions
manure_emissions <- calc_emissions_manure(
  n_cows = farm_data$dairy_cows,
  manure_system = "pasture", # Typical for extensive systems
  tier = 2,
  include_indirect = TRUE,
  boundaries = boundaries
)

manure_emissions

## -----------------------------------------------------------------------------
# Calculate soil N2O emissions
soil_emissions <- calc_emissions_soil(
  n_fertilizer_synthetic = farm_data$n_fertilizer_kg,
  n_excreta_pasture = farm_data$dairy_cows * 100, # Estimated N excretion
  area_ha = farm_data$total_area_ha,
  soil_type = "well_drained",
  climate = "temperate",
  include_indirect = TRUE,
  boundaries = boundaries
)

soil_emissions

## -----------------------------------------------------------------------------
# Calculate energy-related emissions
energy_emissions <- calc_emissions_energy(
  diesel_l = farm_data$diesel_litres,
  electricity_kwh = farm_data$electricity_kwh,
  country = "UY", # Uruguay electricity grid
  boundaries = boundaries
)

energy_emissions

## -----------------------------------------------------------------------------
# Calculate emissions from purchased inputs
input_emissions <- calc_emissions_inputs(
  conc_kg = farm_data$concentrate_kg,
  fert_n_kg = farm_data$n_fertilizer_kg,
  region = "global", # Use global emission factors
  boundaries = boundaries
)

input_emissions

## -----------------------------------------------------------------------------
# Combine all emission sources
total_emissions <- calc_total_emissions(
  enteric_emissions,
  manure_emissions,
  soil_emissions,
  energy_emissions,
  input_emissions
)

total_emissions

## -----------------------------------------------------------------------------
# Calculate emissions per kg of milk (FPCM)
milk_intensity <- calc_intensity_litre(
  total_emissions = total_emissions,
  milk_litres = farm_data$milk_litres,
  fat = 3.8, # Typical fat content
  protein = 3.2 # Typical protein content
)

milk_intensity

## -----------------------------------------------------------------------------
# Calculate emissions per hectare
area_intensity <- calc_intensity_area(
  total_emissions = total_emissions,
  area_total_ha = farm_data$total_area_ha,
  area_productive_ha = farm_data$productive_area_ha,
  area_breakdown = list(
    pasture_permanent = 80,
    pasture_temporary = 20,
    crops_feed = 15,
    infrastructure = 5
  )
)

area_intensity

## -----------------------------------------------------------------------------
# Create a data frame for plotting
emission_breakdown <- data.frame(
  Source = names(total_emissions$breakdown),
  Emissions = as.numeric(total_emissions$breakdown)
)

# Create pie chart
ggplot(emission_breakdown, aes(x = "", y = Emissions, fill = Source)) +
  geom_col(width = 1) +
  coord_polar("y", start = 0) +
  theme_void() +
  labs(
    title = "Farm Emissions by Source",
    subtitle = paste("Total:", round(total_emissions$total_co2eq), "kg CO₂eq/year")
  ) +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)
  )

## -----------------------------------------------------------------------------
# Create comparison chart
intensity_data <- data.frame(
  Metric = c(
    "Milk Intensity\n(kg CO₂eq/kg FPCM)",
    "Area Intensity\n(kg CO₂eq/ha)"
  ),
  Value = c(
    milk_intensity$intensity_co2eq_per_kg_fpcm,
    area_intensity$intensity_per_productive_ha
  ),
  Benchmark = c(1.2, 8000) # Typical benchmark values
)

ggplot(intensity_data, aes(x = Metric)) +
  geom_col(aes(y = Value), fill = "steelblue", alpha = 0.7) +
  geom_point(aes(y = Benchmark), color = "red", size = 3) +
  geom_text(aes(y = Benchmark, label = "Benchmark"),
    color = "red", vjust = -0.5
  ) +
  labs(
    title = "Farm Intensity Metrics",
    y = "Value",
    x = ""
  ) +
  theme_minimal()

