from __future__ import annotations

import hashlib
from pathlib import Path

import numpy as np

import mikoshi.indexing.indexer as indexer
import mikoshi.retrieval.hybrid as hybrid
from mikoshi.retrieval.semantic import EmbeddingsProvider


class DummyProvider(EmbeddingsProvider):
    def __init__(self) -> None:
        self.name = "local"
        self.model = "dummy"
        self.dimension = 8

    def embed_texts(self, texts):
        vectors = []
        for text in texts:
            digest = hashlib.sha256(text.encode("utf-8")).digest()
            values = [b / 255.0 for b in digest[: self.dimension]]
            vectors.append(values)
        return np.asarray(vectors, dtype=np.float32)


def test_index_roundtrip(tmp_path: Path, monkeypatch) -> None:
    repo = tmp_path / "repo"
    repo.mkdir()
    (repo / "a.txt").write_text("hello world\nsecond line\n", encoding="utf-8")

    provider = DummyProvider()
    monkeypatch.setattr(indexer, "get_embeddings_provider", lambda config: provider)
    monkeypatch.setattr(hybrid, "get_embeddings_provider", lambda config: provider)
    monkeypatch.setenv("MIKOSHI_INDEX_ROOT", str(tmp_path / "index-data"))

    result = indexer.index_repo(str(repo))
    assert result.chunks_indexed > 0

    results = hybrid.search_repo(str(repo), "hello", k=5)
    assert results
    assert results[0].relpath == "a.txt"
