"""
cortex/hippo/reranker.py — Voyage reranker for post-retrieval precision.

Provides a VoyageReranker class that satisfies the RerankerProvider protocol
defined in retrieval.py. Uses the Voyage AI rerank API.

Issue: #1189
"""

from __future__ import annotations

import logging
from typing import Optional

logger = logging.getLogger(__name__)


class VoyageReranker:
    """Voyage rerank-2.5 implementation.

    Uses aiohttp for async HTTP calls to the Voyage rerank API.
    Satisfies the RerankerProvider protocol defined in retrieval.py.

    Issue: #1189
    """

    def __init__(
        self,
        api_key: str,
        model: str = "rerank-2.5",
        base_url: str = "https://api.voyageai.com/v1/rerank",
        timeout_seconds: float = 30.0,
    ) -> None:
        self.api_key = api_key
        self.model = model
        self._base_url = base_url
        self._timeout_seconds = timeout_seconds

    async def rerank(
        self,
        query: str,
        documents: list[str],
        top_k: int = 10,
    ) -> list[tuple[int, float]]:
        """Rerank documents by relevance to query.

        Returns list of (original_index, relevance_score) sorted by relevance
        descending.
        """
        if not documents:
            return []

        import aiohttp

        timeout = aiohttp.ClientTimeout(total=self._timeout_seconds)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            resp = await session.post(
                self._base_url,
                json={
                    "query": query,
                    "documents": documents,
                    "model": self.model,
                    "top_k": min(top_k, len(documents)),
                },
                headers={
                    "Authorization": f"Bearer {self.api_key}",
                    "Content-Type": "application/json",
                },
            )
            resp.raise_for_status()
            data = await resp.json()

        return [
            (r["index"], r["relevance_score"])
            for r in data.get("data", [])
        ]
