from qdrant_client.models import ScoredPoint


def rerank(query: str, results: list[ScoredPoint], k: int = 5) -> list[dict]:
    if not results:
        return []

    def get_payload(p: ScoredPoint, key: str, default=""):
        return (p.payload or {}).get(key, default)

    scored = []
    for r in results:
        scored.append({
            "ticket_id": get_payload(r, "ticket_id"),
            "score": float(r.score or 0),
            "full_text": get_payload(r, "full_text"),
            "category": get_payload(r, "category"),
        })

    scored.sort(key=lambda x: x["score"], reverse=True)
    return scored[:k]
