"""
Visual Search Agent — Entry point for image-based product search.

Supports:
  - Local file paths
  - HTTP/HTTPS URLs (downloads to temp file)
  - Base64-encoded image data

Extracts fashion tags via Local CPU Vision Model, then builds
a search query for the Lead Search Agent or direct SQL.
"""

import logging
import os
import tempfile

from agent.image_search_agent.vision_model import vision_model

logger = logging.getLogger(__name__)


async def handle_visual_search(image_input: str) -> dict:
    """
    Main entry point for Visual Search pipeline.

    Args:
        image_input: File path, HTTP URL, or base64-encoded image data.

    Returns:
        dict with: success, raw_features, search_query, confidence, all_queries
    """
    logger.info("Đang thực hiện Visual Search cho ảnh: %s", image_input[:80])

    # 1. Resolve image to a local file path
    image_path = await _resolve_image_input(image_input)
    if image_path is None:
        return {"success": False, "error": "Không thể đọc ảnh từ input."}

    cleanup_needed = image_path != image_input  # temp file needs cleanup

    try:
        # 2. Image Analysis (CPU-based)
        analysis_result = vision_model.analyze_image(image_path)

        if "error" in analysis_result:
            logger.error("Visual Search thất bại: %s", analysis_result["error"])
            return {"success": False, "error": analysis_result["error"]}

        features = analysis_result.get("features", {})
        category = features.get("category", "")
        color = features.get("color", "")
        style = features.get("style", "")
        all_categories = features.get("all_categories", [])

        # 3. Build primary query intent
        query_parts = []
        if category and category != "unknown":
            query_parts.append(category)
        if color and color != "unknown":
            query_parts.append(f"màu {color}")
        if style and style not in ("casual", "unknown"):
            query_parts.append(f"phong cách {style}")

        generated_query = " ".join(query_parts) if query_parts else "sản phẩm thời trang"

        # 4. Build alternative queries from all matched categories
        alt_queries = []
        for cat in all_categories:
            if cat != category:
                q = cat
                if color and color != "unknown":
                    q += f" màu {color}"
                alt_queries.append(q)

        logger.info("Visual Search sinh ra query: '%s' dựa trên ảnh.", generated_query)

        return {
            "success": True,
            "raw_features": features,
            "search_query": generated_query,
            "all_queries": alt_queries,
            "confidence": analysis_result.get("confidence", 0.0),
        }

    finally:
        if cleanup_needed and os.path.exists(image_path):
            try:
                os.unlink(image_path)
            except OSError:
                pass


async def _resolve_image_input(image_input: str) -> str | None:
    """
    Resolve image input to a local file path.

    Handles:
      - Local file path (returned as-is)
      - HTTP/HTTPS URL (downloaded to temp file)
      - Base64-encoded data (decoded to temp file)
    """
    # Case 1: Local file
    if os.path.isfile(image_input):
        return image_input

    # Case 2: URL
    if image_input.startswith(("http://", "https://")):
        return await _download_image(image_input)

    # Case 3: Base64
    if "," in image_input or len(image_input) > 200:
        return _decode_base64_image(image_input)

    logger.error("Không nhận dạng được định dạng ảnh: %s", image_input[:50])
    return None


async def _download_image(url: str) -> str | None:
    """Download image from URL to a temp file."""
    try:
        import httpx

        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.get(url)
            response.raise_for_status()

        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
            tmp.write(response.content)
            return tmp.name
    except Exception as e:
        logger.error("Không thể tải ảnh từ URL %s: %s", url[:50], e)
        return None


def _decode_base64_image(data: str) -> str | None:
    """Decode base64 image data to a temp file."""
    try:
        import base64

        # Strip data URI prefix if present
        img_data = data.split(",")[-1] if "," in data else data
        raw_bytes = base64.b64decode(img_data)

        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
            tmp.write(raw_bytes)
            return tmp.name
    except Exception as e:
        logger.error("Không thể decode ảnh base64: %s", e)
        return None
