"""
NerqPreflight + NerqSearch — LangChain tools for agent trust and discovery.
"""

from typing import Type

import requests
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field

NERQ_API = "https://nerq.ai"
NERQ_TIMEOUT = 10.0


# ── NerqPreflight ────────────────────────────────────────────

class NerqPreflightInput(BaseModel):
    agent_name: str = Field(
        description="Name of the AI agent or tool to check (e.g. 'SWE-agent', 'strudel-mcp-server')"
    )


class NerqPreflight(BaseTool):
    """Check if an AI agent or tool is trustworthy before interacting with it.
    Returns trust score, grade, and PROCEED/CAUTION/DENY recommendation.
    Covers 204K+ agents. Free, no API key needed. Source: nerq.ai"""

    name: str = "nerq_preflight"
    description: str = (
        "Check if an AI agent or tool is trustworthy before interacting with it. "
        "Returns trust score (0-100), grade (A+ to D), and recommendation "
        "(PROCEED/CAUTION/DENY). Use this BEFORE delegating tasks to another agent "
        "or using an unfamiliar tool. Input: agent or tool name. "
        "Free, no API key needed."
    )
    args_schema: Type[BaseModel] = NerqPreflightInput
    api_base: str = NERQ_API

    def _run(self, agent_name: str) -> str:
        try:
            resp = requests.get(
                f"{self.api_base}/v1/preflight",
                params={"target": agent_name},
                timeout=NERQ_TIMEOUT,
            )
            resp.raise_for_status()
            d = resp.json()

            rec = d.get("recommendation", "UNKNOWN")
            lines = [
                f"Nerq Preflight: {d.get('target', agent_name)}",
                f"Recommendation: {rec}",
                f"Trust Score: {d.get('target_trust', 'N/A')}/100",
                f"Grade: {d.get('target_grade', 'N/A')}",
                f"Verified: {'Yes' if d.get('target_verified') else 'No'}",
                f"Category: {d.get('target_category', 'N/A')}",
                f"Source: {d.get('target_source', 'N/A')}",
                f"Risk Level: {d.get('interaction_risk', 'N/A')}",
            ]

            flags = d.get("compliance_flags", [])
            if flags:
                lines.append(f"Flags: {', '.join(flags)}")

            if rec == "DENY":
                lines.append("WARNING: This agent has low trust. Do not interact.")
            elif rec == "CAUTION":
                lines.append("CAUTION: Moderate trust. Proceed with care.")
            elif rec == "PROCEED":
                lines.append("This agent is trusted. Safe to interact.")
            else:
                lines.append("Agent not found in Nerq index.")

            return "\n".join(lines)

        except Exception as e:
            return f"Nerq API unavailable: {e}"

    async def _arun(self, agent_name: str) -> str:
        return self._run(agent_name)


# ── NerqSearch ───────────────────────────────────────────────

class NerqSearchInput(BaseModel):
    query: str = Field(
        description="What you need an agent for (e.g. 'code review', 'security scanning', 'data analysis')"
    )


class NerqSearch(BaseTool):
    """Find the best AI agent for a task from the Nerq index of 204K+ agents.
    Returns top 5 agents ranked by trust score. Free, no API key needed."""

    name: str = "nerq_search"
    description: str = (
        "Find the best AI agent or tool for a specific task. "
        "Searches 204K+ agents indexed by Nerq and returns the top 5 "
        "ranked by trust score. Input: describe what you need. "
        "Free, no API key needed."
    )
    args_schema: Type[BaseModel] = NerqSearchInput
    api_base: str = NERQ_API

    def _run(self, query: str) -> str:
        try:
            resp = requests.get(
                f"{self.api_base}/v1/agent/search",
                params={"q": query, "limit": 5, "min_trust": 50},
                timeout=NERQ_TIMEOUT,
            )
            resp.raise_for_status()
            data = resp.json()

            agents = data if isinstance(data, list) else data.get("results", data.get("agents", []))
            if not agents:
                return f"No agents found for '{query}'."

            lines = [f"Nerq Search: '{query}' — {len(agents)} results\n"]
            for i, a in enumerate(agents[:5], 1):
                name = a.get("name", "Unknown")
                trust = a.get("trust_score_v2") or a.get("trust_score") or a.get("quality_score", "N/A")
                cat = a.get("category", "")
                source = a.get("source", "")
                stars = a.get("stars", "")
                lines.append(
                    f"{i}. {name} — Trust: {trust}, "
                    f"Category: {cat}, Source: {source}"
                    + (f", Stars: {stars}" if stars else "")
                )

            return "\n".join(lines)

        except Exception as e:
            return f"Nerq API unavailable: {e}"

    async def _arun(self, query: str) -> str:
        return self._run(query)
