"""File-backed vector store adapter (Phase 1 stub)."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Iterable, List

from ..types import VectorMetadata


class VectorStoreAdapter:
    """Lightweight file-backed vector metadata store.

    This is a Phase 1 scaffold to enable dual-write and ingestion tests
    without requiring an external vector database.
    """

    def __init__(self, base_dir: Path):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(parents=True, exist_ok=True)
        self.file_path = self.base_dir / "vector_metadata.jsonl"

    def add_metadata(self, items: Iterable[VectorMetadata]) -> int:
        """Append metadata entries to the store."""
        count = 0
        with self.file_path.open("a", encoding="utf-8") as f:
            for item in items:
                f.write(item.model_dump_json() + "\n")
                count += 1
        return count

    def load_all(self) -> List[VectorMetadata]:
        """Load all metadata entries."""
        if not self.file_path.exists():
            return []
        items: List[VectorMetadata] = []
        with self.file_path.open("r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                items.append(VectorMetadata(**json.loads(line)))
        return items

    def search(self, query: str, top_k: int = 5) -> List[VectorMetadata]:
        """Naive keyword search over metadata for Phase 1 demos."""
        q = query.lower()
        matches = []
        for item in self.load_all():
            haystack = " ".join([
                item.id,
                item.source_type,
                item.source_id,
                " ".join(item.tags),
            ]).lower()
            if q in haystack:
                matches.append(item)
        return matches[:top_k]
