# Material Database Pattern for Renovation Apps

This document describes the JSON-based material database pattern used in the home renovation app, which can be adapted for similar data-driven recommendation systems.

## Database Structure (`backend/data/materials.json`)

```json
{
  "materials": [
    {
      "id": "floor_001",
      "name": "复合地板",
      "category": "地面",
      "brand": "圣象",
      "model": "F-2001",
      "price_per_unit": 128.0,
      "unit": "平方米",
      "style_match": ["现代简约", "北欧风", "日式风格"],
      "description": "耐磨层压地板，适合客厅卧室",
      "supplier": "圣象地板官方旗舰店",
      "purchase_url": "https://example.com/shengxiang-f2001"
    }
  ],
  "rooms": {
    "living_room": {
      "name": "客厅",
      "areas": {
        "floor": 25.0,
        "wall": 60.0,
        "ceiling": 25.0
      },
      "required_materials": ["floor", "wall", "ceiling", "lighting"]
    }
  }
}
```

## Key Design Principles

1. **Flat material list**: All materials in one array, with `category` and `style_match` fields for filtering.
2. **Room configuration**: Separate `rooms` object defines area calculations and required material categories.
3. **Style matching**: Each material has `style_match` array; backend filters by `request.style in material["style_match"]`.
4. **Dynamic cost calculation**: Backend computes `subtotal = material["price_per_unit"] * room_area`.

## Backend Integration Pattern

```python
import json
from pathlib import Path

# Load database
materials_db = {}
try:
    data_path = Path(__file__).parent / "data" / "materials.json"
    with open(data_path, 'r', encoding='utf-8') as f:
        materials_db = json.load(f)
except Exception as e:
    print(f"Material DB load failed: {e}")
    materials_db = {"materials": [], "rooms": {}}

# Recommendation algorithm
def recommend_materials(style: str, room_type: str):
    all_materials = materials_db.get("materials", [])
    room_config = materials_db.get("rooms", {}).get(room_type)
    if not room_config:
        return []
    
    required_cats = room_config.get("required_materials", [])
    areas = room_config.get("areas", {})
    results = []
    
    for cat in required_cats:
        # Map category key to Chinese category name
        cat_map = {"floor": "地面", "wall": "墙面", "ceiling": "顶面"}
        target_category = cat_map.get(cat, cat)
        
        # Filter by category
        cat_materials = [m for m in all_materials if m.get("category") == target_category]
        # Filter by style
        style_materials = [m for m in cat_materials if style in m.get("style_match", [])]
        if not style_materials:
            style_materials = cat_materials  # Fallback to any in category
        
        if style_materials:
            material = style_materials[0]  # Select first match
            area = areas.get(cat, 0)
            subtotal = material["price_per_unit"] * area
            results.append({
                "name": material["name"],
                "brand": material.get("brand"),
                "model": material.get("model"),
                "estimated_cost": subtotal,
                "room": room_config["name"]
            })
    
    return results
```

## Frontend Display Pattern

Display as a table with: Material name, Brand/Model, Category, Room, Cost, Purchase link.

See `/home/ubuntu/projects/home-renovation-app/backend/data/materials.json` for full example.
