# AI Insights Service

## Overview

The **AI Insights Service** provides intelligent, actionable recommendations to bakery operators by analyzing patterns across inventory, production, procurement, and sales data. It acts as a virtual operations consultant, proactively identifying opportunities for cost savings, waste reduction, and operational improvements. This service transforms raw data into business intelligence that drives profitability.

## Key Features

### Intelligent Recommendations
- **Inventory Optimization** - Smart reorder point suggestions and stock level adjustments
- **Production Planning** - Optimal batch size and scheduling recommendations
- **Procurement Suggestions** - Best supplier selection and order timing advice
- **Sales Opportunities** - Identify trending products and underperforming items
- **Cost Reduction** - Find areas to reduce waste and lower operational costs
- **Quality Improvements** - Detect patterns affecting product quality

### Unified Insight Management
- **Centralized Storage** - All AI-generated insights in one place
- **Confidence Scoring** - Standardized 0-100% confidence calculation across insight types
- **Impact Estimation** - Business value quantification for recommendations
- **Feedback Loop** - Closed-loop learning from applied insights
- **Cross-Service Intelligence** - Correlation detection between insights from different services

## Features

### Core Capabilities

1. **Insight Aggregation**
   - Collect insights from Forecasting, Procurement, Production, and Sales services
   - Categorize and prioritize recommendations
   - Filter by confidence, category, priority, and actionability

2. **Confidence Calculation**
   - Multi-factor scoring: data quality, model performance, sample size, recency, historical accuracy
   - Insight-type specific adjustments
   - Specialized calculations for forecasting and optimization insights

3. **Impact Estimation**
   - Cost savings quantification
   - Revenue increase projections
   - Waste reduction calculations
   - Efficiency gain measurements
   - Quality improvement tracking

4. **Feedback & Learning**
   - Track application outcomes
   - Compare expected vs. actual impact
   - Calculate success rates
   - Enable model improvement

5. **Orchestration Integration**
   - Pre-orchestration insight gathering
   - Actionable insight filtering
   - Categorized recommendations for workflow phases

## Architecture

### Database Models

- **AIInsight**: Core insights table with classification, confidence, impact metrics
- **InsightFeedback**: Feedback tracking for closed-loop learning
- **InsightCorrelation**: Cross-service insight relationships

### API Endpoints

```
POST   /api/v1/ai-insights/tenants/{tenant_id}/insights
GET    /api/v1/ai-insights/tenants/{tenant_id}/insights
GET    /api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}
PATCH  /api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}
DELETE /api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}

GET    /api/v1/ai-insights/tenants/{tenant_id}/insights/orchestration-ready
GET    /api/v1/ai-insights/tenants/{tenant_id}/insights/metrics/summary
POST   /api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}/apply
POST   /api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}/feedback
POST   /api/v1/ai-insights/tenants/{tenant_id}/insights/refresh
GET    /api/v1/ai-insights/tenants/{tenant_id}/insights/export
```

## Installation

### Prerequisites

- Python 3.11+
- PostgreSQL 14+
- Redis 6+

### Setup

1. **Clone and navigate**:
   ```bash
   cd services/ai_insights
   ```

2. **Create virtual environment**:
   ```bash
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
   ```

3. **Install dependencies**:
   ```bash
   pip install -r requirements.txt
   ```

4. **Configure environment**:
   ```bash
   cp .env.example .env
   # Edit .env with your configuration
   ```

5. **Run migrations**:
   ```bash
   alembic upgrade head
   ```

6. **Start the service**:
   ```bash
   uvicorn app.main:app --reload
   ```

The service will be available at `http://localhost:8000`.

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | Required |
| `REDIS_URL` | Redis connection string | Required |
| `FORECASTING_SERVICE_URL` | Forecasting service URL | `http://forecasting-service:8000` |
| `PROCUREMENT_SERVICE_URL` | Procurement service URL | `http://procurement-service:8000` |
| `PRODUCTION_SERVICE_URL` | Production service URL | `http://production-service:8000` |
| `MIN_CONFIDENCE_THRESHOLD` | Minimum confidence for insights | `60` |
| `DEFAULT_INSIGHT_TTL_DAYS` | Days before insights expire | `7` |

## Usage Examples

### Creating an Insight

```python
import httpx

insight_data = {
    "tenant_id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "recommendation",
    "priority": "high",
    "category": "procurement",
    "title": "Flour Price Increase Expected",
    "description": "Price predicted to rise 8% in next week. Consider ordering now.",
    "impact_type": "cost_savings",
    "impact_value": 120.50,
    "impact_unit": "euros",
    "confidence": 85,
    "metrics_json": {
        "current_price": 1.20,
        "predicted_price": 1.30,
        "order_quantity": 1000
    },
    "actionable": True,
    "recommendation_actions": [
        {"label": "Order Now", "action": "create_purchase_order"},
        {"label": "Review", "action": "review_forecast"}
    ],
    "source_service": "procurement",
    "source_data_id": "price_forecast_123"
}

response = httpx.post(
    "http://localhost:8000/api/v1/ai-insights/tenants/550e8400-e29b-41d4-a716-446655440000/insights",
    json=insight_data
)
print(response.json())
```

### Querying Insights

```python
# Get high-confidence actionable insights
response = httpx.get(
    "http://localhost:8000/api/v1/ai-insights/tenants/550e8400-e29b-41d4-a716-446655440000/insights",
    params={
        "actionable_only": True,
        "min_confidence": 80,
        "priority": "high",
        "page": 1,
        "page_size": 20
    }
)
insights = response.json()
```

### Recording Feedback

```python
feedback_data = {
    "insight_id": "insight-uuid",
    "action_taken": "create_purchase_order",
    "success": True,
    "expected_impact_value": 120.50,
    "actual_impact_value": 115.30,
    "result_data": {
        "order_id": "PO-12345",
        "actual_savings": 115.30
    },
    "applied_by": "user@example.com"
}

response = httpx.post(
    f"http://localhost:8000/api/v1/ai-insights/tenants/{tenant_id}/insights/{insight_id}/feedback",
    json=feedback_data
)
```

## Development

### Running Tests

```bash
pytest
```

### Code Quality

```bash
# Format code
black app/

# Lint
flake8 app/

# Type checking
mypy app/
```

### Creating a Migration

```bash
alembic revision --autogenerate -m "Description of changes"
alembic upgrade head
```

## Insight Types

- **optimization**: Process improvements with measurable gains
- **alert**: Warnings requiring attention
- **prediction**: Future forecasts with confidence intervals
- **recommendation**: Suggested actions with estimated impact
- **insight**: General data-driven observations
- **anomaly**: Unusual patterns detected in data

## Priority Levels

- **critical**: Immediate action required (e.g., stockout risk)
- **high**: Action recommended soon (e.g., price opportunity)
- **medium**: Consider acting (e.g., efficiency improvement)
- **low**: Informational (e.g., pattern observation)

## Categories

- **forecasting**: Demand predictions and patterns
- **inventory**: Stock management and optimization
- **production**: Manufacturing efficiency and scheduling
- **procurement**: Purchasing and supplier management
- **customer**: Customer behavior and satisfaction
- **cost**: Cost optimization opportunities
- **quality**: Quality improvements
- **efficiency**: Process efficiency gains

## Integration with Other Services

### Forecasting Service

- Receives forecast accuracy insights
- Pattern detection alerts
- Demand anomaly notifications

### Procurement Service

- Price forecast recommendations
- Supplier performance alerts
- Safety stock optimization

### Production Service

- Yield prediction insights
- Schedule optimization recommendations
- Equipment maintenance alerts

### Orchestrator Service

- Pre-orchestration insight gathering
- Actionable recommendation filtering
- Feedback recording for applied insights

## API Documentation

Once the service is running, interactive API documentation is available at:

- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`

## Monitoring

### Health Check

```bash
curl http://localhost:8000/health
```

### Metrics Endpoint

```bash
curl http://localhost:8000/api/v1/ai-insights/tenants/{tenant_id}/insights/metrics/summary
```

## License

Copyright © 2025 Bakery IA. All rights reserved.

## Support

For issues and questions, please contact the development team or create an issue in the project repository.
