from typing import Annotated

from fastapi import APIRouter, Depends
from session_hub_fastapi.models.session_hub import (
    MessageSearchResult,
    SessionRow,
    SessionSearchResult,
)

from session_hub_api.dependencies import get_query_api
from session_hub_api.mapping import message_search_result, session_row, session_search_result
from session_hub_core.query import QueryAPI

router = APIRouter(tags=["Search"])


@router.get("/api/search", response_model=list[MessageSearchResult])
async def search_messages(
    query: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
    tool: str | None = None,
    host: str | None = None,
    role: str | None = None,
    limit: int = 50,
    mode: str = "fts",
) -> list[MessageSearchResult]:
    results = await query_api.search_messages(
        query=query, tool=tool, host=host, role=role, limit=limit, mode=mode
    )
    return [message_search_result(result) for result in results]


@router.get("/api/search/sessions", response_model=list[SessionRow])
async def search_sessions(
    query: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
    tool: str | None = None,
    host: str | None = None,
    limit: int = 50,
    mode: str = "fts",
) -> list[SessionRow]:
    rows = await query_api.search_sessions(
        query=query, tool=tool, host=host, limit=limit, mode=mode
    )
    return [session_row(row) for row in rows]


@router.get("/api/search/similar/sessions", response_model=list[SessionSearchResult])
async def search_similar_sessions(
    query: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
    tool: str | None = None,
    host: str | None = None,
    limit: int = 20,
) -> list[SessionSearchResult]:
    results = await query_api.search_similar_sessions(
        query=query, tool=tool, host=host, limit=limit
    )
    return [session_search_result(result) for result in results]


@router.get("/api/search/similar/messages", response_model=list[MessageSearchResult])
async def search_similar_messages(
    query: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
    tool: str | None = None,
    host: str | None = None,
    role: str | None = None,
    limit: int = 50,
) -> list[MessageSearchResult]:
    results = await query_api.search_similar_messages(
        query=query, tool=tool, host=host, role=role, limit=limit
    )
    return [message_search_result(result) for result in results]
