"""
使用 ChatGPT API 动态生成材料清单
成本: ~$0.02-0.06/次 (比数据库查询贵很多)
适用场景: 需要智能分析户型图、个性化推荐
"""
import os
import httpx
from typing import List, Dict
import json

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

async def generate_materials_with_chatgpt(
    style: str, 
    room_type: str,
    room_area: float,
    layout_description: str = ""
) -> List[Dict]:
    """
    调用 ChatGPT API 生成材料清单
    
    参数:
        style: 装修风格 (Modern, Scandinavian, etc.)
        room_type: 房间类型 (living_room, bedroom, kitchen)
        room_area: 房间面积 (sq ft)
        layout_description: 户型图描述 (可选，从图片识别)
    
    返回: 
        [
            {
                "name": "Laminate Flooring",
                "brand": "Pergo",
                "model": "Outlast+",
                "price_per_unit": 2.59,
                "unit": "sq ft",
                "quantity": 300,
                "subtotal": 777.0,
                "supplier": "Home Depot",
                "purchase_url": "https://www.homedepot.com/p/...",
                "reason": "Waterproof, durable, matches modern style"
            },
            ...
        ]
    """
    if not OPENAI_API_KEY:
        raise ValueError("OPENAI_API_KEY not set")
    
    # 构造提示词
    prompt = f"""
    You are a professional interior designer. Generate a detailed material list for a {room_type} renovation.
    
    Requirements:
    - Style: {style}
    - Room area: {room_area} sq ft
    - Room type: {room_type}
    - Location: North America (USA/Canada)
    
    For each material, provide:
    1. Material name
    2. Recommended brand (popular in North America)
    3. Model/Product name
    4. Price per unit (USD)
    5. Quantity needed (based on room area)
    6. Total cost
    7. Where to buy (Home Depot, Lowe's, Amazon, etc.)
    8. Direct purchase URL (real working URL)
    9. Reason for recommendation
    
    Include materials for:
    - Flooring (floor)
    - Wall paint (wall)
    - Ceiling (ceiling)
    - Lighting (lighting)
    - Furniture (if applicable)
    
    Return JSON format:
    [
        {{
            "name": "...",
            "category": "...",
            "brand": "...",
            "model": "...",
            "price_per_unit": 0.0,
            "unit": "...",
            "quantity": 0,
            "subtotal": 0.0,
            "supplier": "...",
            "purchase_url": "...",
            "reason": "..."
        }}
    ]
    
    IMPORTANT: 
    - Use real brands and products available at Home Depot, Lowe's, Amazon
    - Provide REAL working URLs (not example.com)
    - Be specific with model names
    - Calculate quantities based on room area
    """
    
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://api.openai.com/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {OPENAI_API_KEY}",
                "Content-Type": "application/json"
            },
            json={
                "model": "gpt-3.5-turbo",  # 用 3.5 省钱，4 更准
                "messages": [
                    {"role": "system", "content": "You are a professional interior designer."},
                    {"role": "user", "content": prompt}
                ],
                "temperature": 0.7,
                "max_tokens": 2000
            },
            timeout=30.0
        )
        
        if response.status_code != 200:
            raise Exception(f"OpenAI API Error: {response.text}")
        
        content = response.json()["choices"][0]["message"]["content"]
        
        # 解析 JSON (处理可能的 markdown 代码块)
        import re
        json_match = re.search(r'```json\s*(.*?)\s*```', content, re.DOTALL)
        if json_match:
            content = json_match.group(1)
        
        try:
            materials = json.loads(content)
            return materials
        except json.JSONDecodeError:
            print(f"Failed to parse JSON: {content}")
            return []


# 成本对比
COST_COMPARISON = {
    "ChatGPT (gpt-3.5-turbo)": {
        "cost_per_call": "$0.002-0.01",  # 输入+输出 tokens
        "speed": "3-10秒",
        "pros": ["动态生成", "智能推理", "可分析图片"],
        "cons": ["成本高", "速度慢", "不稳定（可能返回错误格式）"]
    },
    "ChatGPT (gpt-4)": {
        "cost_per_call": "$0.03-0.06",
        "speed": "5-15秒",
        "pros": ["更准确", "更好推理"],
        "cons": ["非常贵", "速度慢"]
    },
    "当前方案 (JSON数据库)": {
        "cost_per_call": "$0.000001 (几乎免费)",
        "speed": "<0.01秒",
        "pros": ["零成本", "毫秒级响应", "数据可控"],
        "cons": ["静态数据", "需手动维护"]
    },
    "混合方案 (推荐)": {
        "cost_per_call": "$0.002 (按需)",
        "speed": "数据库 <0.01s, ChatGPT 3-10s",
        "pros": ["快速+智能", "成本可控", "最佳实践"],
        "cons": ["实现复杂"]
    }
}

# 年度成本估算 (假设每月生成 500 次材料清单)
ANNUAL_COST = {
    "ChatGPT gpt-3.5": "$0.005 * 500 * 12 = $30/年",
    "ChatGPT gpt-4": "$0.045 * 500 * 12 = $270/年",
    "JSON 数据库": "<$1/年 (几乎免费)",
    "当前方案": "<$1/年 (已经部署)"
}
