"""
AiGentsy + OpenAI Agents Starter — Proof creation via OpenAI function-calling.

Install:
    pip install openai httpx

Run:
    export OPENAI_API_KEY=sk-...
    python openai_agents_starter.py

No AiGentsy API key needed — stamp requires no signup.
"""

import json
import httpx

BASE = "https://aigentsy-ame-runtime.onrender.com"

# ── AiGentsy tool definitions for OpenAI function-calling ──

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "aigentsy_stamp",
            "description": "Create verifiable proof of delivered AI work. No signup needed.",
            "parameters": {
                "type": "object",
                "properties": {
                    "agent_id": {"type": "string", "description": "Agent identifier"},
                    "description": {"type": "string", "description": "What was delivered"},
                },
                "required": ["agent_id", "description"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "aigentsy_verify",
            "description": "Verify a proof bundle's cryptographic integrity.",
            "parameters": {
                "type": "object",
                "properties": {
                    "deal_id": {"type": "string", "description": "Deal ID to verify"},
                },
                "required": ["deal_id"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "aigentsy_export",
            "description": "Export a portable proof bundle for a deal.",
            "parameters": {
                "type": "object",
                "properties": {
                    "deal_id": {"type": "string", "description": "Deal ID to export"},
                },
                "required": ["deal_id"],
            },
        },
    },
]


def handle_tool_call(name: str, args: dict) -> dict:
    """Execute an AiGentsy tool call."""
    c = httpx.Client(base_url=BASE, timeout=30)

    if name == "aigentsy_stamp":
        return c.post("/protocol/stamp", json=args).json()
    elif name == "aigentsy_verify":
        return c.get(f"/proof/{args['deal_id']}/verify").json()
    elif name == "aigentsy_export":
        return c.get(f"/proof/{args['deal_id']}").json()
    else:
        return {"error": f"Unknown tool: {name}"}


def main():
    """Demo: create a proof and verify it using OpenAI function-calling tools."""
    # Direct tool usage (no LLM needed for this demo)
    print("1. Stamping proof...")
    stamp_result = handle_tool_call("aigentsy_stamp", {
        "agent_id": "openai_demo_agent",
        "description": "Completed quarterly market analysis report with 12 data visualizations",
    })
    print(f"   deal_id: {stamp_result.get('deal_id', 'N/A')}")

    deal_id = stamp_result.get("deal_id")
    if not deal_id:
        print("   Error: no deal_id returned")
        return 1

    print("2. Verifying proof...")
    verify_result = handle_tool_call("aigentsy_verify", {"deal_id": deal_id})
    verified = verify_result.get("verified") or verify_result.get("chain_integrity")
    print(f"   verified: {verified}")

    print("3. Exporting bundle...")
    bundle = handle_tool_call("aigentsy_export", {"deal_id": deal_id})
    proof_count = len(bundle.get("proof_bundle", {}).get("proofs", []))
    event_count = len(bundle.get("proof_bundle", {}).get("events", []))
    print(f"   proofs: {proof_count}, events: {event_count}")

    print()
    print("=" * 50)
    print(f"  deal_id:  {deal_id}")
    print(f"  verified: {verified}")
    print(f"  bundle:   {proof_count} proofs, {event_count} events")
    print("=" * 50)
    print()
    print("These tools work with OpenAI's Responses API, Assistants API,")
    print("and Chat Completions. Pass TOOLS to your model and handle")
    print("function_call responses with handle_tool_call().")
    print()
    print("Docs: https://aigentsy.com/integrations#openai")

    return 0 if verified else 1


if __name__ == "__main__":
    raise SystemExit(main())
