#!/usr/bin/env python3
"""
Synapse Layer Cookbook — 05: Secure Agent Handover with Audit Trail
https://synapselayer.org/docs

Demonstrates Secure Agent Handover (V2):
- Agent A completes a task and initiates handover
- Synapse generates a single-use SHA-256 token
- Context is encrypted with AES-256-GCM in transit
- Agent B receives and decrypts the full context
- Audit trail records the entire chain

Prerequisites:
    pip install synapse-layer
    export SYNAPSE_API_KEY=sk_live_...
"""

from synapse_layer import SynapseClient
import os
import json

client = SynapseClient(api_key=os.environ["SYNAPSE_API_KEY"])


def agent_a_sales():
    """Agent A: Sales Agent — qualifies lead and initiates handover."""
    print("=== STEP 1: Agent A (Sales) qualifies the lead ===")

    # Store context during the sales conversation
    client.store(
        content="Lead: Jane Smith, CTO at TechCorp. "
                "Interested in Pro plan. Budget approved for Q3.",
        agent="sales-agent",
        memory_type="lead",
        tags=["sales", "qualified"],
    )

    # Initiate secure handover to support agent
    print("\n=== STEP 2: Initiating Secure Handover (V2) ===")
    handover = client.handover(
        from_agent="sales-agent",
        to_agent="support-agent",
        context="Qualified lead: Jane Smith (CTO, TechCorp). "
                "Wants Pro plan. Needs onboarding call this week. "
                "Prefers async communication via email.",
    )

    print(f"Handover ID: {handover.handover_id}")
    print(f"Token: {handover.token[:16]}... (SHA-256, single-use)")
    print(f"Status: {handover.status}")
    return handover


def agent_b_support(handover_result):
    """Agent B: Support Agent — receives handover with full context."""
    print("\n=== STEP 3: Agent B (Support) receives the handover ===")

    # In production, Agent B would use the handover token to
    # retrieve the encrypted context. The token is single-use
    # and verified via SHA-256.
    print(f"Received handover: {handover_result.handover_id}")
    print(f"From: {handover_result.audit_trail['from_agent']}")
    print(f"To: {handover_result.audit_trail['to_agent']}")
    print(f"Timestamp: {handover_result.audit_trail['timestamp']}")

    # Agent B can also recall memories stored by Agent A
    memories = client.recall(
        query="What do we know about Jane Smith at TechCorp?",
        limit=5,
        min_tq=0.6,
    )
    print(f"\nRecalled {len(memories)} memories from sales-agent:")
    for m in memories:
        print(f"  [{m.agent}] [TQ:{m.trust_quotient:.2f}] {m.content}")


def print_audit_trail(handover_result):
    """Display the complete audit trail."""
    print("\n=== AUDIT TRAIL ===")
    trail = handover_result.audit_trail
    print(json.dumps(trail, indent=2, default=str))
    print("\nAll handover events are logged with:")
    print("  - Timestamp (ISO 8601)")
    print("  - Agent identifiers (from/to)")
    print("  - Handover ID for traceability")
    print("  - Encryption: AES-256-GCM in transit")
    print("  - Token: SHA-256, single-use, non-replayable")


if __name__ == "__main__":
    result = agent_a_sales()
    agent_b_support(result)
    print_audit_trail(result)


"""
Expected output:
    === STEP 1: Agent A (Sales) qualifies the lead ===

    === STEP 2: Initiating Secure Handover (V2) ===
    Handover ID: hnd_7f3a9b2c
    Token: sha256_e8f2a1b3... (SHA-256, single-use)
    Status: completed

    === STEP 3: Agent B (Support) receives the handover ===
    Received handover: hnd_7f3a9b2c
    From: sales-agent
    To: support-agent
    Timestamp: 2026-06-22T14:30:00Z

    Recalled 1 memories from sales-agent:
      [sales-agent] [TQ:0.94] Lead: Jane Smith, CTO at TechCorp. Interested in Pro plan. Budget approved for Q3.

    === AUDIT TRAIL ===
    {
      "from_agent": "sales-agent",
      "to_agent": "support-agent",
      "timestamp": "2026-06-22T14:30:00Z"
    }

    All handover events are logged with:
      - Timestamp (ISO 8601)
      - Agent identifiers (from/to)
      - Handover ID for traceability
      - Encryption: AES-256-GCM in transit
      - Token: SHA-256, single-use, non-replayable
"""
