"""Session search tool — search past conversations via FTS5."""

from __future__ import annotations

import json
from datetime import datetime
from typing import Any

from flowly.agent.tools.base import Tool


def _format_ts(ts: float | None) -> str:
    """Convert Unix timestamp to readable string."""
    if not ts:
        return ""
    try:
        return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
    except (ValueError, OSError):
        return ""


class SessionSearchTool(Tool):
    """Search past conversations using full-text search.

    Two modes:
    - With query: FTS5 keyword search across all past sessions
    - Without query: list recent sessions (no cost, instant)
    """

    def __init__(self, indexer: Any):  # SessionIndexer
        self._indexer = indexer

    @property
    def name(self) -> str:
        return "session_search"

    @property
    def description(self) -> str:
        return (
            "Search past conversations for specific topics, decisions, or details. "
            "Use this PROACTIVELY when the user says 'we did this before', "
            "'remember when', 'last time', or references a past topic. "
            "Call with no query to browse recent sessions. "
            "Better to search and confirm than to guess or ask the user to repeat."
        )

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": (
                        "Search keywords. Use OR for broad recall "
                        "(e.g. 'docker OR kubernetes'), quotes for exact "
                        "phrases ('\"docker build\"'). Omit to list recent sessions."
                    ),
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (default 5, max 10)",
                    "default": 5,
                },
            },
            "required": [],
        }

    async def execute(
        self,
        query: str = "",
        limit: int = 5,
        **kwargs: Any,
    ) -> str:
        limit = min(max(limit, 1), 10)
        current_session = kwargs.get("session_key", "")

        try:
            if not query or not query.strip():
                return self._list_recent(limit, current_session)
            return self._search(query.strip(), limit, current_session)
        except Exception as e:
            return json.dumps({"error": str(e), "results": []})

    def _search(self, query: str, limit: int, exclude: str) -> str:
        results = self._indexer.search(
            query=query,
            limit=limit,
            exclude_session=exclude or None,
        )

        if not results:
            return json.dumps({
                "query": query,
                "results": [],
                "message": "No matching sessions found.",
            })

        items = []
        for r in results:
            items.append({
                "session": r["session_key"],
                "date": _format_ts(r.get("session_created")),
                "role": r["role"],
                "snippet": r["snippet"],
                "context": r.get("context", []),
                "messages_in_session": r.get("msg_count", 0),
            })

        return json.dumps({
            "query": query,
            "results": items,
            "count": len(items),
        }, ensure_ascii=False)

    def _list_recent(self, limit: int, exclude: str) -> str:
        results = self._indexer.list_recent(
            limit=limit,
            exclude_session=exclude or None,
        )

        items = []
        for r in results:
            items.append({
                "session": r["key"],
                "date": _format_ts(r.get("created_at")),
                "last_active": _format_ts(r.get("updated_at")),
                "messages": r.get("msg_count", 0),
                "preview": r.get("preview", ""),
            })

        return json.dumps({
            "mode": "recent",
            "results": items,
            "count": len(items),
            "message": "Use a keyword query to search specific topics.",
        }, ensure_ascii=False)
