# LocalGreenChain Transparency System

## Overview

The LocalGreenChain Transparency System provides complete visibility into platform operations, ensuring trust, accountability, and compliance for all stakeholders - growers, consumers, certifiers, and regulators.

## Key Features

### 1. Immutable Audit Logging

Every action on the platform is recorded in an immutable, cryptographically-linked audit log.

**Tracked Actions:**
- Plant registrations and clones
- Transport events and handoffs
- Demand signals and supply commitments
- Farm operations and batch management
- System events and configuration changes
- API calls and user activities

**API Endpoints:**
```
GET  /api/transparency/audit          - Query audit entries
POST /api/transparency/audit          - Log custom audit entry
```

**Query Parameters:**
- `startDate`, `endDate` - Date range filter
- `actions` - Filter by action types (comma-separated)
- `categories` - Filter by categories
- `severities` - Filter by severity levels
- `actorId` - Filter by actor
- `resourceType`, `resourceId` - Filter by resource
- `format` - Output format (json, csv, summary)

### 2. Real-Time Event Stream

Server-Sent Events (SSE) for real-time notifications and webhook support for integrations.

**Event Types:**
- `plant.*` - Plant lifecycle events
- `transport.*` - Transport events
- `demand.*` - Demand and supply events
- `farm.*` - Farm operation events
- `agent.*` - Agent task and alert events
- `blockchain.*` - Blockchain events
- `system.*` - System health events
- `audit.*` - Audit events

**API Endpoints:**
```
GET  /api/transparency/events         - Get recent events
GET  /api/transparency/events?stream=true  - SSE connection
POST /api/transparency/events         - Emit custom event
```

**Webhook Management:**
```
GET    /api/transparency/webhooks     - List webhooks
POST   /api/transparency/webhooks     - Register webhook
DELETE /api/transparency/webhooks     - Remove webhook
PATCH  /api/transparency/webhooks     - Update webhook
```

### 3. Transparency Dashboard

Comprehensive metrics aggregation across all platform components.

**API Endpoint:**
```
GET /api/transparency/dashboard
```

**Returns:**
- System health status
- Plant registry metrics
- Transport statistics
- Environmental impact metrics
- Blockchain status
- Agent activity
- Active alerts

**Public Portal:**
Visit `/transparency` for the public-facing dashboard.

### 4. Digital Signatures

Cryptographic verification for transport handoffs, ownership transfers, and certifications.

**Features:**
- ECDSA/RSA key pair generation
- Identity registration and verification
- Single and multi-party signatures
- Transport handoff signing
- Certificate of Authenticity generation

**API Endpoints:**
```
GET  /api/transparency/signatures          - Get signature stats
POST /api/transparency/signatures          - Various signature actions
GET  /api/transparency/certificate/[plantId] - Generate plant certificate
```

**Signature Actions:**
- `register_identity` - Register a new signing identity
- `generate_keypair` - Generate a key pair
- `sign` - Create a signature
- `verify_data` - Verify a signature
- `transport_handoff` - Sign transport handoff

### 5. Data Export & Reporting

Export transparency data in multiple formats for compliance and analysis.

**API Endpoint:**
```
GET /api/transparency/export
```

**Export Types:**
- `dashboard` - Dashboard metrics
- `audit` - Audit log entries
- `events` - Event stream data
- `plants` - Plant registry
- `transport` - Transport history
- `signatures` - Digital signatures
- `full` - Complete export

**Formats:**
- `json` - Structured JSON data
- `csv` - Spreadsheet-compatible
- `summary` - Human-readable text

**Report Generation:**
```
GET /api/transparency/report
```

### 6. System Health Monitoring

Real-time health status of all platform components.

**API Endpoint:**
```
GET /api/transparency/health
```

**Components Monitored:**
- Blockchain storage
- Agent system
- API layer
- Data storage

## Usage Examples

### Query Audit Log
```javascript
// Get last 24 hours of plant registrations
const response = await fetch('/api/transparency/audit?' + new URLSearchParams({
  startDate: new Date(Date.now() - 86400000).toISOString(),
  actions: 'PLANT_REGISTER,PLANT_CLONE',
  format: 'json'
}));
const data = await response.json();
```

### Subscribe to Events (SSE)
```javascript
const eventSource = new EventSource('/api/transparency/events?stream=true');

eventSource.addEventListener('plant.registered', (event) => {
  const data = JSON.parse(event.data);
  console.log('New plant registered:', data);
});

eventSource.addEventListener('transport.completed', (event) => {
  const data = JSON.parse(event.data);
  console.log('Transport completed:', data);
});
```

### Register a Webhook
```javascript
const response = await fetch('/api/transparency/webhooks', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    url: 'https://your-server.com/webhook',
    types: ['plant.registered', 'transport.completed']
  })
});
const { data } = await response.json();
// Store data.secret securely for verifying webhooks
```

### Generate Plant Certificate
```javascript
const response = await fetch('/api/transparency/certificate/plant_123?format=json');
const { data } = await response.json();
console.log('Certificate:', data.certificate);
console.log('Verification:', data.verification);
```

### Sign Transport Handoff
```javascript
const response = await fetch('/api/transparency/signatures', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    action: 'transport_handoff',
    plantId: 'plant_123',
    fromParty: 'grower_001',
    toParty: 'transporter_001',
    location: { lat: 40.7128, lng: -74.0060 },
    privateKey: '-----BEGIN PRIVATE KEY-----...'
  })
});
```

### Export Data
```javascript
// Export audit log as CSV
window.location.href = '/api/transparency/export?type=audit&format=csv';

// Generate full report
const response = await fetch('/api/transparency/report?format=summary');
const report = await response.text();
```

## Security Considerations

1. **Audit Integrity**: Audit entries are cryptographically linked; tampering is detectable
2. **Signature Security**: Private keys are never stored on the server
3. **Webhook Security**: Webhooks include HMAC signatures for verification
4. **Data Privacy**: Personal data can be anonymized in exports
5. **Rate Limiting**: Consider implementing rate limiting for production

## Integration with Existing Systems

The transparency system integrates with:
- **PlantChain**: Plant registration events are automatically logged
- **TransportChain**: Transport events trigger audit entries and notifications
- **AgentOrchestrator**: Agent activities are tracked and monitored
- **DemandForecaster**: Demand signals are logged for transparency

## Best Practices

1. **Subscribe to Critical Events**: Set up webhooks for important events
2. **Regular Exports**: Schedule regular data exports for compliance
3. **Monitor Health**: Check `/api/transparency/health` in monitoring systems
4. **Verify Certificates**: Always verify plant certificates before transactions
5. **Sign Handoffs**: Use digital signatures for all transport handoffs

## Public Transparency Portal

Access the public transparency portal at `/transparency` to view:
- Real-time system health
- Platform metrics
- Environmental impact
- Blockchain status
- Active alerts

The portal auto-refreshes every 30 seconds and provides export links for all data.
