summaryrefslogtreecommitdiff
path: root/services/pantry_service.py
blob: 19271e585d09594a68f979a69910f2d862a378f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from models import Ingredient, MealLog
from collections import Counter


def build_pantry_context(db: Session) -> dict:
    """Return a dict with pantry state for use as AI context."""
    today = datetime.utcnow().date()
    soon = today + timedelta(days=3)

    # All ingredients
    all_ingredients = db.query(Ingredient).all()
    available = [
        {
            "name": i.name,
            "quantity": i.quantity,
            "unit": i.unit,
            "category": i.category,
            "expiry": i.expiry_date.isoformat() if i.expiry_date else None,
        }
        for i in all_ingredients
    ]

    # Expiring within 3 days
    expiring = [
        i for i in available
        if i["expiry"] and i["expiry"] <= soon.isoformat()
    ]

    # Recent meals (last 14 days)
    cutoff = datetime.utcnow() - timedelta(days=14)
    recent_meal_logs = db.query(MealLog).filter(MealLog.eaten_at >= cutoff).order_by(MealLog.eaten_at.desc()).all()
    recent_meals = [
        {
            "date": m.eaten_at.date().isoformat(),
            "meal_type": m.meal_type,
            "meal_name": m.meal_name,
        }
        for m in recent_meal_logs
    ]

    # Meal frequency (count by name)
    meal_frequency = dict(Counter(m["meal_name"] for m in recent_meals))

    return {
        "available_ingredients": available,
        "expiring_soon": expiring,
        "recent_meals": recent_meals,
        "meal_frequency": meal_frequency,
    }