# Quick Start: Production Inbox Deployment

Get your production-grade Synqed inbox running in 5 minutes!

## 🚀 Automated Deployment (Easiest)

```bash
# Run automated deployment script
cd synqed-python
./scripts/deploy_production_inbox.sh
```

This script will:
- ✓ Check prerequisites
- ✓ Install dependencies
- ✓ Start Redis (via Docker)
- ✓ Create application files
- ✓ Initialize demo agents with keypairs
- ✓ Optionally install systemd service
- ✓ Start the server

## 📝 Manual Deployment (More Control)

### 1. Install Dependencies

```bash
pip install synqed cryptography>=41.0.0 redis>=5.0.0 httpx>=0.24.0 uvicorn
```

### 2. Start Redis

```bash
docker run -d -p 6379:6379 redis:7-alpine
```

### 3. Create Application

Create `main.py`:

```python
from fastapi import FastAPI
from synqed.agent_email.inbox import router
from synqed.agent_email.inbox.startup import create_lifespan

app = FastAPI(lifespan=create_lifespan("redis://localhost:6379"))
app.include_router(router)
```

### 4. Initialize Agents

```python
# init_agents.py
from synqed.agent_email.registry.api import get_registry
from synqed.agent_email.registry.models import AgentRegistryEntry
from synqed.agent_email.inbox import generate_keypair

registry = get_registry()
private_key, public_key = generate_keypair()

registry.register(AgentRegistryEntry(
    agent_id="agent://yourorg/agent1",
    email_like="agent1@yourorg",
    inbox_url="http://localhost:8000/v1/a2a/inbox",
    public_key=public_key,
))
```

### 5. Run

```bash
python init_agents.py
uvicorn main:app --host 0.0.0.0 --port 8000
```

## ✅ Verify Deployment

```bash
# Check health
curl http://localhost:8000/health

# View API docs
open http://localhost:8000/docs

# Check Redis
redis-cli ping
```

## 📤 Send First Message

```python
import httpx
from synqed.agent_email.inbox import sign_message

# Load keypair
import json
with open('keypairs.json') as f:
    keys = json.load(f)
    private_key = keys['agent://demo/alice']['private_key']

# Sign message
message = {
    "thread_id": "test-123",
    "role": "user",
    "content": "Hello!",
}

signature = sign_message(
    private_key_b64=private_key,
    sender="agent://demo/alice",
    recipient="agent://demo/bob",
    message=message,
    thread_id="test-123",
)

# Send
response = httpx.post(
    "http://localhost:8000/v1/a2a/inbox",
    json={
        "sender": "agent://demo/alice",
        "recipient": "agent://demo/bob",
        "message": message,
        "signature": signature,
    }
)

print(response.json())
# {"status": "accepted", "message_id": "...", "trace_id": "..."}
```

## 🎯 What's New in Production Version?

| Feature | Prototype | Production |
|---------|-----------|------------|
| **Delivery** | Synchronous | Async queue with retry |
| **Identity** | None | Ed25519 signatures |
| **Rate Limiting** | None | Per-sender + per-IP |
| **Tracing** | None | Distributed trace_id |
| **Reliability** | Best effort | Guaranteed delivery + DLQ |
| **Routing** | Local only | Local + remote forwarding |
| **Dependencies** | None | Redis + cryptography |

## 📚 Next Steps

- **Full deployment guide**: See [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md)
- **API reference**: See [inbox README](src/synqed/agent_email/inbox/README.md)
- **Working example**: Run [production_inbox_demo.py](examples/production_inbox_demo.py)
- **Migration guide**: Section in DEPLOYMENT_GUIDE.md

## 🏭 Production Deployment Options

### Single Server
```bash
uvicorn main:app --host 0.0.0.0 --port 8000
```

### Multi-Worker
```bash
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
```

### Docker
```bash
docker-compose up -d
```

### Kubernetes
```bash
kubectl apply -f deployment.yaml
```

See [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md) for detailed instructions.

## 🔒 Security Checklist

Before production:

- [ ] Redis secured with AUTH
- [ ] TLS enabled for Redis
- [ ] Keypairs in secrets manager (not files)
- [ ] HTTPS enforced for all inbox URLs
- [ ] Rate limits configured
- [ ] Application runs as non-root user
- [ ] Firewall rules configured
- [ ] Logging configured

## 🆘 Troubleshooting

**Issue**: Messages not processing

```bash
# Check Redis
redis-cli ping

# Check queue
redis-cli XLEN agent_inbox:agent://yourorg/agent1

# Check logs
tail -f /var/log/synqed.log
```

**Issue**: Signature verification failing

```python
# Verify sender is registered with correct public_key
from synqed.agent_email.registry.api import get_registry
registry = get_registry()
entry = registry.get_by_uri("agent://yourorg/agent1")
print(entry.public_key)
```

**Issue**: Rate limited

```bash
# Increase limits in .env
SENDER_RATE_LIMIT=200
IP_RATE_LIMIT=1000
```

## 📊 Monitoring

```python
# Check queue health
from synqed.agent_email.inbox import get_message_queue

queue = get_message_queue()
await queue.connect()

pending = await queue.get_queue_length("agent://yourorg/agent1")
dlq = await queue.get_dlq_length("agent://yourorg/agent1")

print(f"Pending: {pending}, DLQ: {dlq}")
```

## 🎓 Learn More

- **Key concepts**: Crypto identity, queue-based delivery, distributed tracing
- **Architecture**: Validate → Sign → Queue → Worker → Deliver
- **Components**: 
  - `crypto.py`: Ed25519 signatures
  - `queue.py`: Redis Streams
  - `rate_limiter.py`: Abuse protection
  - `worker.py`: Async processing
  - `api.py`: Inbox endpoint

---

**Ready to go! 🚀**

For questions or issues, see [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md) or check the logs.

