"""
Image Search API — FastAPI route
Nhận text query + mảng base64 ảnh.
"""

import logging
from pydantic import BaseModel
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from typing import List, Optional

from agent.image_search_agent.image_search_graph import get_image_search_agent

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

class ImageSearchRequest(BaseModel):
    query: str
    images: Optional[List[str]] = None

@router.post("/chat", summary="Chat with Vision Image Search Agent")
async def image_search_chat(req: ImageSearchRequest):
    """
    Gửi câu hỏi và gửi ảnh (base64) để agent vision phân tích và tìm trong DB.
    """
    query = req.query.strip()
    images = req.images or []
    
    if not query and not images:
        return JSONResponse(status_code=400, content={"status": "error", "message": "Query text và ảnh đều trống"})

    try:
        agent = get_image_search_agent()
        result = await agent.chat(query, images=images)

        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"❌ Image Search error: {e}", exc_info=True)
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
