"""
Search API routes — Meilisearch keyword search for memos.
"""

import logging

from fastapi import APIRouter, Query, Request

from common.meili_service import meili_service

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


def get_current_user_id(request: Request) -> str | None:
    return getattr(request.state, "user_id", None)


@router.get("/search", summary="Search memos by keyword")
async def search_memos(
    request: Request,
    q: str = Query(..., min_length=1, description="Search query"),
    limit: int = Query(default=20, ge=1, le=100, description="Max results"),
):
    """
    Full-text keyword search on memos using Meilisearch.
    - Typo-tolerant
    - Search-as-you-type ready
    - Filtered by current user (multi-tenant)
    """
    user_id = get_current_user_id(request)

    if not meili_service.enabled:
        return {"hits": [], "query": q, "message": "Search service unavailable"}

    hits = meili_service.search(
        query=q,
        creator_id=user_id,
        limit=limit,
    )

    return {
        "hits": hits,
        "query": q,
        "total": len(hits),
    }
