# Demand Forecasting & Seasonal Planning

LocalGreenChain's demand forecasting system enables truly demand-driven agriculture by connecting consumer preferences with grower capabilities, optimizing for seasonal availability and minimal environmental impact.

## Core Philosophy

### Traditional Agriculture Problem

```
Grower decides → Plants → Harvests → Finds buyers → Surplus/shortage
     ↓              ↓         ↓           ↓              ↓
   Guesses      Fixed plan  Hope sells  Waste if not  Lost income
```

### LocalGreenChain Solution

```
Consumer signals → Aggregated demand → Grower recommendation → Matched harvest
       ↓                  ↓                    ↓                    ↓
   Preferences     Regional needs       Optimal planting      Pre-sold produce
```

## Demand Signal Flow

```
┌─────────────────────────────────────────────────────────────────────┐
│                    DEMAND SIGNAL GENERATION                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  CONSUMER PREFERENCES                                               │
│  ┌─────────────────┐                                               │
│  │ Consumer A      │──┐                                            │
│  │ - Tomatoes: 2kg │  │                                            │
│  │ - Lettuce: 1kg  │  │                                            │
│  │ - Organic only  │  │                                            │
│  └─────────────────┘  │                                            │
│  ┌─────────────────┐  │      ┌─────────────────────┐              │
│  │ Consumer B      │──┼─────→│  DEMAND AGGREGATOR  │              │
│  │ - Tomatoes: 1kg │  │      │                     │              │
│  │ - Basil: 200g   │  │      │  Region: Downtown   │              │
│  │ - Local pref    │  │      │  Radius: 25km       │              │
│  └─────────────────┘  │      │  Season: Summer     │              │
│  ┌─────────────────┐  │      │                     │              │
│  │ Consumer C...   │──┘      │  Total Consumers:   │              │
│  │                 │         │  150                │              │
│  └─────────────────┘         └──────────┬──────────┘              │
│                                         │                          │
│                                         ▼                          │
│                              ┌─────────────────────┐              │
│                              │   DEMAND SIGNAL     │              │
│                              │                     │              │
│                              │ Tomatoes: 180kg/wk  │              │
│                              │ Lettuce: 95kg/wk    │              │
│                              │ Basil: 15kg/wk      │              │
│                              │                     │              │
│                              │ Gap: 120kg tomatoes │              │
│                              │ Status: SHORTAGE    │              │
│                              └─────────────────────┘              │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

## Consumer Preferences

### Preference Structure

```typescript
interface ConsumerPreference {
  // Who
  consumerId: string;
  location: { latitude, longitude, maxDeliveryRadiusKm };

  // What they want
  preferredCategories: ['leafy_greens', 'herbs', 'nightshades'];
  preferredItems: [
    { produceType: 'tomato', priority: 'must_have', weeklyQuantity: 2 },
    { produceType: 'lettuce', priority: 'preferred', weeklyQuantity: 1 },
    { produceType: 'basil', priority: 'nice_to_have' }
  ];

  // How they want it
  certificationPreferences: ['organic', 'local'];
  deliveryPreferences: {
    method: ['home_delivery', 'farmers_market'],
    frequency: 'weekly'
  };

  // Constraints
  householdSize: 4;
  weeklyBudget: 75;
}
```

### Priority Levels

| Priority | Weight | Meaning |
|----------|--------|---------|
| must_have | 10 | Essential - will seek elsewhere if not available |
| preferred | 7 | Strong preference - important for satisfaction |
| nice_to_have | 4 | Would enjoy - not essential |
| occasional | 2 | Sometimes interested - opportunistic |

## Demand Signals

### Regional Aggregation

Demand signals aggregate preferences within a geographic region:

```typescript
interface DemandSignal {
  region: { centerLat, centerLon, radiusKm, name };
  seasonalPeriod: 'summer';

  demandItems: [
    {
      produceType: 'tomato',
      weeklyDemandKg: 180,
      consumerCount: 95,
      aggregatePriority: 8.5,
      urgency: 'this_week',
      inSeason: true,
      matchedSupply: 60,
      gapKg: 120  // Opportunity for growers!
    }
  ];

  supplyStatus: 'shortage';  // surplus | balanced | shortage | critical
}
```

### Supply Matching

The system continuously matches demand with available supply:

```
Demand: 180 kg/week tomatoes

Current Supply:
  - Grower A: 30 kg committed
  - Grower B: 20 kg committed
  - Vertical Farm X: 10 kg committed
  Total: 60 kg

Gap: 120 kg/week

→ Generate planting recommendations for growers
→ Vertical farms can respond within 6-8 weeks
→ Traditional growers plan for next season
```

## Planting Recommendations

### Recommendation Engine

```typescript
// Generate recommendations for a grower
const recommendations = forecaster.generatePlantingRecommendations(
  growerId,
  growerLat,
  growerLon,
  deliveryRadiusKm: 50,
  availableSpaceSqm: 1000,
  season: 'summer'
);

// Returns prioritized recommendations
[
  {
    produceType: 'tomato',
    recommendedQuantity: 200, // sqm
    expectedYieldKg: 1600,
    projectedDemandKg: 480, // monthly gap
    projectedPricePerKg: 4.50,
    projectedRevenue: 7200,
    riskFactors: [...],
    explanation: "Based on 3 demand signals showing 120kg weekly gap..."
  },
  {
    produceType: 'lettuce',
    recommendedQuantity: 100,
    ...
  }
]
```

### Risk Assessment

Each recommendation includes risk factors:

| Risk Type | Description | Mitigation |
|-----------|-------------|------------|
| weather | Outdoor crop vulnerable to conditions | Consider greenhouse |
| oversupply | Other growers may fill gap | Start smaller, scale up |
| market | Demand may shift | Diversify crops |
| pest | Known pest pressure in region | Preventive measures |

## Seasonal Planning

### Seasonal Crop Calendar

```
SPRING (Mar-May)
├── Lettuce ★★★★★
├── Spinach ★★★★★
├── Peas ★★★★☆
├── Radishes ★★★★☆
└── Carrots ★★★☆☆

SUMMER (Jun-Aug)
├── Tomatoes ★★★★★
├── Peppers ★★★★★
├── Cucumbers ★★★★☆
├── Basil ★★★★★
└── Beans ★★★★☆

FALL (Sep-Nov)
├── Kale ★★★★★
├── Broccoli ★★★★☆
├── Brussels Sprouts ★★★★☆
├── Squash ★★★★☆
└── Lettuce ★★★★★

WINTER (Dec-Feb)
├── Microgreens ★★★★★ (indoor)
├── Sprouts ★★★★★ (indoor)
├── Kale ★★★★☆
└── Spinach ★★★☆☆

★ = Demand strength in season
```

### Year-Round Planning with Vertical Farms

Vertical farms can produce year-round, filling seasonal gaps:

```
Traditional Supply:  ████████████░░░░░░░░░░████████████
Vertical Farm:       ████████████████████████████████████
Combined:            ████████████████████████████████████

Legend: █ = Supply available, ░ = Gap
```

## Forecasting Models

### Simple Moving Average

```typescript
// Basic forecast from historical data
const forecast = history.reduce((a, b) => a + b, 0) / history.length;
```

### Seasonal Adjustment

```typescript
// Apply seasonal multiplier
const seasonalFactor = isInSeason(produceType, currentSeason) ? 1.2 : 0.6;
const adjustedForecast = baseForecast * seasonalFactor;
```

### Trend Analysis

```typescript
// Detect growing/declining interest
const trend = (latestDemand - earliestDemand) / dataPoints;
const futureDemand = currentDemand + (trend * weeksAhead);
```

## Integration Points

### With Transport System

```typescript
// Transport events update demand fulfillment
transportChain.recordEvent({
  eventType: 'distribution',
  batchIds: ['harvest-123'],
  destinationType: 'consumer',
  // Updates matched supply in demand signals
});
```

### With Vertical Farms

```typescript
// Vertical farms can respond quickly to demand signals
const gaps = demandSignal.demandItems.filter(i => i.gapKg > 0 && i.urgency === 'this_week');

for (const gap of gaps) {
  if (canGrowInVerticalFarm(gap.produceType)) {
    // Start batch immediately
    verticalFarmController.startCropBatch(...);
  }
}
```

### With Blockchain

```typescript
// All demand signals and commitments recorded on chain
plantChain.recordDemandSignal(signal);
plantChain.recordSupplyCommitment(commitment);
plantChain.recordMarketMatch(match);
```

## Best Practices

### For Consumers

1. **Set Preferences Early**: The more lead time, the better matching
2. **Be Flexible**: Mark some items as "nice to have"
3. **Accept Seasonal Variety**: In-season produce is better and cheaper
4. **Provide Feedback**: Help improve recommendations

### For Growers

1. **Register Capacity**: Let the system know what you can grow
2. **Follow Recommendations**: Data-driven planting reduces risk
3. **Commit Early**: Pre-committed supply gets priority matching
4. **Diversify**: Grow multiple crops to balance risk

### For the System

1. **Aggregate Regionally**: Local matching reduces transport
2. **Prioritize Seasonal**: In-season crops have better yields
3. **Balance Supply**: Prevent oversupply situations
4. **Learn Continuously**: Improve forecasts from actual outcomes

## Environmental Impact

### Demand-Driven Benefits

| Metric | Traditional | Demand-Driven | Savings |
|--------|-------------|---------------|---------|
| Food Waste | 30-40% | 5-10% | 75% reduction |
| Transport Miles | 1,500 avg | < 50 local | 97% reduction |
| Unsold Produce | 20% | < 5% | 75% reduction |
| Energy (storage) | High | Minimal | 80% reduction |

### Carbon Calculation

```
Traditional Tomato (California to NYC):
  Growing: 0.5 kg CO2/kg
  Transport: 2.0 kg CO2/kg
  Storage: 0.3 kg CO2/kg
  Total: 2.8 kg CO2/kg

LocalGreenChain Tomato (local vertical farm):
  Growing: 0.3 kg CO2/kg
  Transport: 0.02 kg CO2/kg
  Storage: 0.0 kg CO2/kg
  Total: 0.32 kg CO2/kg

Savings: 89% carbon reduction
```
