from __future__ import annotations

import asyncio
import logging

from src.config import LLMConfig
from src.database import Database
from src.database.bundles import SearchBundle
from src.models import SearchResult

logger = logging.getLogger(__name__)

_SYSTEM_PROMPT = """Ты — ассистент для поиска по Telegram-постам.
Используй инструмент search_posts_tool для поиска по базе.
Анализируй результаты и давай краткое резюме на русском языке.
Выдели ключевые находки и укажи ссылки на каналы."""


class AISearchEngine:
    def __init__(self, config: LLMConfig, search: SearchBundle | Database):
        self._config = config
        if isinstance(search, Database):
            search = SearchBundle.from_database(search)
        self._search = search
        self._agent = None
        self._init_error: str | None = None

    @property
    def enabled(self) -> bool:
        return self._config.enabled and bool(self._config.api_key)

    def initialize(self) -> None:
        if not self.enabled:
            logger.info("AI search disabled (llm.enabled=false or no API key)")
            return

        try:
            from deepagents import create_deep_agent
        except ImportError as exc:
            logger.warning("deepagents not installed, AI search unavailable: %s", exc)
            return

        search = self._search

        def search_posts_tool(query: str) -> str:
            """Search collected posts in the database."""
            import concurrent.futures

            try:
                asyncio.get_running_loop()
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    coro = search.search_messages(query, limit=20)
                    future = executor.submit(asyncio.run, coro)
                    messages, total = future.result()
            except RuntimeError:
                messages, total = asyncio.run(search.search_messages(query, limit=20))

            if not messages:
                return f"No results found for: {query}"

            lines = [f"Found {total} results for '{query}'. Top results:"]
            for m in messages:
                text_preview = (m.text or "")[:200]
                lines.append(f"- [{m.date}] Channel {m.channel_id}: {text_preview}")
            return "\n".join(lines)

        model_str = f"{self._config.provider}:{self._config.model}"
        try:
            self._agent = create_deep_agent(
                model=model_str,
                tools=[search_posts_tool],
                system_prompt=_SYSTEM_PROMPT,
            )
            logger.info("AI search agent initialized with model %s", model_str)
        except ImportError as exc:
            logger.warning("AI search dependency missing: %s", exc)
        except Exception as e:
            logger.error("Failed to initialize AI search: %s", e)
            self._init_error = str(e)

    async def search(self, query: str) -> SearchResult:
        """Run AI-powered search."""
        if not self._agent:
            # Fallback to basic local search
            messages, total = await self._search.search_messages(query, limit=20)
            return SearchResult(
                messages=messages,
                total=total,
                query=query,
                ai_summary="AI search is not available. Showing local results.",
            )

        try:
            response = await asyncio.to_thread(self._agent.run, query)
            summary = str(response)

            # Also get raw messages for display
            messages, total = await self._search.search_messages(query, limit=20)

            return SearchResult(
                messages=messages,
                total=total,
                query=query,
                ai_summary=summary,
            )
        except Exception as e:
            logger.error("AI search error: %s", e)
            messages, total = await self._search.search_messages(query, limit=20)
            return SearchResult(
                messages=messages,
                total=total,
                query=query,
                ai_summary=f"AI search error: {e}. Showing local results.",
            )
