# SmartCane Client Type Architecture

SmartCane serves two distinct agricultural client types with different needs and data processing requirements. This document explains how the system branches to support both, starting from a unified pipeline and diverging at Stage 80.

## Client Type Overview

| Aspect | **Agronomic Support (AURA)** | **Cane Supply (ANGATA)** |
|--------|------------------------------|------------------------|
| **Project Examples** | chemba, xinavane, esa, aura, simba | angata |
| **Primary Use** | Farm-level agronomic advisory, crop monitoring | Sugarcane harvest operations, milling coordination |
| **Field Count** | Typically 1–10 fields | Typically 20–50+ fields |
| **Data Dependencies** | `pivot.geojson` required; `harvest.xlsx` optional | `pivot.geojson` + `harvest.xlsx` both required |
| **Harvest Integration** | Minimal; focuses on crop health | Central; harvest prediction drives operations |
| **Output Type** | Farm summary + field-level trends | Per-field alerts + harvest readiness |
| **Report Client** | Agronomist / farm consultant | Mill operations / harvest scheduler |
| **KPI Focus** | Uniformity, growth patterns, anomalies | Acreage, age phases, harvest readiness |

---

## Configuration: Project → Client Type Mapping

**File**: `r_app/parameters_project.R`

```r
CLIENT_TYPE_MAP <- list(
  "angata"     = "cane_supply",
  "chemba"     = "agronomic_support",
  "xinavane"   = "agronomic_support",
  "esa"        = "agronomic_support",
  "simba"      = "agronomic_support",
  "aura"       = "agronomic_support"
)
```

**How it Works**:
1. At pipeline startup, project name (e.g., "angata") is passed to `parameters_project.R`
2. Script looks up project in `CLIENT_TYPE_MAP`
3. Downstream scripts (Stage 80, Scripts 90/91) use this mapping to determine which utilities and reports to use

---

## Pipeline Divergence: Before vs After Stage 80

### Stages 00–40: Unified Pipeline

**All client types run identical processing**:
- Stage 00 (Python): Download 4-band satellite imagery
- Stage 10 (R): Split into per-field tiles
- Stage 20 (R): Extract Canopy Index
- Stage 30 (R): Interpolate growth model
- Stage 40 (R): Create weekly mosaics

**Output**: Per-field weekly mosaics (`weekly_mosaic/{FIELD}/week_WW_YYYY.tif`) + interpolated CI data

### Stage 80: KPI Calculation (Client-Type Branching Point)

**File**: `r_app/80_calculate_kpis.R`

```r
# Pseudo-code showing branching logic
PROJECT <- Sys.getenv("PROJECT")
client_type <- CLIENT_TYPE_MAP[[PROJECT]]

if (client_type == "agronomic_support") {
  source("80_utils_agronomic_support.R")
  kpis <- calculate_agronomic_kpis(weekly_mosaic, boundaries, harvest_data)
  
} else if (client_type == "cane_supply") {
  source("80_utils_cane_supply.R")
  kpis <- calculate_cane_supply_kpis(weekly_mosaic, boundaries, harvest_data, imminent_prob)
}

# Both save KPI summary to RDS
saveRDS(kpis, file = "kpi_summary_tables_week{WW}.rds")
```

### Stages 90 & 91: Report Rendering (Client-Type Specific)

**Agronomic Support Branch** → Script 90
```
r_app/90_CI_report_with_kpis_agronomic_support.Rmd
```

**Cane Supply Branch** → Script 91
```
r_app/91_CI_report_with_kpis_cane_supply.Rmd
```

---

## Agronomic Support (AURA) Pipeline

### KPIs Calculated (Stage 80)

**File**: `r_app/80_utils_agronomic_support.R`

| KPI | Calculation | Interpretation | Data Source |
|------|------------|-----------------|-------------|
| **Field Uniformity** | Coefficient of Variation (CV) of CI within field + Moran's I | Low CV = healthy uniform crop; High CV = stress/disease clusters | Current week mosaic + spatial analysis |
| **Area Change** | % pixel difference week-over-week | Increasing pixels = plant growth; decreasing = harvest/stress | Previous week vs current week |
| **TCH Forecast** | CI trajectory × historical yield | Projected tonnage per hectare at harvest | Growth model interpolation + training data |
| **Growth Decline** | Rate of change in daily CI | Negative slope = ripening or stress; positive = recovery | Interpolated time series (Stage 30) |
| **Weed Presence** | NDVI-based clustering analysis | Clustered spectral anomalies = weeds or pests | Multi-spectral bands |
| **Gap Filling Quality** | % of dates successfully interpolated | High % = reliable trend; Low % = cloudy season | Growth model output (Stage 30) |

### Report Output (Script 90)

**File**: `r_app/90_CI_report_with_kpis_agronomic_support.Rmd`

**Contents**:
- **Executive Summary**: Farm-level KPI averages (6 KPIs across all fields)
- **Field-Level Trends**: 8-week CV plots showing uniformity stability
- **Spatial Analysis**: Moran's I maps (cluster detection)
- **Interactive Map**: tmap with field boundaries and current CI values
- **Recommendations**: Rule-based suggestions based on KPI thresholds
- **Colorblind Palette**: Accessible color scheme (Viridis preferred)

**Output Filename**: `SmartCane_Report_agronomic_support_{PROJECT}_{DATE}.docx`

**Sample Usage**:
```r
# Render for Aura project, week 07, 2026
rmarkdown::render(
  "r_app/90_CI_report_with_kpis_agronomic_support.Rmd",
  params = list(
    data_dir = "aura",
    report_date = as.Date("2026-02-19")
  ),
  output_file = "SmartCane_Report_agronomic_support_aura_week07_2026.docx",
  output_dir = "laravel_app/storage/app/aura/reports"
)
```

---

## Cane Supply (ANGATA) Pipeline

### KPIs Calculated (Stage 80)

**File**: `r_app/80_utils_cane_supply.R`

| KPI | Calculation | Interpretation | Data Source |
|------|------------|-----------------|-------------|
| **Per-Field Acreage** | Field area (hectares + acres) | Tonnage forecast requires acreage | pivot.geojson area |
| **Phase Assignment** | Age derived from planting date in harvest.xlsx | Germination (0–6 wk), Tillering (4–16 wk), Grand Growth (17–39 wk), Maturation (39+ wk) | Harvest dates + current week # |
| **Harvest Readiness** | CI maturity threshold + imminent probability | Is field ready to harvest? What's the urgency? | CI values + Python 31 probability |
| **Stress Detection** | Growth rate vs baseline | Drop in daily CI = stress signal | Growth model daily_change |
| **Tonnage Forecast** | Phase × CI trajectory × regional yield model | Projected tons at harvest | Phase assignment + CI growth curve |
| **Status Trigger** | Composite alert (URGENT / ALERT / OK) | Field action priority for mill | Age + stress + readiness |

### Harvest Probability Integration (Python → R)

**Python Script 31**: `python_app/31_harvest_imminent_weekly.py`

- **Input**: CI time series from `combined_CI_data.rds` (Stage 20 output)
- **Output**: `harvest_imminent_weekly.csv` with columns:
  - `field_name`: Field identifier
  - `week`: ISO week number
  - `imminent_prob`: Probability (0.0–1.0) field is harvest-ready

**Integration in Stage 80**:
```r
# Load harvest imminent probabilities from Python 31
imminent_probs <- read.csv("harvest_imminent_weekly.csv")

# Use in harvest readiness KPI
for (field in all_fields) {
  prob <- imminent_probs[imminent_probs$field == field, "imminent_prob"]
  if (prob > 0.7) {
    status <- "URGENT: harvest imminent"
  } else if (prob > 0.5) {
    status <- "ALERT: harvest approaching"
  } else {
    status <- "OK: still growing"
  }
}
```

### Report Output (Script 91)

**File**: `r_app/91_CI_report_with_kpis_cane_supply.Rmd`

**Contents**:
- **Field-by-Field Status Table**: 21 columns (name, acreage, phase, CI, growth_rate, stress_flag, harvest_prob, status, ...)
- **Harvest Readiness Summary**: Which fields can be harvested this week?
- **Daily Forecast**: Projected tonnage per field × phase
- **Phase Distribution Chart**: How many fields in each growth stage?
- **Alerts Section**: URGENT fields (harvest-ready), ALERT fields (approaching), OK fields
- **Operational Notes**: Recommended harvest sequence by acreage/tonnage

**Output Filename**: `SmartCane_Report_cane_supply_{PROJECT}_{DATE}.docx`

**Sample Usage**:
```r
# Render for Angata project, week 07, 2026
rmarkdown::render(
  "r_app/91_CI_report_with_kpis_cane_supply.Rmd",
  params = list(
    data_dir = "angata",
    report_date = as.Date("2026-02-19")
  ),
  output_file = "SmartCane_Report_cane_supply_angata_week07_2026.docx",
  output_dir = "laravel_app/storage/app/angata/reports"
)
```

---

## Data Requirements: Input Files Needed

### Agronomic Support (AURA)

**Required**:
- `pivot.geojson` — Field boundaries (must exist, defines all analysis units)
- `merged_tif/{YYYY-MM-DD}.tif` — Downloaded from Stage 00

**Optional**:
- `harvest.xlsx` — If provided, Stage 30 uses it for season grouping; otherwise uses calendar weeks

### Cane Supply (ANGATA)

**Required**:
- `pivot.geojson` — Field boundaries
- `harvest.xlsx` — **MUST exist** with planting/harvest dates (Stage 30 requires it; Stage 80 requires it for phase assignment)
- `merged_tif/{YYYY-MM-DD}.tif` — Downloaded from Stage 00

**Optional**:
- `harvest_imminent_weekly.csv` — Output from Python 31; if not present, harvest readiness KPI uses only CI thresholds (less accurate)

---

## Configuration Parameter: Triggering Client-Type Logic

### In parameters_project.R

```r
# The project name determines client type lookup
PROJECT <- Sys.getenv("PROJECT")  # Set by calling script (e.g., "angata")

# CLIENT_TYPE_MAP is consulted by downstream scripts
CLIENT_TYPE <- CLIENT_TYPE_MAP[[PROJECT]]

# Example: if PROJECT == "angata", then CLIENT_TYPE == "cane_supply"
```

### In Stage 80 Script

```r
# Load project-specific configuration
source("parameters_project.R")

# Determine which utility functions to use
if (CLIENT_TYPE == "agronomic_support") {
  source("80_utils_agronomic_support.R")
} else if (CLIENT_TYPE == "cane_supply") {
  source("80_utils_cane_supply.R")
}
```

### In Report Scripts

**RMarkdown YAML params**:
```yaml
---
params:
  data_dir: "aura"              # Project directory
  report_date: "2026-02-19"     # Report week
  client_type: "agronomic_support"  # Determined from data_dir
---
```

---

## Decision Tree: Which Report Will Be Generated?

```mermaid
%% KPI Client Type Logic
flowchart TD
    A["Stage 80<br/>Calculate KPIs"] -->|Read PROJECT| B["Load parameters_project.R"]
    B -->|Lookup in CLIENT_TYPE_MAP| C{"Client Type?"}
    
    C -->|agronomic_support<br/>chemba/aura/esa/etc| D["Source<br/>80_utils_agronomic_support.R"]
    C -->|cane_supply<br/>angata| E["Source<br/>80_utils_cane_supply.R"]
    
    D -->|Calculate 6 KPIs| F["Save<br/>kpi_summary_tables_*.rds"]
    E -->|Calculate 4 KPIs| F
    
    F -->|Report rendering| G{"Which Report?"}
    
    G -->|agronomic_support| H["90_CI_report_with_kpis<br/>_agronomic_support.Rmd"]
    G -->|cane_supply| I["91_CI_report_with_kpis<br/>_cane_supply.Rmd"]
    
    H -->|Word output| J["SmartCane_Report<br/>_agronomic_support_*.docx"]
    I -->|Word output| K["SmartCane_Report<br/>_cane_supply_*.docx"]
```

---

## Switching Client Type for a Project

**Scenario**: Angata (currently cane_supply) wants to switch to agronomic_support for experimental advisory.

**Steps**:
1. Edit `r_app/parameters_project.R`:
   ```r
   CLIENT_TYPE_MAP <- list(
     ...
     "angata" = "agronomic_support"  # Changed from "cane_supply"
   )
   ```
2. Ensure `harvest.xlsx` is still in `Data/` (Stage 20 may still need it for grouping, even though agronomic_support doesn't require it)
3. Re-run Stage 80:
   ```powershell
   & "C:\Program Files\R\R-4.4.3\bin\x64\Rscript.exe" r_app/80_calculate_kpis.R 2026-02-19 angata 7
   ```
4. Re-render report (will now use Script 90 instead of 91)
   ```powershell
   & "C:\Program Files\R\R-4.4.3\bin\x64\Rscript.exe" -e `
     "rmarkdown::render('r_app/90_CI_report_with_kpis_agronomic_support.Rmd', ...)"
   ```

---

## Next Steps

- See [ARCHITECTURE_DATA_FLOW.md](ARCHITECTURE_DATA_FLOW.md) for stage-by-stage transformation details
- See [SOBIT_DEPLOYMENT.md](SOBIT_DEPLOYMENT.md) to understand how client type affects job queue routing
- See [DEV_LAPTOP_EXECUTION.md](DEV_LAPTOP_EXECUTION.md) for manual execution of client-type-specific reports
