"""FalkorDB adapter — Redis protocol."""

from __future__ import annotations

from falkordb import FalkorDB

from . import CypherAdapter, QueryResult


class FalkorDBAdapter(CypherAdapter):

    def connect(self, host, port, auth, **options):
        self._db = FalkorDB(host=host, port=port)
        self._graph = self._db.select_graph(
            options.get("graph_name", "default")
        )

    def execute(self, query):
        result = self._graph.query(query)
        return QueryResult(
            columns=[h[1] for h in result.header],
            rows=[list(row) for row in result.result_set],
        )

    def get_version(self) -> str | None:
        try:
            info = self._db.connection.info("modules")
            for mod in info.get("modules", []):
                if mod.get("name") == "graph":
                    ver = mod["ver"]
                    return f"FalkorDB {ver // 10000}.{ver % 10000 // 100}.{ver % 100}"
            return None
        except Exception:
            return None

    def close(self):
        pass  # FalkorDB client has no explicit close
