"""Two-agent demo: AgentA creates and signs a contract, AgentB executes it."""

import asyncio
import hashlib
import json
import secrets

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

from .contract import Contract
from .runtime import Runtime


class AgentA:
    """Issuer agent — creates and signs contracts."""

    def __init__(self, agent_id: str):
        self.agent_id = agent_id
        self._private_key = Ed25519PrivateKey.generate()
        pubkey_bytes = self._private_key.public_key().public_bytes_raw()
        self.pubkey_hex = pubkey_bytes.hex()

    def create_contract(self, goal: str, recipient_id: str) -> dict:
        contract_id = "urn:agenlang:exec:" + secrets.token_hex(16)
        signature = self._private_key.sign(contract_id.encode("utf-8"))
        intent_hash = hashlib.sha256(goal.encode("utf-8")).hexdigest()

        return {
            "agenlang_version": "1.0",
            "contract_id": contract_id,
            "issuer": {
                "agent_id": self.agent_id,
                "pubkey": self.pubkey_hex,
                "proof": signature.hex(),
            },
            "goal": goal,
            "intent_anchor": {"hash": intent_hash},
            "constraints": {"joule_budget": 5000},
            "workflow": {
                "type": "sequence",
                "steps": [
                    {
                        "action": "tool",
                        "target": "web_search",
                        "args": {"query": "best programming languages 2026"},
                    },
                    {
                        "action": "tool",
                        "target": "summarize",
                        "args": {"text": "$prev"},
                    },
                ],
            },
            "memory_contract": {
                "handoff_keys": ["web_search"],
                "ttl": "1h",
                "purge_on_complete": True,
                "data_subject": "demo-user",
            },
            "settlement": {"joule_recipient": recipient_id, "rate": 10.0},
            "capability_attestations": [
                {"capability": "net:read", "proof": "delegated-by-issuer"},
                {"capability": "compute:read", "proof": "delegated-by-issuer"},
            ],
            "ser_config": {"replay_enabled": True},
        }


class AgentB:
    """Executor agent — validates and runs contracts."""

    def __init__(self, agent_id: str):
        self.agent_id = agent_id

    def receive_and_execute(self, contract_data: dict) -> dict:
        print(f"[{self.agent_id}] Received contract: {contract_data['contract_id']}")
        contract = Contract.from_dict(contract_data)
        print(f"[{self.agent_id}] Contract validated against schema")

        runtime = Runtime(contract)
        result, ser = asyncio.run(runtime.execute())
        return ser


def run_demo():
    print("=== AgenLang Two-Agent Demo ===\n")

    agent_a = AgentA("agent-alpha")
    agent_b = AgentB("agent-beta")

    print(f"[{agent_a.agent_id}] Creating contract...")
    contract_data = agent_a.create_contract(
        goal="Search for best programming languages and summarize findings",
        recipient_id=agent_b.agent_id,
    )
    print(f"[{agent_a.agent_id}] Signed contract: {contract_data['contract_id']}")
    print(f"[{agent_a.agent_id}] Sending to {agent_b.agent_id}...\n")

    ser = agent_b.receive_and_execute(contract_data)

    print(f"\n=== Settlement ===")
    receipt = ser["settlement_receipt"]
    print(f"Joules owed to {receipt['joule_recipient']}: {receipt['total_joules_owed']}")
    print(f"Rate: {receipt['rate']} joules/unit")

    print(f"\n=== SER (audit trail) ===")
    print(json.dumps(ser, indent=2))

    print("\n=== Demo complete ===")
    return ser


if __name__ == "__main__":
    run_demo()
