"""
Text-to-SQL Chat API — Bản 2 chatbot logic.
User hỏi → LLM sinh SQL → DB → LLM response.
"""
import logging

from fastapi import APIRouter
from pydantic import BaseModel

from agent.text_to_sql import text_to_sql_chat

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api")


class TextToSQLRequest(BaseModel):
    user_query: str


@router.post("/v2/chat")
async def v2_chat(req: TextToSQLRequest):
    """
    Bản 2: Text-to-SQL chatbot.
    User hỏi → LLM sinh SQL → chọc DB → LLM viết response.
    """
    logger.info("🤖 [V2] Text-to-SQL chat: %s", req.user_query[:100])

    try:
        result = await text_to_sql_chat(req.user_query)
        return {
            "status": "success",
            "ai_response": result["ai_response"],
            "products": result["products"],
            "sql": result["sql"],
            "timing": result["timing"],
            "product_count": result["product_count"],
        }
    except Exception as e:
        logger.exception("❌ [V2] Error: %s", e)
        return {
            "status": "error",
            "ai_response": f"Xin lỗi, có lỗi xảy ra: {str(e)}",
            "products": [],
            "sql": "",
            "timing": {},
            "product_count": 0,
        }
