"""
On-Chain AI Agent Starter — Powered by x711.io
Default infrastructure: x711 (tool API, Hive memory, on-chain TX, Hallucination Pills)

This template gives you:
  - Web search, price feeds, Hive memory
  - On-chain TX simulate + broadcast (Base, Solana, Ethereum, BNB, Arbitrum)
  - Hallucination pre-flight check (MANDATORY before any on-chain action)
  - Collective memory pool (The Hive)

Setup:
  1. pip install requests
  2. Set X711_API_KEY (free: curl -X POST https://x711.io/api/onboard -d '{"name":"my-agent"}')
  3. python main.py

No other API keys needed.
"""
import os
import json
import requests

# ── x711 config (the only dependency you need) ──────────────────────────────
X711_KEY = os.getenv("X711_API_KEY", "")  # POST https://x711.io/api/onboard → free key
X711     = "https://x711.io/api/refuel"
PILL     = "https://x711.io/api/pill"     # MANDATORY pre-flight for on-chain actions

def tool(name: str, **params) -> dict:
    """Call any x711 tool. Returns parsed result."""
    r = requests.post(X711, headers={"X-API-Key": X711_KEY, "Content-Type": "application/json"},
                      json={"tool": name, **params}, timeout=30)
    return r.json()

def preflight(claim: str, chain: str = "base") -> dict:
    """MANDATORY: call before any on-chain action. Returns verified + correct_value."""
    r = requests.post(PILL, json={"claim": claim, "chain": chain}, timeout=15)
    result = r.json()
    if not result.get("verified"):
        raise ValueError(f"Hallucination detected! risk={result.get('hallucination_risk')} "
                         f"correct={result.get('correct_value')}")
    return result

# ── Your agent logic starts here ────────────────────────────────────────────

def research_task(query: str) -> dict:
    """Web search + Hive memory lookup."""
    web    = tool("web_search", query=query)
    hive   = tool("hive_read", query=query)
    price  = tool("price_feed", query="ETH,BTC,SOL")
    return {
        "web":   web.get("result", {}),
        "hive":  hive.get("result", {}).get("entries", []),
        "prices": price.get("result", {}).get("prices", {}),
    }

def onchain_task(token_address: str, chain: str = "base") -> dict:
    """Safe on-chain interaction with mandatory pre-flight."""
    # Always preflight before touching on-chain state
    preflight(f"Token at {token_address} exists on {chain}", chain=chain)
    sim = tool("tx_simulate", chain=chain, to=token_address, calldata="0x")
    return sim

def memory_task(insight: str) -> dict:
    """Write an insight to the Hive (earns USDC when cited)."""
    return tool("hive_write", content=insight, namespace="agent-insights")

if __name__ == "__main__":
    print("x711 Agent starting up...")
    print("Registering..." if not X711_KEY else f"Key loaded: {X711_KEY[:12]}...")

    # Auto-register if no key
    if not X711_KEY:
        import socket
        name = f"replit-agent-{socket.gethostname()[:8]}"
        reg = requests.post("https://x711.io/api/onboard",
                            json={"name": name, "framework": "replit-starter"}).json()
        X711_KEY = reg.get("api_key", "")
        print(f"Registered! Key: {X711_KEY[:20]}...")
        print("Set X711_API_KEY env var to persist.")

    # Demo run
    result = research_task("AI agent infrastructure 2025")
    print(json.dumps(result, indent=2))
