# Configuration Guide

Complete guide to configuring LocalGreenChain for your environment.

## Environment Variables

### Core Settings

```bash
# Server Configuration
PORT=3001                    # HTTP port (default: 3001)
NODE_ENV=development         # development, production, test
HOST=0.0.0.0                 # Bind address

# Application
APP_NAME=LocalGreenChain     # Application name
LOG_LEVEL=info               # debug, info, warn, error
```

### Blockchain Settings

```bash
# Mining Configuration
BLOCKCHAIN_DIFFICULTY=3      # Proof-of-work difficulty (1-6)
AUTO_MINE=true               # Auto-mine new blocks

# Chain Storage
CHAIN_FILE=data/plantchain.json
TRANSPORT_FILE=data/transport.json
```

### API Keys

```bash
# Plant Identification
PLANTS_NET_API_KEY=your_key  # plants.net API for plant ID

# Geocoding
GEOCODING_PROVIDER=nominatim # nominatim, google, mapbox
GOOGLE_MAPS_API_KEY=         # If using Google
MAPBOX_TOKEN=                # If using Mapbox
```

### Privacy Settings

```bash
# Tor Integration
TOR_ENABLED=false            # Enable Tor hidden service
TOR_SOCKS_PORT=9050          # Tor SOCKS proxy port
TOR_CONTROL_PORT=9051        # Tor control port

# Location Privacy
LOCATION_PRIVACY=city        # exact, fuzzy, city, country, hidden
LOCATION_FUZZ_RADIUS_KM=5    # Radius for fuzzy locations
```

### Database Configuration

```bash
# File Storage (default)
STORAGE_TYPE=file
DATA_DIR=./data

# PostgreSQL (optional)
DATABASE_URL=postgresql://user:pass@localhost:5432/localgreenchain

# Redis Cache (optional)
REDIS_URL=redis://localhost:6379
CACHE_TTL=3600               # Cache TTL in seconds
```

### Vertical Farming

```bash
# Default Farm Settings
VF_DEFAULT_RECIPE=lettuce-butterhead
VF_ALERT_THRESHOLD=0.1       # Alert when 10% outside targets
VF_LOG_INTERVAL=300          # Environment log interval (seconds)
```

### Demand Forecasting

```bash
# Forecaster Settings
FORECAST_HORIZON_WEEKS=12    # Default forecast period
DEMAND_AGGREGATION_RADIUS=50 # Default radius in km
MIN_CONSUMERS_FOR_SIGNAL=5   # Minimum consumers for signal
```

## Configuration Files

### .env File Structure

Create `.env` in project root:

```bash
# LocalGreenChain Configuration
# Copy from .env.example and customize

#=== Server ===#
PORT=3001
NODE_ENV=development

#=== Blockchain ===#
BLOCKCHAIN_DIFFICULTY=3

#=== Privacy ===#
TOR_ENABLED=false
LOCATION_PRIVACY=city

#=== External APIs ===#
PLANTS_NET_API_KEY=

#=== Features ===#
ENABLE_TRANSPORT=true
ENABLE_DEMAND=true
ENABLE_VERTICAL_FARM=true
```

### TypeScript Configuration

`tsconfig.json` settings:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true,
    "paths": {
      "@/*": ["./*"],
      "@lib/*": ["./lib/*"],
      "@components/*": ["./components/*"]
    }
  }
}
```

### Next.js Configuration

`next.config.js` options:

```javascript
module.exports = {
  reactStrictMode: true,
  swcMinify: true,

  // API timeout
  serverRuntimeConfig: {
    apiTimeout: 30000
  },

  // Environment exposure
  publicRuntimeConfig: {
    appName: process.env.APP_NAME
  }
};
```

## Feature Toggles

Enable or disable specific features:

```bash
# Core Features
ENABLE_TRANSPORT=true        # Transport tracking
ENABLE_DEMAND=true           # Demand forecasting
ENABLE_VERTICAL_FARM=true    # Vertical farm integration
ENABLE_ENVIRONMENTAL=true    # Environmental tracking

# Privacy Features
ENABLE_TOR=false             # Tor hidden service
ENABLE_ANONYMOUS=true        # Anonymous registration

# Experimental
ENABLE_AI_FORECAST=false     # AI-powered forecasting
ENABLE_GENETICS=false        # Genetic tracking
```

## Security Settings

### Authentication

```bash
# Session Management
SESSION_SECRET=your-secret-key-here
SESSION_TTL=86400            # Session lifetime (seconds)

# Rate Limiting
RATE_LIMIT_WINDOW=60000      # Window in ms
RATE_LIMIT_MAX=100           # Max requests per window
```

### CORS Configuration

```bash
# Allowed Origins
CORS_ORIGINS=http://localhost:3000,https://yourdomain.com

# CORS Options
CORS_CREDENTIALS=true
CORS_MAX_AGE=86400
```

## Performance Tuning

### For Development

```bash
# Fast iteration
BLOCKCHAIN_DIFFICULTY=1      # Quick mining
LOG_LEVEL=debug              # Verbose logging
CACHE_TTL=0                  # No caching
```

### For Production

```bash
# Optimized performance
BLOCKCHAIN_DIFFICULTY=4      # More secure
LOG_LEVEL=warn               # Minimal logging
CACHE_TTL=3600               # 1 hour cache
NODE_ENV=production          # Production optimizations
```

## Multi-Environment Setup

### Development

`.env.development`:
```bash
PORT=3001
NODE_ENV=development
BLOCKCHAIN_DIFFICULTY=2
LOG_LEVEL=debug
```

### Staging

`.env.staging`:
```bash
PORT=3001
NODE_ENV=staging
BLOCKCHAIN_DIFFICULTY=3
LOG_LEVEL=info
DATABASE_URL=postgresql://...
```

### Production

`.env.production`:
```bash
PORT=3001
NODE_ENV=production
BLOCKCHAIN_DIFFICULTY=4
LOG_LEVEL=warn
DATABASE_URL=postgresql://...
REDIS_URL=redis://...
```

## Docker Environment

### Docker Compose Override

`docker-compose.override.yml`:

```yaml
version: '3.8'
services:
  app:
    environment:
      - PORT=3001
      - NODE_ENV=production
      - BLOCKCHAIN_DIFFICULTY=4
    volumes:
      - ./data:/app/data
```

## Validation

### Check Configuration

```bash
# Validate environment
bun run config:check

# Test configuration
bun run test:config
```

### Common Errors

| Error | Cause | Solution |
|-------|-------|----------|
| `Missing API key` | PLANTS_NET_API_KEY not set | Add key or disable feature |
| `Invalid difficulty` | Value out of range | Use 1-6 |
| `Database connection failed` | Wrong DATABASE_URL | Check credentials |

## Next Steps

- [Installation Guide](./installation.md) - Complete setup
- [Grower Guide](./grower-guide.md) - Start growing
- [Transport Guide](./transport-guide.md) - Track transport
