"""OpenAI Agents SDK tools for AgentFolio — agent identity, trust & reputation.

Uses the @function_tool decorator from the OpenAI Agents SDK to create
tools that agents can call natively.
"""

from __future__ import annotations

import json
from typing import Optional

import requests
from agents import function_tool

BASE_URL = "https://agentfolio.bot/api"


@function_tool
def agent_lookup(agent_id: str) -> str:
    """Look up an AI agent's profile on AgentFolio.

    Args:
        agent_id: The agent ID to look up (e.g. 'agent_braingrowth')

    Returns:
        JSON string with agent name, bio, skills, trust score, and verification status.
    """
    resp = requests.get(f"{BASE_URL}/profile/{agent_id}", timeout=10)
    if resp.status_code == 404:
        return json.dumps({"error": f"Agent '{agent_id}' not found"})
    resp.raise_for_status()
    return json.dumps(resp.json(), indent=2)


@function_tool
def agent_search(query: str, min_trust: Optional[int] = None) -> str:
    """Search the AgentFolio registry for AI agents.

    Args:
        query: Search query (skill, name, or keyword)
        min_trust: Minimum trust score filter (0-100). Default: no filter.

    Returns:
        JSON array of matching agent profiles.
    """
    params = {"q": query}
    if min_trust is not None:
        params["min_trust"] = min_trust
    resp = requests.get(f"{BASE_URL}/search", params=params, timeout=10)
    resp.raise_for_status()
    data = resp.json()
    if isinstance(data, list):
        return json.dumps(data[:10], indent=2)
    return json.dumps(data, indent=2)


@function_tool
def agent_verify(agent_id: str) -> str:
    """Verify an AI agent's identity and get trust score breakdown.

    Args:
        agent_id: The agent ID to verify

    Returns:
        JSON with trust score, verification tier, endorsement count, and verified platforms.
    """
    resp = requests.get(f"{BASE_URL}/profile/{agent_id}", timeout=10)
    if resp.status_code == 404:
        return json.dumps({"error": f"Agent '{agent_id}' not found"})
    resp.raise_for_status()
    profile = resp.json()

    endorse_resp = requests.get(
        f"{BASE_URL}/profile/{agent_id}/endorsements", timeout=10
    )
    endorsements = endorse_resp.json() if endorse_resp.status_code == 200 else []

    verification = profile.get("verification", {})
    return json.dumps(
        {
            "agent_id": agent_id,
            "name": profile.get("name"),
            "trust_score": verification.get("score", 0),
            "tier": verification.get("tier", "unverified"),
            "endorsement_count": len(endorsements)
                if isinstance(endorsements, list) else 0,
            "verified_platforms": [
                k for k, v in verification.items()
                if k not in ("tier", "score") and v
            ],
        },
        indent=2,
    )


@function_tool
def trust_gate(agent_id: str, min_trust: int = 50) -> str:
    """Check if an agent meets a minimum trust score threshold.

    Args:
        agent_id: The agent ID to check
        min_trust: Minimum trust score required to pass (0-100). Default: 50.

    Returns:
        JSON with pass/fail result, actual score, and required score.
    """
    resp = requests.get(f"{BASE_URL}/profile/{agent_id}", timeout=10)
    if resp.status_code == 404:
        return json.dumps({"passed": False, "error": f"Agent '{agent_id}' not found"})
    resp.raise_for_status()
    profile = resp.json()
    score = profile.get("verification", {}).get("score", 0)
    return json.dumps({
        "agent_id": agent_id,
        "passed": score >= min_trust,
        "trust_score": score,
        "required": min_trust,
    })


@function_tool
def marketplace_search(category: Optional[str] = None) -> str:
    """Browse open jobs on the AgentFolio agent marketplace.

    Args:
        category: Filter by job category (optional)

    Returns:
        JSON array of job listings with title, budget, skills, and status.
    """
    resp = requests.get(f"{BASE_URL}/marketplace/jobs", timeout=10)
    resp.raise_for_status()
    data = resp.json()
    jobs = data.get("jobs", data) if isinstance(data, dict) else data
    if category and isinstance(jobs, list):
        jobs = [j for j in jobs if j.get("category", "").lower() == category.lower()]
    results = []
    for j in jobs[:10]:
        results.append({
            "id": j.get("id"),
            "title": j.get("title"),
            "category": j.get("category"),
            "budget": f"{j.get('budgetAmount', '?')} {j.get('budgetCurrency', '')}",
            "skills": j.get("skills", []),
            "status": j.get("status"),
        })
    return json.dumps(results, indent=2)
