---
name: multi-market-app-config
description: Configure apps to support multiple markets (CN/US/etc) with localized data, pricing, and suppliers. Includes database schema design, environment-based switching, and cost analysis patterns.
---

# Multi-Market App Configuration

Enable your app to serve multiple geographic markets with localized:
- Material/product databases
- Pricing in local currencies
- Local supplier links
- Market-specific AI service selection

## When to Use
- Building apps serving multiple countries/regions
- Need localized material/product databases
- Want market-specific cost optimization
- User selects "expand database" over "AI dynamic generation"

## Architecture Pattern

### 1. Database Structure
Create separate JSON databases per market:
```
backend/data/
├── materials.json      # Default (CN)
├── materials_cn.json  # China
├── materials_us.json  # United States
└── materials_uk.json  # Future expansion
```

**Database schema template:**
```json
{
  "materials": [
    {
      "id": "unique_id",
      "name": "Material name",
      "category": "floor|wall|ceiling|kitchen|bathroom|lighting",
      "brand": "Brand name",
      "model": "Model/Product name",
      "price_per_unit": 0.0,
      "unit": "sq ft|gallon|piece|linear ft",
      "style_match": ["Modern", "Traditional"],
      "description": "Brief description",
      "supplier": "Supplier name",
      "purchase_url": "https://real-purchase-url"
    }
  ],
  "rooms": {
    "living_room": {
      "name": "Living Room",
      "areas": {"floor": 300.0, "wall": 600.0, "ceiling": 300.0},
      "required_materials": ["floor", "wall", "ceiling", "lighting"]
    }
  }
}
```

### 2. Environment-Based Switching
Use environment variables to select market at runtime:

```python
# backend/main.py
import os
from pathlib import Path

materials_db = {}
market = os.getenv("MARKET", "CN").upper()

if market == "US":
    data_path = Path(__file__).parent / "data" / "materials_us.json"
elif market == "CN":
    data_path = Path(__file__).parent / "data" / "materials.json"
else:
    data_path = Path(__file__).parent / "data" / "materials.json"

with open(data_path, 'r', encoding='utf-8') as f:
    materials_db = json.load(f)
```

Docker Compose configuration:
```yaml
# docker-compose.yml
services:
  backend:
    environment:
      - MARKET=CN  # CN=中国, US=北美, UK=英国
```

### 3. Smart Material Recommendation
Filter materials by style and room type:

```python
# Get materials for category
cat_materials = [m for m in all_materials if m.get('category') == target_category]

# Filter by style match
style_materials = [m for m in cat_materials if request.style in m.get('style_match', [])]
if not style_materials:
    style_materials = cat_materials  # Fallback to all

# Return top N options (2-3 per category)
max_items = min(3, len(style_materials))
selected_materials = style_materials[:max_items]
```

### 4. Cost Analysis Pattern
Compare AI services for cost optimization:

| Service | Cost/Image | Speed | Quality | Use Case |
|---------|------------|------|--------|---------|
| DALL-E 3 | $0.040 | Slow | ⭐⭐⭐⭐⭐ | Premium users |
| Stability AI | $0.003 | Medium | ⭐⭐⭐⭐ | Default choice |
| Leonardo AI | $0.0015 | Fast | ⭐⭐⭐⭐ | Cost optimization |
| Local SDXL | $0.0001 | Slow | ⭐⭐⭐ | Self-hosted |

**Annual cost estimate (1000 images/month):**
- DALL-E 3: $480/year
- Stability AI: $36/year ✅
- Leonardo AI: $18/year
- Local: $1/year

## Workflow: Expanding Material Database

### Step 1: Add Materials to JSON
Add 2-3 brands per category with real supplier URLs:
```json
{
  "id": "us_floor_004",
  "name": "Engineered Hardwood",
  "brand": "Mohawk",
  "model": "RevWood",
  "price_per_unit": 4.29,
  "unit": "sq ft",
  "style_match": ["Modern", "Traditional"],
  "supplier": "Home Depot",
  "purchase_url": "https://www.homedepot.com/p/mohawk-revwood"
}
```

### Step 2: Update Backend Logic
Modify recommendation to return multiple options:
```python
# Return 2-3 options per category instead of just first match
max_items = min(3, len(style_materials))
for material in style_materials[:max_items]:
    materials.append(MaterialItem(...))
```

### Step 3: Rebuild and Test
```bash
cd ~/projects/your-app
sudo docker-compose up -d --build backend

# Test with different markets
MARKET=US curl -s -X POST http://localhost:8000/api/v1/generate-plan ...
```

## Pitfalls

1. **Hardcoded single material**: Avoid selecting only `style_materials[0]`. Return 2-3 options for user choice.

2. **Fake purchase URLs**: Always use real URLs (homedepot.com, lowes.com, taobao.com). Fake URLs destroy user trust.

3. **Missing style_match**: Every material should have `style_match` array. Without it, recommendation fails.

4. **Wrong unit conversion**: CN uses 平方米 (sq meters), US uses sq ft. Handle in room area config.

5. **Environment variable not loaded**: Ensure `docker-compose.yml` passes `MARKET` to backend container.

## User Preference Notes

- **Cost-conscious**: User chose "expand database" (one-time effort) over "ChatGPT API" ($30-270/year ongoing cost)
- **Structured output**: Provide comparison tables, not paragraphs
- **Actionable steps**: Always give specific commands, not vague advice

## References

- [materials_us.json](../references/materials_us.json) - North America database (26 materials, 13 brands: Pergo, Behr, Kohler, IKEA, etc.)
- [materials_cn.json](../references/materials_cn.json) - China database (22 materials, 10 brands: 圣象, 多乐士, 科勒, 欧派, etc.)
- [cost-comparison.md](../references/cost-comparison.md) - Detailed AI service cost analysis
- [expanded-database-pattern.md](references/expanded-database-pattern.md) - Pattern for expanding from 10 → 26+ materials per market
