# retoor <retoor@molodetz.nl>

from __future__ import annotations

import json
import logging
from typing import Any

from ..config import Settings
from ..errors import ToolInputError

logger = logging.getLogger("devii.docs")

DEFAULT_MAX_RESULTS = 5
CONTENT_CHARS = 2400


class DocsController:
    def __init__(self, settings: Settings, is_admin: bool = False) -> None:
        self._settings = settings
        self._is_admin = is_admin

    def set_admin(self, is_admin: bool) -> None:
        self._is_admin = is_admin

    async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
        if name != "search_docs":
            raise ToolInputError(f"Unknown docs tool: {name}")
        return await self._search(arguments)

    async def _search(self, arguments: dict[str, Any]) -> str:
        from devplacepy import docs_search

        query = str(arguments.get("query", "")).strip()
        if not query:
            raise ToolInputError("search_docs requires a query.")
        max_results = int(
            arguments.get("max_results", DEFAULT_MAX_RESULTS) or DEFAULT_MAX_RESULTS
        )
        max_results = max(1, min(max_results, 10))

        results = docs_search.search_pages(
            query,
            user=None,
            is_admin=self._is_admin,
            limit=max_results,
            content_chars=CONTENT_CHARS,
        )
        return json.dumps(
            {
                "status": "success",
                "query": query,
                "count": len(results),
                "results": results,
            },
            ensure_ascii=False,
        )
