# AI Insights Service - Quick Start Guide

Get the AI Insights Service running in 5 minutes.

## Prerequisites

- Python 3.11+
- PostgreSQL 14+ (running)
- Redis 6+ (running)

## Step 1: Setup Environment

```bash
cd services/ai_insights

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

## Step 2: Configure Database

```bash
# Copy environment template
cp .env.example .env

# Edit .env file
nano .env
```

**Minimum required configuration**:
```env
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/bakery_ai_insights
REDIS_URL=redis://localhost:6379/5
```

## Step 3: Create Database

```bash
# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE bakery_ai_insights;
\q
```

## Step 4: Run Migrations

```bash
# Run Alembic migrations
alembic upgrade head
```

You should see:
```
INFO  [alembic.runtime.migration] Running upgrade  -> 001, Initial schema for AI Insights Service
```

## Step 5: Start the Service

```bash
uvicorn app.main:app --reload
```

You should see:
```
INFO:     Uvicorn running on http://127.0.0.1:8000
INFO:     Application startup complete.
```

## Step 6: Verify Installation

Open browser to http://localhost:8000/docs

You should see the Swagger UI with all API endpoints.

### Test Health Endpoint

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

Expected response:
```json
{
  "status": "healthy",
  "service": "ai-insights",
  "version": "1.0.0"
}
```

## Step 7: Create Your First Insight

```bash
curl -X POST "http://localhost:8000/api/v1/ai-insights/tenants/550e8400-e29b-41d4-a716-446655440000/insights" \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "recommendation",
    "priority": "high",
    "category": "forecasting",
    "title": "Test Insight - Weekend Demand Pattern",
    "description": "Weekend sales 20% higher than weekdays",
    "impact_type": "revenue_increase",
    "impact_value": 150.00,
    "impact_unit": "euros/week",
    "confidence": 85,
    "metrics_json": {
      "weekday_avg": 45.2,
      "weekend_avg": 54.2,
      "increase_pct": 20.0
    },
    "actionable": true,
    "recommendation_actions": [
      {"label": "Increase Production", "action": "adjust_production"}
    ],
    "source_service": "forecasting"
  }'
```

## Step 8: Query Your Insights

```bash
curl "http://localhost:8000/api/v1/ai-insights/tenants/550e8400-e29b-41d4-a716-446655440000/insights?page=1&page_size=10"
```

## Common Issues

### Issue: "ModuleNotFoundError: No module named 'app'"

**Solution**: Make sure you're running from the `services/ai_insights/` directory and virtual environment is activated.

### Issue: "Connection refused" on database

**Solution**: Verify PostgreSQL is running:
```bash
# Check if PostgreSQL is running
pg_isready

# Start PostgreSQL (macOS with Homebrew)
brew services start postgresql

# Start PostgreSQL (Linux)
sudo systemctl start postgresql
```

### Issue: "Redis connection error"

**Solution**: Verify Redis is running:
```bash
# Check if Redis is running
redis-cli ping

# Should return: PONG

# Start Redis (macOS with Homebrew)
brew services start redis

# Start Redis (Linux)
sudo systemctl start redis
```

### Issue: "Alembic command not found"

**Solution**: Virtual environment not activated:
```bash
source venv/bin/activate
```

## Next Steps

1. **Explore API**: Visit http://localhost:8000/docs
2. **Read Documentation**: See `README.md` for detailed documentation
3. **Implementation Guide**: See `AI_INSIGHTS_IMPLEMENTATION_SUMMARY.md`
4. **Integration**: Start integrating with other services

## Useful Commands

```bash
# Check service status
curl http://localhost:8000/health

# Get aggregate metrics
curl "http://localhost:8000/api/v1/ai-insights/tenants/{tenant_id}/insights/metrics/summary"

# Filter high-confidence insights
curl "http://localhost:8000/api/v1/ai-insights/tenants/{tenant_id}/insights?actionable_only=true&min_confidence=80"

# Stop the service
# Press Ctrl+C in the terminal running uvicorn

# Deactivate virtual environment
deactivate
```

## Docker Quick Start (Alternative)

If you prefer Docker:

```bash
# Build image
docker build -t ai-insights .

# Run container
docker run -d \
  --name ai-insights \
  -p 8000:8000 \
  -e DATABASE_URL=postgresql+asyncpg://postgres:postgres@host.docker.internal:5432/bakery_ai_insights \
  -e REDIS_URL=redis://host.docker.internal:6379/5 \
  ai-insights

# Check logs
docker logs ai-insights

# Stop container
docker stop ai-insights
docker rm ai-insights
```

## Support

- **Documentation**: See `README.md`
- **API Docs**: http://localhost:8000/docs
- **Issues**: Create GitHub issue or contact team

---

**You're ready!** The AI Insights Service is now running and ready to accept insights from other services.
