"""HeadroomRetrieveTool — CCR 可逆压缩检索工具

当 HeadroomCompressor 启用时，LLM 可通过此工具从 CCR 缓存中
取回被压缩的原始数据。工具输出中的 <!-- CCR:hash=xxx --> 标记
指示可检索的内容。
"""

import logging
from typing import Any

from agentkit.tools.base import Tool

logger = logging.getLogger(__name__)


class HeadroomRetrieveTool(Tool):
    """从 CCR 缓存检索原始未压缩数据

    当 Headroom 压缩工具输出后，LLM 可通过此工具取回原始数据。
    压缩内容中包含 <!-- CCR:hash=xxx --> 标记，LLM 可使用该哈希值检索。
    """

    def __init__(self, compressor: Any):
        super().__init__(
            name="headroom_retrieve",
            description=(
                "Retrieve original uncompressed data from the CCR (Compress-Cache-Retrieve) cache. "
                "Use this tool when you see a <!-- CCR:hash=xxx --> marker in compressed content "
                "and need the full original data. Pass the hash value or a search query."
            ),
            input_schema={
                "type": "object",
                "properties": {
                    "ccr_hash": {
                        "type": "string",
                        "description": "The CCR hash from a <!-- CCR:hash=xxx --> marker. Use this for direct lookup.",
                    },
                    "query": {
                        "type": "string",
                        "description": "Search query to find matching cached content. Used when hash is not available.",
                    },
                },
                "anyOf": [
                    {"required": ["ccr_hash"]},
                    {"required": ["query"]},
                ],
            },
        )
        self._compressor = compressor

    async def execute(self, **kwargs) -> dict:
        """从 CCR 缓存检索原始数据"""
        ccr_hash = kwargs.get("ccr_hash")
        query = kwargs.get("query")

        if not ccr_hash and not query:
            return {
                "error": "Either ccr_hash or query must be provided",
                "success": False,
            }

        try:
            result = self._compressor.retrieve(ccr_hash=ccr_hash, query=query)
            return result
        except Exception as e:
            logger.error(f"CCR retrieval failed: {e}")
            return {
                "error": f"CCR retrieval failed: {e}",
                "success": False,
            }
