# Demand API Reference

Complete API reference for the LocalGreenChain Demand Forecasting system.

## Overview

The Demand API enables demand-driven agriculture by:
- Capturing consumer preferences
- Aggregating regional demand signals
- Generating planting recommendations
- Matching supply with demand

---

## Consumer Preferences

### Register Preferences

```http
POST /api/demand/preferences
Content-Type: application/json

{
  "consumerId": "consumer-123",

  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "maxDeliveryRadiusKm": 25,
    "city": "Brooklyn",
    "region": "New York"
  },

  "dietaryType": ["vegetarian"],
  "allergies": ["peanuts"],
  "dislikes": ["cilantro"],

  "preferredCategories": [
    "leafy_greens",
    "herbs",
    "nightshades"
  ],

  "preferredItems": [
    {
      "produceType": "tomato",
      "category": "nightshades",
      "priority": "must_have",
      "weeklyQuantity": 2,
      "unit": "kg",
      "seasonalOnly": true
    },
    {
      "produceType": "basil",
      "category": "herbs",
      "priority": "preferred",
      "weeklyQuantity": 0.1
    }
  ],

  "certificationPreferences": ["organic", "local"],
  "freshnessImportance": 5,
  "priceImportance": 3,
  "sustainabilityImportance": 5,

  "deliveryPreferences": {
    "method": ["home_delivery", "farmers_market"],
    "frequency": "weekly",
    "preferredDays": ["saturday"]
  },

  "householdSize": 4,
  "weeklyBudget": 75,
  "currency": "USD"
}
```

Response:

```json
{
  "success": true,
  "data": {
    "consumerId": "consumer-123",
    "createdAt": "2024-06-01T10:00:00Z",
    "updatedAt": "2024-06-01T10:00:00Z"
  }
}
```

### Get Preferences

```http
GET /api/demand/preferences/{consumerId}
```

### Update Preferences

```http
PUT /api/demand/preferences/{consumerId}
Content-Type: application/json

{
  "preferredItems": [...]
}
```

---

## Demand Signals

### Generate Demand Signal

Aggregate demand for a region:

```http
POST /api/demand/signal
Content-Type: application/json

{
  "centerLat": 40.7128,
  "centerLon": -74.0060,
  "radiusKm": 25,
  "regionName": "Brooklyn",
  "season": "summer"
}
```

Response:

```json
{
  "success": true,
  "data": {
    "id": "demand-abc123",
    "timestamp": "2024-06-01T10:00:00Z",

    "region": {
      "centerLat": 40.7128,
      "centerLon": -74.0060,
      "radiusKm": 25,
      "name": "Brooklyn"
    },

    "periodStart": "2024-06-01T00:00:00Z",
    "periodEnd": "2024-06-08T00:00:00Z",
    "seasonalPeriod": "summer",

    "demandItems": [
      {
        "produceType": "tomato",
        "category": "nightshades",
        "weeklyDemandKg": 180,
        "monthlyDemandKg": 720,
        "consumerCount": 95,
        "aggregatePriority": 8,
        "urgency": "this_week",
        "preferredCertifications": ["organic"],
        "averageWillingPrice": 4.50,
        "priceUnit": "per_kg",
        "inSeason": true,
        "matchedSupply": 60,
        "matchedGrowers": 5,
        "gapKg": 120
      }
    ],

    "totalConsumers": 150,
    "totalWeeklyDemandKg": 450,
    "confidenceLevel": 85,
    "currentSupplyKg": 180,
    "supplyGapKg": 270,
    "supplyStatus": "shortage"
  }
}
```

### Get Demand Signal

```http
GET /api/demand/signal/{signalId}
```

### Query Demand Signals

```http
GET /api/demand/signal?lat=40.7128&lon=-74.0060&radius=50&season=summer
```

---

## Planting Recommendations

### Get Recommendations

```http
GET /api/demand/recommendations
  ?growerId=grower-123
  &lat=40.7128
  &lon=-74.0060
  &deliveryRadiusKm=50
  &availableSpaceSqm=500
  &season=summer
```

Response:

```json
{
  "success": true,
  "data": {
    "recommendations": [
      {
        "id": "rec-abc123",
        "timestamp": "2024-06-01T10:00:00Z",
        "growerId": "grower-123",

        "produceType": "tomato",
        "variety": null,
        "category": "nightshades",

        "recommendedQuantity": 200,
        "quantityUnit": "sqm",
        "expectedYieldKg": 1600,
        "yieldConfidence": 75,

        "plantByDate": "2024-06-05T00:00:00Z",
        "expectedHarvestStart": "2024-08-15T00:00:00Z",
        "expectedHarvestEnd": "2024-09-05T00:00:00Z",
        "growingDays": 80,

        "projectedDemandKg": 480,
        "projectedPricePerKg": 4.50,
        "projectedRevenue": 7200,
        "marketConfidence": 85,

        "riskFactors": [
          {
            "type": "weather",
            "severity": "medium",
            "description": "Single season crop with weather sensitivity",
            "mitigationSuggestion": "Consider greenhouse growing"
          }
        ],
        "overallRisk": "medium",

        "demandSignalIds": ["demand-abc123"],
        "explanation": "Based on 1 demand signal showing 120kg weekly gap..."
      }
    ]
  }
}
```

---

## Demand Forecasts

### Get Forecast

```http
GET /api/demand/forecast
  ?region=Brooklyn
  &weeks=12
```

Response:

```json
{
  "success": true,
  "data": {
    "id": "forecast-abc123",
    "generatedAt": "2024-06-01T10:00:00Z",
    "region": "Brooklyn",

    "forecastPeriod": {
      "start": "2024-06-01T00:00:00Z",
      "end": "2024-08-24T00:00:00Z"
    },

    "forecasts": [
      {
        "produceType": "tomato",
        "category": "nightshades",
        "predictedDemandKg": 2400,
        "confidenceInterval": {
          "low": 1680,
          "high": 3120
        },
        "confidence": 75,
        "trend": "increasing",
        "trendStrength": 65,
        "seasonalFactor": 1.2,
        "predictedPricePerKg": 4.50,
        "factors": [
          {
            "name": "Seasonal adjustment",
            "type": "seasonal",
            "impact": 20,
            "description": "In season - higher demand expected"
          }
        ]
      }
    ],

    "modelVersion": "1.0.0",
    "dataPointsUsed": 45,
    "lastTrainingDate": "2024-06-01T00:00:00Z"
  }
}
```

---

## Supply Commitments

### Register Supply

```http
POST /api/demand/supply
Content-Type: application/json

{
  "growerId": "grower-123",
  "produceType": "tomato",
  "variety": "Cherokee Purple",

  "committedQuantityKg": 400,
  "availableFrom": "2024-08-01T00:00:00Z",
  "availableUntil": "2024-09-30T00:00:00Z",

  "pricePerKg": 4.50,
  "currency": "USD",
  "minimumOrderKg": 2,
  "bulkDiscountThreshold": 10,
  "bulkDiscountPercent": 10,

  "certifications": ["organic"],
  "freshnessGuaranteeHours": 24,

  "deliveryRadiusKm": 50,
  "deliveryMethods": ["grower_delivery", "farmers_market"]
}
```

Response:

```json
{
  "success": true,
  "data": {
    "id": "supply-abc123",
    "status": "available",
    "remainingKg": 400
  }
}
```

### Get Supply Commitment

```http
GET /api/demand/supply/{supplyId}
```

### Update Supply

```http
PUT /api/demand/supply/{supplyId}
Content-Type: application/json

{
  "remainingKg": 350,
  "status": "partially_committed"
}
```

---

## Market Matching

### Create Match

```http
POST /api/demand/match
Content-Type: application/json

{
  "demandSignalId": "demand-abc123",
  "supplyCommitmentId": "supply-abc123",
  "consumerId": "consumer-123",
  "growerId": "grower-123",

  "produceType": "tomato",
  "matchedQuantityKg": 2,

  "agreedPricePerKg": 4.50,
  "totalPrice": 9.00,
  "currency": "USD",

  "deliveryDate": "2024-08-03T00:00:00Z",
  "deliveryMethod": "home_delivery",
  "deliveryLocation": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "address": "123 Main St, Brooklyn, NY"
  }
}
```

Response:

```json
{
  "success": true,
  "data": {
    "id": "match-abc123",
    "status": "pending"
  }
}
```

### Update Match Status

```http
PUT /api/demand/match/{matchId}
Content-Type: application/json

{
  "status": "confirmed"
}
```

---

## Enums

### Priority Levels

```typescript
type Priority = 'must_have' | 'preferred' | 'nice_to_have' | 'occasional';
```

### Produce Categories

```typescript
type ProduceCategory =
  | 'leafy_greens' | 'root_vegetables' | 'nightshades'
  | 'brassicas' | 'alliums' | 'legumes' | 'squash'
  | 'herbs' | 'microgreens' | 'sprouts' | 'mushrooms'
  | 'fruits' | 'berries' | 'citrus' | 'tree_fruits'
  | 'melons' | 'edible_flowers';
```

### Urgency Levels

```typescript
type Urgency = 'immediate' | 'this_week' | 'this_month' | 'next_season';
```

### Supply Status

```typescript
type SupplyStatus = 'surplus' | 'balanced' | 'shortage' | 'critical';
```

### Match Status

```typescript
type MatchStatus = 'pending' | 'confirmed' | 'in_transit' | 'delivered' | 'completed' | 'cancelled';
```
