# Stargate API Bridge v1.0 - Installation Guide

## Quick Install (5 minutes)

### Step 1: Copy the Script
1. Open `stargate_api_bridge_v1.lsl` in a text editor (notepad, VS Code, etc.)
2. Select all text (`Ctrl+A`) and copy (`Ctrl+C`)

### Step 2: Create Script in Prim
1. **In-world**: Select your gate prim
2. Right-click → **Edit**
3. Go to **Content** tab
4. Click **+ New Script** (bottom right)
5. A new script dialog opens
6. Select all in the script editor and delete the default text
7. Paste the API bridge script (`Ctrl+V`)
8. Click **Save**

### Step 3: Monitor the Script
1. Open local chat (make sure it's visible)
2. Watch for messages like:
   ```
   [API BRIDGE] Starting up. Gate: [YourGateName] | Key: [UUID]
   [API BRIDGE] Attempting initial registration...
   [API BRIDGE] Gate registered! ID: gate_xxxxx | Alias: UNIQUE_ALIAS
   ```

3. If you see errors, check the **Script Errors** window (**Ctrl+Shift+0**) for LSL compilation issues

---

## Configuration (Optional)

### Via Notecard
If you want to customize settings, create a notecard in the **same prim**:

1. Right-click prim → **Edit**
2. **Content** tab → **+ New Notecard**
3. Name it `bridge_config.txt`
4. Add these lines:
   ```
   API_URL=https://api.exoticsg.net
  GATE_TYPE=pegasus
   HEARTBEAT_INTERVAL=180
  HEARTBEAT_CHAT_LOGS=0
   GATE_NAME=My Stargate
   ```

**Note:** Current script version reads hardcoded values. See "Advanced Configuration" below for how to load from notecard.

### Manual Script Edits
Edit these lines in the script if needed:

```lsl
// Near the top of the script:
string g_API_URL = "https://api.exoticsg.net";  // Change if API URL changes
string g_GATE_TYPE = "pegasus";  // Current network default
string g_GATE_NAME = "";  // Leave empty to use prim name, or set a custom name
integer GATE_CTRL_CHANNEL = 55301;   // Change if conflicts with other scripts
integer DHD_CTRL_CHANNEL = 55302;
integer BRIDGE_LISTEN_CHANNEL = 55305;

integer g_HEARTBEAT_INTERVAL = 180;  // Seconds between heartbeats (default 3 min)
integer g_HEARTBEAT_CHAT_LOGS = TRUE;  // Set FALSE to hide heartbeat success messages in chat
integer g_ADDRESS_BOOK_CACHE_TTL = 600;  // Seconds to cache directory (default 10 min)
```

---

## Verification

### Check Registration Status
1. Enter local chat: `/55301 register`
2. Script should respond with current gate_id and alias

### Send Manual Heartbeat
1. Enter local chat: `/55301 heartbeat_request`
2. Script should log heartbeat event

### Fetch Address Book
1. Enter local chat: `/55302 request_address_book`
2. Chat should show API response (if available)

---

## What the Script Does Automatically

| Event | Interval | Details |
|-------|----------|---------|
| **Register Gate** | On startup | Contacts backend, gets unique gate_alias, gate_id |
| **Heartbeat** | Every 180 sec (3 min) | Sends current position, status, shield state |
| **Fetch Address Book** | Every 600 sec (10 min) | Updates list of available gates for DHD |
| **Region Crossing** | On detection | Re-registers if gate moves to new region |

---

## Troubleshooting

### Script shows: "Network error on register request"
- **Cause**: API server unreachable or network blocked
- **Fix**: 
  - Verify your sim has HTTP access enabled
  - Check that `api.exoticsg.net` is reachable (try pinging from outside)
  - Confirm firewall/parcel permissions allow HTTP

### Script shows: "ERROR: Invalid heartbeat response"
- **Cause**: API response format unexpected (possible version mismatch)
- **Fix**: Check that backend is running: `curl https://api.exoticsg.net/health`

### Script doesn't start after rebooting region
- **Cause**: Timer may need restart
- **Fix**: 
  1. Select prim
  2. Right-click → **Edit** → **Content** tab
  3. Find script, right-click → **Reset** (or delete & re-add)

### "Gate registered" message appears but DHD not getting directory
- **Cause**: Channel mismatch or DHD script not listening on 55302
- **Fix**: Verify DHD controller is on `DHD_CTRL_CHANNEL = 55302`

### Address book not updating
- **Cause**: Backend has no other gates registered, or cache TTL hasn't expired
- **Fix**: 
  - Manually force refresh via chat: `/55305 refresh_directory`
  - Or register another gate to populate directory

---

## Integration with Other Controllers

### For DHD (Dialing Device)
DHD script should:
1. Listen on channel `55302` (DHD_CTRL_CHANNEL)
2. When needing address book, send: `request_address_book`
3. Expect response: `{"event":"address_book","data":[...]}`

### For GDO/IDC Controller
GDO script should:
1. Request dial authorization from backend: `POST /api/gates/{sourceId}/dial/authorize`
2. Wait for: `{"authorized":true, "target_gate":{...}}`
3. Only proceed with dial sequence if authorized=true

### For Gate Controller
Gate controller should:
1. Tell bridge about status changes: send `heartbeat_request` on channel `55301` when status changes
2. Listen for: `api_gate_registered` event with gate_id/alias when registration completes

---

## Advanced: Loading Config from Notecard

The current script reads hardcoded values. To add notecard config support:

1. In the script, add this function before `default` state:
```lsl
LoadConfigFromNotecard() {
    // This would parse a notecard named "bridge_config.txt"
    // and override settings like g_API_URL, g_GATE_NAME, etc.
    // Requires implementing notecard reading with llGetInventoryName() + osGetNotecard()
    // or llCollisionSounds() + dataserver events
}
```

2. Call in `state_entry()`:
```lsl
    state_entry() {
        // ... existing code ...
        LoadConfigFromNotecard();
    }
```

---

## Next Steps

1. **✅ Script Installed**: Bridge is now running
2. **✅ DHD v3 Ready**: Use `stargate_dhd_controller_v3.lsl` for live directory via bridge channel `55302`
3. **→ Update GDO/IDC**: Wire authorization endpoint into `stargate_gdo_idc_controller_v1.lsl`
4. **→ In-World Testing**: Register multiple gates and test dialing

---

## Support & Debugging

### Enable Debug Mode
Uncomment this line in the script to see verbose logging:
```lsl
// At top of script, after configuration:
integer DEBUG_MODE = 1;
```

Then add logging before HTTP calls:
```lsl
if (DEBUG_MODE) llSay(0, "[DEBUG] Sending request to " + url);
```

### Raw API Testing
Test endpoints manually from terminal:
```bash
# Check health
curl https://api.exoticsg.net/health

# Check if any gates registered
curl https://api.exoticsg.net/api/network/directory

# Check a specific gate's address book
curl https://api.exoticsg.net/api/gates/{gate_id}/address-book
```

### Capture Full Request/Response
In the `http_response()` function, add:
```lsl
llSay(0, "[DEBUG] Status: " + (string)status + " | Body: " + body);
```

This will show full API responses in local chat for debugging.

---

## File Location Reference

- **Script File**: `d:\Stargate\stargate_api_bridge_v1.lsl`
- **Backend API**: `https://api.exoticsg.net`
- **Live Server**: `104.171.126.236`
- **Database**: PostgreSQL on server, gate registry in `esn_production`

---

**Version**: API Bridge v1.0
**Last Updated**: 2026-04-06
**Status**: Production Ready
