"""Local synthetic document pipeline with chunking, hybrid scoring and citations."""
from __future__ import annotations

from collections import Counter
from dataclasses import dataclass
from hashlib import sha256
from math import sqrt
import re

from labs.retrieval_evaluation import Document, latest_documents, terms


@dataclass(frozen=True)
class Passage:
    document_id: str
    tenant: str
    revision: int
    start_word: int
    text: str

    @property
    def citation(self):
        return (self.document_id, self.revision, self.start_word)


def feature_vector(text):
    """Hash terms into deterministic sparse features without a learned model."""
    tokens = re.findall(r"\w+", text.lower())
    return Counter(int.from_bytes(sha256(term.encode()).digest()[:2], "big") for term in tokens)


def build_index(documents, words_per_chunk=30):
    if type(words_per_chunk) is not int or words_per_chunk < 1:
        raise ValueError("Chunk size must be a positive integer")
    documents = tuple(documents)
    if any(not doc.id or not doc.tenant or type(doc.revision) is not int or doc.revision < 0
           or (doc.text is not None and not isinstance(doc.text, str)) for doc in documents):
        raise ValueError("Each document needs an ID, tenant, revision and text or a tombstone")
    index = []
    for doc in latest_documents(documents).values():
        words = (doc.text or "").split()
        for offset in range(0, len(words), words_per_chunk):
            text = " ".join(words[offset:offset + words_per_chunk])
            passage = Passage(doc.id, doc.tenant, doc.revision, offset, text)
            index.append((passage, feature_vector(text), terms(text)))
    return index


def search(index, tenant, question, k=3):
    """Return extractive passages with references to the indexed source revision."""
    if not tenant or type(k) is not int or k < 1:
        raise ValueError("Tenant and positive result count are required")
    query_tokens = terms(question)
    query_vector = feature_vector(question)
    query_norm = sqrt(sum(count * count for count in query_vector.values()))
    if not query_norm:
        return []
    ranked = []
    for passage, vector, tokens in index:
        if passage.tenant != tenant:
            continue
        hits = len(query_tokens & tokens)
        if not hits:
            continue
        norm = sqrt(sum(count * count for count in vector.values()))
        cosine = sum(count * vector.get(key, 0) for key, count in query_vector.items()) / (norm * query_norm)
        ranked.append((hits / len(query_tokens) + cosine, passage))
    return [passage for _, passage in sorted(ranked, key=lambda entry: (-entry[0], entry[1].citation))[:k]]


if __name__ == "__main__":
    corpus = [Document("guide", "demo", 1, "Restore a dataset by checking its snapshot and watermark."),
              Document("secret", "other", 1, "Restore the confidential dataset.")]
    for passage in search(build_index(corpus), "demo", "restore dataset"):
        print(passage.text, passage.citation)
