from typing import List

from fastapi import APIRouter, Body, Depends, HTTPException

from memos_core.schemas import MemoEmbeddingCreate, MemoEmbeddingResponse
from memos_core.services import get_memo_embedding_service

router = APIRouter(prefix="/memo-embeddings", tags=["memo-embeddings"])


@router.post("", response_model=MemoEmbeddingResponse)
async def create_embedding(
    payload: MemoEmbeddingCreate = Body(...),
    svc=Depends(get_memo_embedding_service),
):
    try:
        return await svc.create_embedding(payload)
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/search", response_model=List[MemoEmbeddingResponse])
async def search_embeddings(
    payload: dict = Body(...),
    svc=Depends(get_memo_embedding_service),
):
    """
    Payload:
    {
      "queryEmbedding": [float],
      "topK": 5,
      "dateKey": "YYYY-MM-DD" (optional),
      "memoId": 1 (optional)
    }
    """
    try:
        query_embedding = payload.get("queryEmbedding") or payload.get("embedding")
        top_k = int(payload.get("topK", 5))
        date_key = payload.get("dateKey")
        memo_id = payload.get("memoId")
        return await svc.search_embeddings(query_embedding, top_k=top_k, date_key=date_key, memo_id=memo_id)
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=400, detail=str(exc)) from exc
