"""
Vaultfire Agent Trust SDK — Python Example

Uses the Vaultfire REST API to verify trust, check reputation,
and interact with the Vaultfire Protocol. No blockchain node required.

API Base: https://theloopbreaker.com/api/agent/v1
"""

import requests
import json
from typing import Optional

VAULTFIRE_API = "https://theloopbreaker.com/api/agent/v1"


def verify_trust(address: str, chain: str = "base") -> dict:
    """Verify the full trust profile of any address on Vaultfire Protocol."""
    response = requests.post(
        f"{VAULTFIRE_API}/verify",
        json={"address": address, "chain": chain},
        headers={"Content-Type": "application/json"},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


def get_reputation(address: str, chain: str = "base") -> dict:
    """Get reputation score and accountability history for an address."""
    response = requests.get(
        f"{VAULTFIRE_API}/reputation/{address}",
        params={"chain": chain},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


def check_bond(agent: str, partner: str, chain: str = "base") -> dict:
    """Check if two addresses have an active partnership bond."""
    response = requests.post(
        f"{VAULTFIRE_API}/bond",
        json={"agentAddress": agent, "partnerAddress": partner, "chain": chain},
        headers={"Content-Type": "application/json"},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


def submit_attestation(
    agent_address: str,
    attestation_type: str,
    content: str,
    chain: str = "base",
    confidence: float = 0.8,
) -> dict:
    """Submit an on-chain attestation. Returns transaction data for signing."""
    response = requests.post(
        f"{VAULTFIRE_API}/attest",
        json={
            "agentAddress": agent_address,
            "attestationType": attestation_type,
            "content": content,
            "confidence": confidence,
            "chain": chain,
        },
        headers={"Content-Type": "application/json"},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


def mcp_call(tool_name: str, arguments: dict) -> dict:
    """Call a Vaultfire MCP tool directly."""
    response = requests.post(
        "https://theloopbreaker.com/api/mcp",
        json={
            "jsonrpc": "2.0",
            "method": "tools/call",
            "params": {"name": tool_name, "arguments": arguments},
            "id": 1,
        },
        headers={"Content-Type": "application/json"},
        timeout=15,
    )
    response.raise_for_status()
    return response.json()


# ── Example Usage ──

if __name__ == "__main__":
    # Verify trust profile
    print("=== Verify Trust ===")
    trust = verify_trust("0xfA15Ee28939B222B0448261A22156070f0A7813C", "base")
    if trust.get("success"):
        data = trust["data"]
        print(f"  Trust Grade: {data.get('trustGrade', 'N/A')}")
        print(f"  Reputation:  {data.get('reputationScore', 0)}/100")
        print(f"  Bonded:      {data.get('isBonded', False)}")
        print(f"  VNS Name:    {data.get('vnsName', 'None')}")
    else:
        print(f"  Error: {trust.get('error', 'Unknown')}")

    # Get reputation
    print("\n=== Reputation ===")
    rep = get_reputation("0xfA15Ee28939B222B0448261A22156070f0A7813C", "base")
    if rep.get("success"):
        data = rep["data"]
        print(f"  Score: {data.get('score', 0)}")
        print(f"  Tier:  {data.get('tier', 'unverified')}")

    # MCP tool call
    print("\n=== MCP: Protocol Status ===")
    status = mcp_call("vaultfire_protocol_status", {})
    print(f"  Response: {json.dumps(status.get('result', {}), indent=2)[:200]}...")
