# Server CRUD Implementation

## Overview

Full CRUD (Create, Read, Update, Delete) implementation for GeViSoft G-Core server management via gRPC SDK Bridge and REST API.

## Critical Implementation Details

### Boolean Type Fix

**Issue**: Initial implementation used `int32` type for boolean fields (Enabled, DeactivateEcho, DeactivateLiveCheck), causing servers to be written but not recognized by GeViSet.

**Solution**: Changed to proper `bool` type (type code 1) instead of `int32` (type code 4).

**Affected Files**:
- `src/sdk-bridge/GeViScopeBridge/Services/ConfigurationServiceImplementation.cs`
  - Lines 1062-1078: CreateServer method
  - Lines 1194-1200: UpdateServer method
  - Lines 1344-1383: UpdateOrAddChild helper (added bool handling)

### Field Order Requirements

Server configuration nodes must have fields in specific order:
1. Alias (string)
2. DeactivateEcho (bool)
3. DeactivateLiveCheck (bool)
4. Enabled (bool)
5. Host (string)
6. Password (string)
7. User (string)

**Reference**: Working implementation in `C:\DEV\COPILOT_codex\geviset_parser.py` lines 389-404

### Auto-Increment Server IDs

**Implementation**: `server_manager.py` demonstrates proper ID management:
- Reads existing servers from configuration
- Finds highest numeric server ID
- Increments by 1 for new server ID
- Skips non-numeric IDs gracefully

```python
def get_next_server_id(servers):
    numeric_ids = []
    for server in servers:
        try:
            numeric_ids.append(int(server['id']))
        except ValueError:
            pass
    if not numeric_ids:
        return "1"
    return str(max(numeric_ids) + 1)
```

## API Endpoints

### REST API (FastAPI)

**Base Path**: `/api/v1/configuration`

- `GET /servers` - List all G-Core servers
- `GET /servers/{server_id}` - Get single server by ID
- `POST /servers` - Create new server
- `PUT /servers/{server_id}` - Update existing server
- `DELETE /servers/{server_id}` - Delete server

**Implementation**: `src/api/routers/configuration.py` lines 278-460

### gRPC API

**Service**: `ConfigurationService`

Methods:
- `CreateServer(CreateServerRequest)` → `ServerOperationResponse`
- `UpdateServer(UpdateServerRequest)` → `ServerOperationResponse`
- `DeleteServer(DeleteServerRequest)` → `ServerOperationResponse`
- `ReadConfigurationTree()` → Configuration tree with all servers

**Implementation**: `src/sdk-bridge/GeViScopeBridge/Services/ConfigurationServiceImplementation.cs`

## Server Data Structure

```protobuf
message ServerData {
    string id = 1;                      // Server ID (numeric string recommended)
    string alias = 2;                   // Display name
    string host = 3;                    // IP address or hostname
    string user = 4;                    // Username (default: "admin")
    string password = 5;                // Password
    bool enabled = 6;                   // Enable/disable server
    bool deactivate_echo = 7;           // Deactivate echo (default: false)
    bool deactivate_live_check = 8;     // Deactivate live check (default: false)
}
```

## Test Scripts

### Production Scripts

1. **server_manager.py** - Complete server lifecycle management
   - Lists existing servers
   - Auto-increments IDs
   - Creates, deletes servers
   - Manages action mappings
   - Cleanup functionality

2. **cleanup_to_base.py** - Restore configuration to base state
   - Deletes test servers (2, 3)
   - Preserves original server (1)
   - Quick reset for testing

3. **add_claude_test_data.py** - Add test data with "Claude" prefix
   - Creates 3 servers: Claude Server Alpha/Beta/Gamma
   - Creates 2 action mappings
   - All identifiable by "Claude" prefix

4. **check_and_add_mapping.py** - Verify and add action mappings
   - Lists existing Claude mappings
   - Adds missing mappings
   - Ensures complete test data

### Legacy Test Scripts

- `test_server_creation.py` - Direct gRPC server creation test
- `add_server_and_mapping.py` - Combined server and mapping creation

## Verification Process

### Testing Workflow

1. **Start Services**:
   ```bash
   cd C:\GEVISOFT
   start GeViServer.exe console

   cd C:\DEV\COPILOT\geutebruck-api\src\sdk-bridge\GeViScopeBridge\bin\Debug\net8.0
   start GeViScopeBridge.exe
   ```

2. **Run Test Script**:
   ```bash
   python server_manager.py
   ```

3. **Stop Services** (required before GeViSet connection):
   ```powershell
   Stop-Process -Name GeViScopeBridge -Force
   Stop-Process -Name python -Force
   Stop-Process -Name GeViServer -Force
   ```

4. **Verify in GeViSet**:
   - Connect to GeViServer
   - Check Configuration → GeViGCoreServer
   - Verify servers appear with correct bool values

### Known Issues & Solutions

**Issue**: Port 50051 (gRPC) in use
- **Solution**: Stop SDK Bridge process

**Issue**: SetupClient connection refused (Error 307)
- **Cause**: GeViSet already connected (only one SetupPort client allowed)
- **Solution**: Disconnect GeViSet, retry SetupClient

**Issue**: Servers created but not visible in GeViSet
- **Root Cause**: Using int32 instead of bool type
- **Solution**: Use proper bool type as documented above

**CRITICAL Issue**: Cascade deletion when deleting multiple action mappings
- **Root Cause**: Deleting in ascending order causes IDs to shift, deleting wrong mappings
- **Solution**: Always delete in REVERSE order (highest ID first)
- **Status**: FIXED in comprehensive_crud_test.py (2025-12-16)
- **Details**: See CRITICAL_BUG_FIX_DELETE.md

## Action Mapping CRUD

Action mappings can also be managed via the same ConfigurationService.

**Endpoints**:
- `GET /api/v1/configuration/action-mappings` - List all mappings
- `GET /api/v1/configuration/action-mappings/{mapping_id}` - Get single mapping
- `POST /api/v1/configuration/action-mappings` - Create mapping
- `PUT /api/v1/configuration/action-mappings/{mapping_id}` - Update mapping
- `DELETE /api/v1/configuration/action-mappings/{mapping_id}` - Delete mapping

**Note**: Mapping IDs are 1-based ordinal positions in the MappingRules list.

## Dependencies

- GeViServer must be running
- SDK Bridge requires GeViServer connection
- REST API requires SDK Bridge on localhost:50051
- GeViSet requires exclusive SetupPort (7703) access

## Success Metrics

✅ Servers persist correctly in GeViSoft configuration
✅ Servers visible in GeViSet with correct boolean values
✅ Auto-increment ID logic prevents conflicts
✅ All CRUD operations functional via gRPC and REST
✅ Action mappings create, read, update, delete working
✅ Configuration changes survive GeViServer restart

## References

- Working Python parser: `C:\DEV\COPILOT_codex\geviset_parser.py`
- SDK Bridge implementation: `src/sdk-bridge/GeViScopeBridge/Services/ConfigurationServiceImplementation.cs`
- REST API: `src/api/routers/configuration.py`
- Protocol definitions: `src/api/protos/configuration.proto`
