# Kitchen Intelligence Suite — Implementation Plan

_Comprises **Recipe Collector**, **Digital Pantry**, and **Meal Planner** working together to auto-generate shopping lists and optimise household grocery workflows._

---

## 1. Product Goals
1. Centralise recipe collection (web clipper, manual entry, photo OCR).
2. Provide frictionless meal-planning on a calendar UI.
3. Maintain a live Digital Pantry (inventory) sourced from shopping lists & expenses.
4. Produce consolidated shopping lists by comparing planned meals vs pantry stock.

## 2. High-Level Architecture
```
Browser Clipper / Mobile App
        ↓ (REST / gRPC)
Backend  (FastAPI)  ─► Recipe ↔ Ingredient ↔ Pantry Stock
                         │
                         └─► MealPlanCalendar ▷ Auto ShoppingList ▷ Existing List system
```
- **Backend** utilises existing FastAPI + Postgres; re-use OCR, list & expense models where possible.
- **Services**: recipe parser, nutrition API integration, suggestion engine.

## 3. Database Design
| Model | Fields | Notes |
|-------|--------|-------|
| `Recipe` | `id`, `group_id`, `title`, `source_url`, `image_url`, `instructions_md`, `created_by_id`, timestamps | Markdown instructions for rich text |
| `RecipeIngredient` | `id`, `recipe_id`, `name`, `quantity`, `unit`, `raw_text` | Denormalised for simplicity |
| `RecipeTag` | `recipe_id`, `tag` | Simple tag list |
| `PantryItem` | `id`, `group_id`, `name`, `quantity`, `unit`, `expires_at`, `updated_at` | Synced from expenses & manual edits |
| `MealPlan` | `id`, `group_id`, `date`, `recipe_id`, `servings`, `position` | Multiple recipes per day possible |

*Indices on (`group_id`, `date`) for fast calendar queries.*

## 4. Backend API Surface (v1)
```
# Recipes
POST   /recipes/clip           → create from URL (async parse)
POST   /recipes/ocr            → upload photo; returns draft recipe
POST   /recipes                → manual create
GET    /recipes?tag=&query=    → search & filter
GET    /recipes/{id}           → detail
PUT    /recipes/{id}           → update
DELETE /recipes/{id}

# Meal Planner
GET    /mealplan?start=&end=   → range fetch
POST   /mealplan               → add recipe to date
DELETE /mealplan/{id}

# Pantry
GET    /pantry                 → list stock
PUT    /pantry/{id}            → adjust qty / mark consumed

# Magic Button
POST   /shopping-list/generate?start=2025-01-01&end=2025-01-07
      → returns consolidated list; also persists to existing List entity
```

## 5. Key Services
1. **Recipe Parser Service**  
   - Uses `recipe-scrapers` library + custom fallbacks.  
   - Normalises units (ml, g, cups) via `quantulum3`.
2. **Photo OCR Pipeline**  
   - Re-use existing Tesseract / Google Vision integration.  
   - Heuristic line-by-line ingredient detection.
3. **Shopping List Generator**  
   - Inputs: planned recipes, servings, pantry items.  
   - Algorithm:
     ```python
     needed = Counter()
     for plan in plans:
         for ing in plan.ingredients:
             qty = convert_to_base_unit(ing.quantity, ing.unit)
             needed[ing.name] += qty
     for stock in pantry:
         needed[stock.name] -= stock.quantity_base
     final = {name: qty for name, qty in needed.items() if qty > 0}
     ```
   - Outputs `List` + `Item` rows; marks them `is_auto_generated=True`.
4. **Pantry Synchroniser**  
   - After expense settlement or list completion, increment `PantryItem` quantities.

## 6. Front-End Work (Vue 3)
### 6.1 Recipe Collector UI
- `RecipeGallery.vue` (masonry grid w/ tag filters)
- `RecipeDetailSheet.vue` (view & edit)
- `RecipeImportDialog.vue` (URL / photo upload)
- `TagSelector.vue`

### 6.2 Meal Planner UI
- `MealPlannerCalendar.vue` (drag-n-drop, week & month views)
- `MealPlannerSidebar.vue` (recipe search & quick add)
- `MealPlanDayCard.vue`

### 6.3 Pantry UI
- `PantryList.vue` (sortable table; colour-coded expirations)

### 6.4 Stores
- `useRecipeStore`, `useMealPlanStore`, `usePantryStore` with optimistic updates.

## 7. Browser Clipper Extension
- MV3 Chrome/Firefox extension; minimal popup with "Save to mitlist".  
- Sends URL + selected text/image to `/recipes/clip`.  
- Auth via existing JWT; allow device pairing QR for quick login.

## 8. Integration with Existing Lists Module
- Generated shopping list saved as hidden list (`type=generated`, `source="meal-plan"`).
- Users can tweak items before marking list complete.

## 9. Background Jobs & Workers
- Async parsing & OCR handled by Celery.
- Nightly job to decrement pantry stock based on MealPlan (consume ingredients on the day).

## 10. Permissions & Roles
- Same as lists/expenses: group-scoped; only members can modify; owners can delete.

## 11. Migration Steps
1. Alembic migrations for new tables.  
2. Back-fill pantry from last 90 days expenses.  
3. Deploy backend behind feature flag.  
4. Release Recipe Collector UI (alpha) → gather feedback.  
5. Ship Meal Planner + Magic Button.  
6. Turn on automatic pantry sync.

## 12. Analytics & Success Metrics
- Weekly Active Meal Planners.  
- Avg. recipes saved per user.  
- % shopping lists auto-generated.  
- Reduction in grocery budget (optional survey).

## 13. Timeline Estimate
| Milestone | Duration |
|-----------|----------|
| DB & API scaffold (recipes, pantry) | 3 w |
| Clipper extension MVP | 2 w |
| OCR import & parser refinements | 2 w |
| Meal Planner calendar + Shopping List generator | 3 w |
| Pantry sync & consumption logic | 2 w |
| UX polish, QA, beta rollout | 2 w |

_Total ≈ 12 weeks with 2 engineers (1 BE, 1 FE) + part-time designer._

## 14. Integration with Existing Codebase

### 14.1 Backend Reuse & Patterns
- **CRUD Base**: Implement `crud/recipe.py`, `crud/pantry.py`, `crud/meal_plan.py` inheriting from existing `CRUDBase` (see `crud/list.py`).
- **Dependency Injection**: Continue using `Depends(get_current_user)`, `Depends(get_db)` per existing routers.
- **Path Organization**: Place new endpoints in `app/api/v1/endpoints/recipes.py`, `mealplanner.py`, `pantry.py`; include them in `api_router_v1` with appropriate prefixes.
- **Transactions Strategy**: Follow rule `fastapi-db-strategy` ([[fetch_rules]]) for wrap-in-transaction per request or unit-of-work pattern.
- **Existing List & Item models**: Shopping list generator will directly create `List` and `Item` rows to avoid duplicating list logic. Flag items with `is_generated` boolean (schema change in migrations).
- **Expense Hooks**: Use SQLAlchemy event listener on `Expense` insert to update `PantryItem` quantities.
- **Job Scheduling**: Add Celery beat tasks next to `jobs/recurring_expenses.py` (e.g., `jobs/pantry_sync.py`).

### 14.2 Front-End Alignment
- **Services**: Add `recipeService.ts`, `mealPlanService.ts`, `pantryService.ts` in `src/services`. Pattern after `expenseService.ts` with generic `api.ts` wrapper.
- **Pinia Stores**: `recipeStore.ts`, `mealPlanStore.ts`, `pantryStore.ts` mirroring structure of `choreStore.ts` (actions for fetch, create, delete, optimistic updates helper).
- **Composable Utilities**: `useMealPlanner.ts` providing drag-and-drop helpers, reusing `useOptimisticUpdates` and `useOfflineSync`.
- **Routing**:
  ```ts
  { path: '/recipes', name: 'Recipes', component: () => import('@/pages/RecipesPage.vue') },
  { path: '/meal-plan', name: 'MealPlanner', component: () => import('@/pages/MealPlannerPage.vue') },
  { path: '/pantry', name: 'Pantry', component: () => import('@/pages/PantryPage.vue') },
  ```
  Add lazy preload helpers in `MainLayout.vue` similar to lists/expenses.
- **UI Consistency**: Use Tailwind & existing UI kit components (e.g., `ui/Tabs.vue`, `ui/Dialog.vue`).
- **Offline Strategy**: Extend `offlineQueue.ts` to support recipe and meal plan mutations.

### 14.3 Migration & Feature Flags
- Introduce boolean env flag `ENABLE_KITCHEN_SUITE`; wrap router include and `MainLayout` nav link in condition to allow gradual rollout.
- Provide data migration to back-fill pantry from recent expenses; executed once via Alembic `upgrade()` function referencing `Expense` table.

### 14.4 Testing Plan
- **Backend**: Unit tests in `tests/api/v1/endpoints/test_recipes.py`, etc., with factory fixtures for recipes & meal plans.
- **Frontend**: Vitest component tests and Playwright e2e tests (`e2e/mealplanner.spec.ts`) replicating patterns in current `lists.spec.ts`.

---

_This section guarantees the Kitchen Suite layers naturally onto our existing architecture without breaking conventions._
