"""
Minimal compatibility console for legacy xwnode_console tests.
"""

from __future__ import annotations

from typing import Any

from exonware.xwquery import XWQuery
from exonware.xwnode import XWNode

from . import data


class XWQueryConsole:
    """
    Lightweight query console adapter expected by old xwquery unit scripts.
    """

    def __init__(self, seed: int = 42, verbose: bool = False):
        self.seed = seed
        self.verbose = verbose
        self.history: list[str] = []
        self.collections = data.load_all_collections(seed=seed)

    def _execute_query(self, query: str) -> Any:
        if not isinstance(query, str) or not query.strip():
            raise ValueError("Query must be a non-empty string")
        dataset = XWNode.from_native(self.collections)
        return XWQuery.execute(query, dataset, auto_detect=True)

    def _handle_command(self, command: str) -> Any:
        command = (command or "").strip()
        if not command:
            return None

        if command == ".help":
            return {
                "commands": [
                    ".help",
                    ".collections",
                    ".show <collection>",
                    ".examples [core]",
                    ".random",
                    ".history",
                ]
            }
        if command == ".collections":
            return sorted(self.collections.keys())
        if command.startswith(".show "):
            collection_name = command.split(maxsplit=1)[1]
            return self.collections.get(collection_name, [])
        if command.startswith(".examples"):
            return [
                "SELECT * FROM users",
                "SELECT name, age FROM users WHERE age > 30",
                "SELECT category, COUNT(*) FROM products GROUP BY category",
            ]
        if command == ".random":
            return "SELECT * FROM users LIMIT 5"
        if command == ".history":
            return list(self.history)
        if self.verbose:
            print(f"Unknown command: {command}")
        return None

