"""SDK Integration Examples — How to add memory to any project.

The Memory SDK provides 5 methods: save, search, update, delete, status.
Zero config, 3 lines to integrate.
"""

from agent_memory import Memory


def example_basic():
    """Basic usage — zero config."""
    mem = Memory()

    # Save
    mid = mem.save("Meeting with Alice at 3pm tomorrow")
    print(f"Saved: {mid}")

    # Search
    results = mem.search("meeting Alice")
    for r in results:
        print(f"  [{r['memory_id']}] {r['content']}")

    # Update
    mem.update(mid, "Meeting with Alice at 4pm tomorrow")

    # Delete
    mem.delete(mid)

    # Status
    status = mem.status()
    print(f"Health: {status['status']}, Memories: {status.get('stats', {}).get('total_memories', '?')}")

    mem.close()


def example_chatbot():
    """ChatBot with memory."""
    mem = Memory()

    def chat(user_input):
        # Recall relevant context
        context = mem.search(user_input, limit=3)
        context_text = "\n".join(r["content"] for r in context)

        # Generate response (replace with your LLM)
        reply = f"Based on what I remember: {context_text}\nResponse to: {user_input}"

        # Remember this conversation
        mem.save(f"User: {user_input}\nAssistant: {reply}")

        return reply

    # Simulate conversation
    chat("My name is Alice")
    chat("I work on Python projects")
    reply = chat("What do you know about me?")
    print(reply)

    mem.close()


def example_with_context_manager():
    """Using context manager for automatic cleanup."""
    with Memory() as mem:
        mem.save("This memory is automatically cleaned up")
        results = mem.search("memory")
        print(f"Found {len(results)} results")


def example_multi_project():
    """Separate memory for different projects."""
    project_a = Memory(db_path="~/.agent_memory/project_a.db", agent_id="project_a")
    project_b = Memory(db_path="~/.agent_memory/project_b.db", agent_id="project_b")

    project_a.save("Project A: Deployed v1.0")
    project_b.save("Project B: Fixed bug #42")

    # Project A only sees its own memories
    results_a = project_a.search("deploy")
    print(f"Project A found: {len(results_a)} results")

    project_a.close()
    project_b.close()


def example_remote_server():
    """Connect to a remote Agent Memory server."""
    # Start server first: agent-memory serve
    mem = Memory(server="http://localhost:8000", api_key="<YOUR_API_KEY>")

    mid = mem.save("Remote memory")
    results = mem.search("remote")
    print(f"Found {len(results)} results from remote server")


if __name__ == "__main__":
    print("=== Basic ===")
    example_basic()

    print("\n=== ChatBot ===")
    example_chatbot()

    print("\n=== Context Manager ===")
    example_with_context_manager()
