"""
Trust verification tool for AutoGen multi-agent conversations.
"""

import logging
import time
from typing import Optional

import requests

logger = logging.getLogger("nerq.autogen")

NERQ_API = "https://nerq.ai"
PREFLIGHT_TIMEOUT = 5.0
CACHE_TTL = 300  # 5 minutes


class TrustError(Exception):
    """Raised when an agent fails trust verification."""

    def __init__(self, agent_name: str, trust_score: Optional[float], recommendation: str):
        self.agent_name = agent_name
        self.trust_score = trust_score
        self.recommendation = recommendation
        super().__init__(
            f"Trust check failed for '{agent_name}': "
            f"trust={trust_score}, recommendation={recommendation}"
        )


class _TTLCache:
    """Simple TTL cache for preflight results."""

    def __init__(self, ttl: int = CACHE_TTL):
        self._cache: dict = {}
        self._ttl = ttl

    def get(self, key: str) -> Optional[dict]:
        if key in self._cache:
            result, ts = self._cache[key]
            if time.time() - ts < self._ttl:
                return result
            del self._cache[key]
        return None

    def set(self, key: str, value: dict):
        self._cache[key] = (value, time.time())
        if len(self._cache) > 5000:
            self._cache.clear()


class NerqTrustTool:
    """Trust verification tool for AutoGen agents.

    Checks agent trust scores via the Nerq Trust Index before allowing
    interaction in multi-agent conversations.

    Args:
        min_trust: Minimum trust score to approve (default 60).
        api_base: Nerq API base URL (default https://nerq.ai).
        cache_ttl: Cache TTL in seconds (default 300).
    """

    def __init__(
        self,
        min_trust: int = 60,
        api_base: str = NERQ_API,
        cache_ttl: int = CACHE_TTL,
    ):
        self.min_trust = min_trust
        self.api_base = api_base.rstrip("/")
        self._cache = _TTLCache(ttl=cache_ttl)

    def check(self, agent_name: str) -> dict:
        """Check an agent's trust score.

        Args:
            agent_name: Name of the agent to verify.

        Returns:
            Dict with trust_score, trust_grade, approved, recommendation.
        """
        cached = self._cache.get(agent_name.lower())
        if cached:
            return cached

        try:
            resp = requests.get(
                f"{self.api_base}/v1/preflight",
                params={"target": agent_name},
                timeout=PREFLIGHT_TIMEOUT,
            )
            resp.raise_for_status()
            data = resp.json()

            trust_score = data.get("target_trust")
            trust_grade = data.get("target_grade")
            recommendation = data.get("recommendation", "UNKNOWN")

            approved = (
                trust_score is not None
                and trust_score >= self.min_trust
                and recommendation != "DENY"
            )

            result = {
                "agent_name": agent_name,
                "trust_score": trust_score,
                "trust_grade": trust_grade,
                "approved": approved,
                "recommendation": recommendation if approved else "REJECT",
            }

        except Exception as e:
            logger.warning(f"Nerq preflight unreachable for '{agent_name}': {e}")
            result = {
                "agent_name": agent_name,
                "trust_score": None,
                "trust_grade": None,
                "approved": False,
                "recommendation": "UNKNOWN",
            }

        self._cache.set(agent_name.lower(), result)
        return result


def trust_check_tool(min_trust: int = 60) -> dict:
    """Create an AutoGen-compatible function tool for trust verification.

    Args:
        min_trust: Minimum trust score to approve (default 60).

    Returns:
        Dict with name, description, and function reference for AutoGen tool registration.

    Example:
        >>> tool = trust_check_tool(min_trust=70)
        >>> assistant = autogen.AssistantAgent("assistant", llm_config={"tools": [tool]})
    """
    trust_tool = NerqTrustTool(min_trust=min_trust)

    def _check(agent_name: str) -> str:
        """Check the trust score of an AI agent before interaction.

        Args:
            agent_name: Name of the agent to verify.

        Returns:
            Formatted string with trust verification result.
        """
        result = trust_tool.check(agent_name)
        status = "APPROVED" if result["approved"] else "REJECTED"
        score = result["trust_score"]
        grade = result["trust_grade"] or "N/A"
        return (
            f"Trust Check: {status}\n"
            f"Agent: {result['agent_name']}\n"
            f"Score: {score}\n"
            f"Grade: {grade}\n"
            f"Recommendation: {result['recommendation']}"
        )

    return {
        "name": "trust_check",
        "description": (
            "Check the trust score of an AI agent before interaction. "
            "Returns trust score, grade, and approval status from the "
            "Nerq Trust Index (204K+ indexed agents)."
        ),
        "function": _check,
    }
