# VibeDB Usage Examples

Copy-paste ready code for common scenarios.

## Key-Value Store

```python
from vibedb import VibeDB

db = VibeDB("config.db")
kv = db.collection("config")

def set_config(key, value):
    kv.upsert({"key": key}, {"key": key, "value": value})

def get_config(key, default=None):
    doc = kv.find_one({"key": key})
    return doc["value"] if doc else default

# Usage
set_config("api_url", "https://api.example.com")
set_config("max_retries", 3)

api_url = get_config("api_url")
timeout = get_config("timeout", default=30)
```

## Session Management

```python
import time
from vibedb import VibeDB

db = VibeDB("sessions.db")
sessions = db.collection("sessions")
sessions.create_index(["session_id"], unique=True)

def create_session(user_id, data, ttl_seconds=3600):
    session_id = f"sess_{int(time.time())}_{user_id}"
    sessions.insert({
        "session_id": session_id,
        "user_id": user_id,
        "data": data,
        "expires_at": int(time.time()) + ttl_seconds
    })
    return session_id

def get_session(session_id):
    session = sessions.find_one({"session_id": session_id})
    if not session:
        return None
    if session["expires_at"] < time.time():
        sessions.delete(session["_id"])
        return None
    return session["data"]

def cleanup_expired():
    now = int(time.time())
    return sessions.delete_many({"expires_at": {"$lt": now}})

# Usage
sid = create_session("user123", {"cart": [1, 2, 3]})
data = get_session(sid)
cleanup_expired()
```

## Event Logging

```python
import time
from vibedb import VibeDB, Q

db = VibeDB("events.db")
events = db.collection("events")
events.create_index(["timestamp"])
events.create_index(["user_id"])

def log_event(event_type, user_id, data):
    events.insert({
        "type": event_type,
        "user_id": user_id,
        "data": data,
        "timestamp": int(time.time())
    })

def get_user_events(user_id, limit=50):
    return events.find({"user_id": user_id}) \
        .sort("timestamp", -1) \
        .limit(limit) \
        .to_list()

def get_recent_events(minutes=60):
    cutoff = int(time.time()) - (minutes * 60)
    return events.find(Q.gte("timestamp", cutoff)) \
        .sort("timestamp", -1) \
        .to_list()

# Usage
log_event("login", "user123", {"ip": "192.168.1.1"})
log_event("purchase", "user123", {"item": "prod-456", "amount": 99.99})

user_history = get_user_events("user123")
recent = get_recent_events(minutes=30)
```

## Cache with TTL

```python
import time
from vibedb import VibeDB, Q

db = VibeDB(":memory:")
cache = db.collection("cache")
cache.create_index(["key"], unique=True)

def cache_set(key, value, ttl_seconds=300):
    expires_at = int(time.time()) + ttl_seconds
    cache.upsert(
        {"key": key},
        {"key": key, "value": value, "expires_at": expires_at}
    )

def cache_get(key):
    doc = cache.find_one({"key": key})
    if not doc:
        return None
    if doc["expires_at"] < time.time():
        cache.delete(doc["_id"])
        return None
    return doc["value"]

def cache_clear_expired():
    now = int(time.time())
    return cache.delete_many(Q.lt("expires_at", now))

# Usage
cache_set("user:123", {"name": "Alice"}, ttl_seconds=600)
user_data = cache_get("user:123")
cache_clear_expired()
```

## Agent State Persistence

```python
from vibedb import VibeDB

db = VibeDB("agent_state.db")
state = db.collection("state")
state.create_index(["agent_id"], unique=True)

class AgentState:
    def __init__(self, agent_id):
        self.agent_id = agent_id

    def save(self, data):
        state.upsert(
            {"agent_id": self.agent_id},
            {"agent_id": self.agent_id, "data": data}
        )

    def load(self):
        doc = state.find_one({"agent_id": self.agent_id})
        return doc["data"] if doc else {}

    def update(self, updates):
        current = self.load()
        current.update(updates)
        self.save(current)

    def clear(self):
        doc = state.find_one({"agent_id": self.agent_id})
        if doc:
            state.delete(doc["_id"])

# Usage
agent = AgentState("agent-001")

agent.save({
    "conversation_id": "conv-123",
    "context": {"topic": "weather", "location": "NYC"},
    "memory": ["user asked about weather"]
})

data = agent.load()
agent.update({"context": {"topic": "news"}})
agent.clear()
```

## Job Queue

```python
import time
from vibedb import VibeDB

db = VibeDB("jobs.db")
jobs = db.collection("jobs")
jobs.create_index(["status"])
jobs.create_index(["priority"])

def enqueue_job(job_type, data, priority=5):
    jobs.insert({
        "type": job_type,
        "data": data,
        "status": "pending",
        "priority": priority,
        "attempts": 0,
        "max_attempts": 3,
        "created_at": int(time.time())
    })

def get_next_job():
    job = jobs.find({"status": "pending"}) \
        .sort("priority", -1) \
        .sort("created_at", 1) \
        .first()

    if job:
        jobs.update(job["_id"], {"status": "processing"})
    return job

def complete_job(job_id):
    jobs.update(job_id, {"status": "completed"})

def fail_job(job_id, error):
    job = jobs.get(job_id)
    attempts = job["attempts"] + 1

    if attempts >= job["max_attempts"]:
        jobs.update(job_id, {
            "status": "failed",
            "attempts": attempts,
            "error": error
        })
    else:
        jobs.update(job_id, {
            "status": "pending",
            "attempts": attempts,
            "last_error": error
        })

# Usage
enqueue_job("send_email", {"to": "user@example.com"}, priority=8)

job = get_next_job()
if job:
    try:
        # Process job
        complete_job(job["_id"])
    except Exception as e:
        fail_job(job["_id"], str(e))
```

## Pagination Helper

```python
def paginate(collection, query={}, page=1, per_page=20, sort_field=None, sort_dir=1):
    skip = (page - 1) * per_page

    cursor = collection.find(query)

    if sort_field:
        cursor = cursor.sort(sort_field, sort_dir)

    results = cursor.skip(skip).limit(per_page).to_list()
    total = collection.count(query)

    return {
        "items": results,
        "page": page,
        "per_page": per_page,
        "total": total,
        "pages": (total + per_page - 1) // per_page
    }

# Usage
page1 = paginate(users, query={"status": "active"}, page=1, per_page=10)
print(f"Showing {len(page1['items'])} of {page1['total']} items")
```

## Soft Delete

```python
import time
from vibedb import VibeDB, Q

db = VibeDB("app.db")
users = db.collection("users")
users.create_index(["deleted_at"])

def soft_delete(user_id):
    users.update(user_id, {"deleted_at": int(time.time())})

def find_active():
    return users.find(Q.exists("deleted_at", False)).to_list()

def restore(user_id):
    users.update(user_id, {"deleted_at": None})

def hard_delete_old(days=30):
    cutoff = int(time.time()) - (days * 86400)
    return users.delete_many(Q.lt("deleted_at", cutoff))

# Usage
soft_delete(user_id)
active_users = find_active()
restore(user_id)
hard_delete_old(days=90)
```
