"""
Store Search API — FastAPI route cho tìm kiếm cửa hàng bằng AI.
Gọi StoreSearchGraph 2-Agent (Planner → Tool → Responder).
"""

import logging

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from agent.store_search_agent.store_search_graph import get_store_search_agent

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/store-search", tags=["Store Search"])


class StoreChatRequest(BaseModel):
    query: str


@router.post("/chat", summary="Chat with Store Search Agent")
async def store_chat(req: StoreChatRequest):
    """
    Gửi câu hỏi cho Store Search Agent.
    Agent sẽ tự phân tích khu vực → gọi tool -> format lại text .
    """
    query = req.query.strip()
    if not query:
        return JSONResponse(status_code=400, content={"status": "error", "message": "Query trống"})

    try:
        agent = get_store_search_agent()
        result = await agent.chat(query)

        return {
            "status": "success",
            "response": result["response"],
            "elapsed_ms": result["elapsed_ms"],
            "agent_path": result["agent_path"],
            "tool_calls": result["tool_calls"],
            "pipeline": result["pipeline"],
        }
    except Exception as e:
        logger.error(f"❌ Store Search error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
