#!/usr/bin/env python3
"""
Genesis Protocol - Letta Memory Setup
Creates shared memory block and agent for Genesis system
"""

from letta_client import Letta
import sys
import json

try:
    # Connect to Letta server (local)
    print("Connecting to Letta server...")
    client = Letta(base_url="http://localhost:8283")

    # Create a shared memory block that both Claude instances can access
    print("Creating Genesis shared memory block...")
    genesis_block = client.blocks.create(
        label="genesis_shared_memory",
        value="Genesis Protocol Active. Progenitors: Kinan, Claude Desktop, Claude Code."
    )

    print(f"✓ Genesis Memory Block created")
    print(f"  Block ID: {genesis_block.id}")
    print(f"  Label: {genesis_block.label}")

    # Create the Genesis agent with required LLM config
    print("\nCreating Genesis agent...")
    from letta import LLMConfig, EmbeddingConfig

    genesis_agent = client.agents.create(
        name="genesis-prime",
        description="Genesis Protocol - Shared memory coordinator for Claude instances",
        llm_config=LLMConfig(
            model="gpt-4",
            model_endpoint_type="openai",
            model_endpoint="https://api.openai.com/v1",
            context_window=8192
        ),
        embedding_config=EmbeddingConfig(
            embedding_model="text-embedding-ada-002",
            embedding_endpoint_type="openai",
            embedding_endpoint="https://api.openai.com/v1",
            embedding_dim=1536
        )
    )

    print(f"✓ Genesis Agent created")
    print(f"  Agent ID: {genesis_agent.id}")
    print(f"  Agent Name: {genesis_agent.name}")

    # Attach the memory block to the agent
    print(f"\nAttaching memory block to agent...")
    try:
        client.agents.attach_block(agent_id=genesis_agent.id, block_id=genesis_block.id)
        print(f"✓ Memory block attached to agent")
    except Exception as e:
        print(f"  Note: Memory block attachment: {e}")

    # Save IDs to a JSON file for easy access
    result = {
        "memory_block_id": genesis_block.id,
        "agent_id": genesis_agent.id,
        "status": "success"
    }

    with open("/mnt/e/genesis-system/genesis_ids.json", "w") as f:
        json.dump(result, f, indent=2)

    print("\n✓ Configuration saved to genesis_ids.json")
    print("\nGenesis Protocol memory layer is now active!")

except Exception as e:
    print(f"✗ Error: {e}", file=sys.stderr)
    result = {
        "status": "error",
        "error": str(e)
    }
    with open("/mnt/e/genesis-system/genesis_ids.json", "w") as f:
        json.dump(result, f, indent=2)
    sys.exit(1)
