# Styrene TUI - Quick Start Guide

Get up and running with LXMF messaging and device management in 5 minutes.

---

## 🚀 Installation (2 minutes)

```bash
# Clone and setup
git clone https://github.com/styrene/styrene-tui.git
cd styrene-tui

# Create virtual environment
python3.11 -m venv .venv
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt
pip install -e .

# Verify installation
python -m pytest tests/ -v --tb=no | tail -5
```

**Expected output:** `XX passed in X.XXs`

---

## 💬 Send Your First Message (1 minute)

```python
from styrene.protocols.chat import ChatProtocol
from styrene.services.lxmf_service import LXMFService

# Initialize
lxmf = LXMFService()
chat = ChatProtocol(router=lxmf, identity=lxmf.identity)

# Get your identity hash
print(f"My identity: {lxmf.identity.hexhash}")
# Share this with contacts so they can message you!

# Send message
await chat.send_message(
    destination="<recipient_identity_hash>",
    content="Hello from Styrene!"
)

print("Message sent!")
```

**Pro tip:** Get recipient's identity hash by asking them to run `rnstatus` on their device.

---

## 🖥️ Manage a Remote Device (2 minutes)

### Step 1: Setup RPC Server (on remote device)

```bash
# On the NixOS device you want to manage
pip install -e packages/styrene-bond-rpc/

# Create auth config
mkdir -p ~/.config/styrene-bond-rpc
cat > ~/.config/styrene-bond-rpc/auth.yaml <<EOF
identities:
  - hash: "<YOUR_CLIENT_IDENTITY_HASH>"
    name: "My Admin User"
    permissions: ["status", "exec", "reboot", "update_config"]
EOF

# Install and start systemd service
sudo cp packages/styrene-bond-rpc/systemd/styrene-bond-rpc.service /etc/systemd/system/
sudo systemctl enable --now styrene-bond-rpc

# Verify
sudo systemctl status styrene-bond-rpc
```

**Get your client identity hash:**
```bash
# On your client machine (where you'll send commands FROM)
python -c "from styrene.services.lxmf_service import LXMFService; print(LXMFService().identity.hexhash)"
```

### Step 2: Send Commands from Client

```python
from styrene.services.rpc_client import RPCClient
from styrene.services.lxmf_service import LXMFService

# Initialize
lxmf = LXMFService()
rpc = RPCClient(lxmf)

device_hash = "<REMOTE_DEVICE_IDENTITY_HASH>"

# Get device status
status = await rpc.call_status(device_hash)
print(f"✓ Device at {status.ip}, uptime {status.uptime}s")

# Execute command
result = await rpc.call_exec(device_hash, "systemctl", ["status", "reticulum"])
print(f"✓ Command exit code: {result.exit_code}")
print(result.stdout)

# Reboot in 5 minutes
reboot = await rpc.call_reboot(device_hash, delay=300)
print(f"✓ {reboot.message}")

# Update config
config = await rpc.call_update_config(device_hash, {"log_level": "DEBUG"})
print(f"✓ Updated: {config.updated_keys}")
```

**Get remote device identity hash:**
```bash
# On the remote device
rnstatus  # Look for: Identity: <abc123...>
```

---

## 🎨 Launch the TUI

```bash
# Run the application
python -m styrene

# Or in development mode with hot reload
textual run --dev src/styrene/app.py
```

**Navigate the TUI:**
- `Tab` / `Shift+Tab` - Move between widgets
- `Enter` - Select/activate
- `Escape` - Go back
- `Ctrl+L` - Clear (context-dependent)
- `Ctrl+C` - Quit

---

## 🔍 Common Commands Cheat Sheet

### Chat

```python
# Send message
await chat.send_message(dest_hash, "Hello!")

# Query messages from database
from styrene.models import get_session, Message
session = get_session()
messages = session.query(Message).filter_by(conversation_id=conv_id).all()
```

### RPC

```python
# Status query
status = await rpc.call_status(device_hash)

# Execute command
result = await rpc.call_exec(device_hash, "command", ["arg1", "arg2"])

# Reboot (immediate)
await rpc.call_reboot(device_hash, delay=0)

# Reboot (in 10 minutes)
await rpc.call_reboot(device_hash, delay=600)

# Update config
await rpc.call_update_config(device_hash, {"key": "value"})

# Adjust timeout for slow networks
rpc.default_timeout = 60.0  # seconds
```

### Device Console (in TUI)

```
$ status                              # Query device info
$ exec systemctl status reticulum     # Run command
$ exec ps aux                         # List processes
$ reboot                              # Reboot now
$ reboot 300                          # Reboot in 5 min
$ update-config log_level DEBUG       # Update config
```

---

## 🐛 Troubleshooting

### "No response from device"

```bash
# Test reachability
rnprobe <device_hash>

# Check if RPC server is running
ssh device-ip
sudo systemctl status styrene-bond-rpc
journalctl -u styrene-bond-rpc -n 50
```

### "Authorization denied"

```bash
# On client: Get your identity hash
python -c "from styrene.services.lxmf_service import LXMFService; print(LXMFService().identity.hexhash)"

# On server: Add to auth.yaml
echo "  - hash: \"<YOUR_HASH>\"" >> ~/.config/styrene-bond-rpc/auth.yaml
echo "    name: \"Your Name\"" >> ~/.config/styrene-bond-rpc/auth.yaml
echo "    permissions: [\"status\", \"exec\"]" >> ~/.config/styrene-bond-rpc/auth.yaml

# Restart server
sudo systemctl restart styrene-bond-rpc
```

### "Database locked"

```python
# Use connection pooling
from sqlalchemy import create_engine

engine = create_engine(
    "sqlite:///messages.db",
    pool_size=20,
    pool_pre_ping=True
)
```

### Enable debug logging

```python
import logging
logging.basicConfig(level=logging.DEBUG)
```

---

## 📋 Security Checklist

Before deploying to production:

- [ ] Generate unique identity for each device (`rnid -g`)
- [ ] Configure authorization with minimal permissions
- [ ] Review command whitelist in `handlers.py`
- [ ] Enable audit logging
- [ ] Test authorization denials work
- [ ] Verify systemd hardening is active
- [ ] Document identity rotation schedule
- [ ] Back up identity keys securely

---

## 🔗 Next Steps

1. **Read the full documentation** - [README.md](README.md)
2. **Review security best practices** - See "Security" section in README
3. **Explore the codebase** - See "Project Structure" in README
4. **Run the test suite** - `python -m pytest tests/ -v`
5. **Join the community** - GitHub Discussions

---

## 💡 Pro Tips

**Identity Management:**
```bash
# Generate new identity
rnid -g -n my-device

# List identities
ls ~/.reticulum/identities/

# Backup identities
tar -czf identities-backup.tar.gz ~/.reticulum/identities/
```

**Performance Tuning:**
```python
# Increase timeout for slow networks
rpc.default_timeout = 120.0

# Batch operations
statuses = await asyncio.gather(
    rpc.call_status(device1),
    rpc.call_status(device2),
    rpc.call_status(device3),
)
```

**Development:**
```bash
# Watch mode for tests
python -m pytest tests/ --looponfail

# Coverage report
python -m pytest --cov=src --cov-report=html
open htmlcov/index.html
```

---

**Questions? Check [README.md](README.md) or open a GitHub issue!**
