"""Weaviate vector adapter (Phase 6)."""
from __future__ import annotations

from typing import Iterable, List

from ..types import VectorMetadata


class WeaviateAdapter:
    """Minimal Weaviate adapter.

    Requires weaviate-client package.
    """

    def __init__(self, url: str, api_key: str = ""):
        try:
            import weaviate
        except Exception as exc:
            raise RuntimeError("weaviate-client not installed") from exc

        auth = None
        if api_key:
            from weaviate.auth import AuthApiKey
            auth = AuthApiKey(api_key)
        self.client = weaviate.Client(url=url, auth_client_secret=auth)
        self._ensure_schema()

    def _ensure_schema(self) -> None:
        try:
            schema = self.client.schema.get()
            classes = {c.get("class") for c in schema.get("classes", [])}
            if "VectorMetadata" in classes:
                return
            self.client.schema.create_class({
                "class": "VectorMetadata",
                "vectorizer": "none",
                "properties": [
                    {"name": "id", "dataType": ["text"]},
                    {"name": "source_type", "dataType": ["text"]},
                    {"name": "source_id", "dataType": ["text"]},
                    {"name": "hierarchy_id", "dataType": ["text"]},
                    {"name": "tags", "dataType": ["text[]"]},
                    {"name": "created_at", "dataType": ["text"]},
                    {"name": "updated_at", "dataType": ["text"]},
                ],
            })
        except Exception:
            # If schema management isn't available, skip
            return

    def add_metadata(self, items: Iterable[VectorMetadata]) -> int:
        count = 0
        for item in items:
            self.client.data_object.create(
                data_object=item.model_dump(),
                class_name="VectorMetadata",
                uuid=item.id,
            )
            count += 1
        return count

    def search(self, query: str, top_k: int = 5) -> List[VectorMetadata]:
        result = (
            self.client.query.get("VectorMetadata", ["id", "source_type", "source_id", "hierarchy_id", "tags", "created_at", "updated_at"])
            .with_near_text({"concepts": [query]})
            .with_limit(top_k)
            .do()
        )
        items = []
        for obj in result.get("data", {}).get("Get", {}).get("VectorMetadata", []):
            items.append(VectorMetadata(**obj))
        return items
