from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel

from app.tool.meetspot_recommender import CafeRecommender
from app.logger import logger

router = APIRouter(prefix="/api/miniprogram", tags=["miniprogram"])

class LocationItem(BaseModel):
    lng: float
    lat: float
    address: Optional[str] = ""
    name: Optional[str] = ""

class CalculateRequest(BaseModel):
    locations: List[LocationItem]
    keywords: Optional[str] = "咖啡馆"
    requirements: Optional[str] = ""
    min_rating: Optional[float] = 0.0
    max_distance: Optional[int] = 100000
    price_range: Optional[str] = ""

@router.post("/calculate")
async def calculate_meetspot(request: CalculateRequest):
    """小程序核心计算接口：根据坐标直接计算推荐"""
    try:
        recommender = CafeRecommender()
        
        # 转换 locations 为 list of dict
        location_dicts = [loc.model_dump() for loc in request.locations]
        
        result = await recommender.execute_for_miniprogram(
            locations=location_dicts,
            keywords=request.keywords,
            user_requirements=request.requirements,
            min_rating=request.min_rating,
            max_distance=request.max_distance,
            price_range=request.price_range
        )
        
        if not result.get("success", False):
            # 业务逻辑错误也返回 200，但在 body 中包含 error
            return result
            
        return result
        
    except Exception as e:
        logger.error(f"Miniprogram calculation failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))
