# Quick Start Guide - Anomaly Detection Dashboard

Get the Anomaly Detection Dashboard running in 10 minutes.

## Step 1: Copy Frontend Files (1 min)

Files are already created at:
```
frontend/src/modules/analytics/ai/anomaly/
```

The module is ready to use!

## Step 2: Database Setup (2 min)

```bash
# Apply the schema
psql -U postgres -d ic3_database -f backend/database/migrations/create_anomaly_tables.sql

# Verify tables created
psql -U postgres -d ic3_database -c "\dt ic3_anomaly*"
```

## Step 3: Backend Integration (2 min)

Edit `backend/src/app.ts` or your main server file:

```typescript
// At the top
import anomalyRoutes from './routes/anomalyDetection';

// In your app setup (after other routes)
app.use('/api/ai/anomalies', anomalyRoutes);
```

## Step 4: Frontend Integration (2 min)

Edit `frontend/src/App.tsx`:

```typescript
// Add import
import { AnomalyDetectionDashboard } from './modules/analytics/ai/anomaly';

// Add to your component routes (find where other panels are routed)
{
  id: 'anomaly-detection',
  component: AnomalyDetectionDashboard,
  label: '🔴 Anomaly Detection'
}
```

## Step 5: Add Navigation (1 min)

Edit `frontend/src/components/Sidebar.tsx`:

```typescript
// In your menu items
{
  id: 'anomaly-detection',
  name: 'Anomaly Detection',
  icon: '🔴',
  domain: 'analytics'
}
```

## Step 6: Start Both Services (1 min)

```bash
# Terminal 1: Backend
cd backend
npm start
# → http://localhost:3001

# Terminal 2: Frontend  
cd frontend
npm run dev
# → http://localhost:5173
```

## Step 7: Navigate to Dashboard (1 min)

1. Open http://localhost:5173
2. Click "Analytics" → "Anomaly Detection"
3. You should see the dashboard with empty state

## Testing It Works

### Quick Test 1: API Health
```bash
curl http://localhost:3001/api/ai/anomalies/active
# → Should return: []
```

### Quick Test 2: Metrics Endpoint
```bash
curl http://localhost:3001/api/ai/anomalies/metrics
# → Should return: { activeCount: 0, avgConfidence: 0, ... }
```

### Quick Test 3: Create Test Data
```bash
# Create a test anomaly
curl -X POST http://localhost:3001/api/ai/anomalies \
  -H "Content-Type: application/json" \
  -d '{
    "assetId": "DMA-05",
    "assetName": "Flow Meter DMA-05",
    "assetType": "flow_meter",
    "severity": 8.5,
    "confidence": 92,
    "measurement": {
      "current": 145,
      "baseline": 120,
      "deviation": 20.8,
      "unit": "m³/hr"
    }
  }'
```

## Common Issues & Fixes

### Issue: "Cannot GET /api/ai/anomalies/active"
**Fix**: Verify route is mounted in backend
```bash
# Check server logs for "Routes configured"
grep -i "routes" server.log
```

### Issue: Dashboard shows "Error Loading"
**Fix**: Check environment variable
```bash
# In frontend/.env
VITE_API_URL=http://localhost:3001
```

### Issue: Database connection error
**Fix**: Verify tables exist
```bash
psql -U postgres -d ic3_database -c "SELECT count(*) FROM ic3_anomalies;"
```

### Issue: 404 on component
**Fix**: Verify routing is correct
```typescript
// Check if domainPanels includes your component
console.log(domainPanels['anomaly-detection']);
```

## Try These Features

### 1. View Live Anomalies
- Dashboard should show KPI cards (all zeros initially)
- "Live Anomalies" tab is default view

### 2. Create an Anomaly
- Post sample data via API (see test above)
- Refresh dashboard → anomaly appears in table

### 3. Click Detail
- Click any anomaly row
- Modal shows full details with probable causes

### 4. Create Work Order
- Click "Create Work Order" button in detail modal
- Select priority and confirm
- Work order created and audit trail updated

### 5. Configure Alerts
- Go to "Configuration" tab
- Click "Add New Rule"
- Set sensor type and severity
- Click "Save"

### 6. View Sensor Health
- Still in Configuration tab
- Scroll to "Sensor Trust Engine"
- See all sensors with trust scores

### 7. View History
- Go to "History & Trends" tab
- See 30-day statistics
- Download CSV report

## Next Steps

### Populate with Real Data
Once API is working, connect real sensor data:

1. Modify `anomalyService.ts` to fetch from your sensor stream
2. Update `create_anomaly_tables.sql` FK constraints if needed
3. Run data pipeline to populate anomalies

### Customize Thresholds
```typescript
// In types.ts
export const SEVERITY_CRITICAL = 9.0;  // Adjust as needed
export const SEVERITY_HIGH = 7.0;
```

### Add Real-Time WebSocket
```typescript
// Uncomment in useAnomalyDetection.ts
const setupWebSocket = () => {
  const ws = new WebSocket(`ws://localhost:3001`);
  // ... implement handlers
};
```

### Deploy to Production
See `ANOMALY_DETECTION_IMPLEMENTATION.md` → "Deployment" section

## File Reference

| File | Purpose |
|------|---------|
| `AnomalyDetectionDashboard.tsx` | Main component |
| `AnomalyKPICards.tsx` | Metrics display |
| `AnomalyTable.tsx` | Live list |
| `AnomalyDetailPanel.tsx` | Detail modal |
| `AnomalyService.ts` | API client |
| `useAnomalyDetection.ts` | React hooks |
| `anomalyDetection.ts` | Backend routes |
| `create_anomaly_tables.sql` | Database |

## Support

- 📖 Full design: `AI_ANOMALY_DETECTION_DESIGN.md`
- 🏗️ Architecture: `ANOMALY_DETECTION_COMPONENTS.md`
- 🚀 Deploy guide: `ANOMALY_DETECTION_IMPLEMENTATION.md`
- 📊 Summary: `ANOMALY_DETECTION_SUMMARY.md`

## Success Checklist

- [ ] Database tables created
- [ ] Backend routes mounted
- [ ] Frontend component imported
- [ ] Sidebar navigation added
- [ ] Both services running
- [ ] Dashboard loads without errors
- [ ] API endpoints responding
- [ ] Can create test anomalies
- [ ] Detail modal opens
- [ ] Work order can be created
- [ ] Configuration tab works
- [ ] History tab shows data

✅ **You're ready to go!**

---

Time to setup: **~10 minutes**
Time to first anomaly visible: **~2 minutes**
