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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env python3
"""
DTO Syncthing Client - Manages distributed file synchronization for Class B/C transfers
Provides automated setup and monitoring of Syncthing mirrors for non-critical data
"""

import os
import json
import requests
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone
from pathlib import Path
import subprocess
import time

class DTOSyncthingClient:
    def __init__(self, api_key: Optional[str] = None, host: str = "localhost", port: int = 8384):
        self.host = host
        self.port = port
        self.api_key = api_key or os.getenv('SYNCTHING_API_KEY')
        self.base_url = f"http://{self.host}:{self.port}/rest"
        self.headers = {
            'Content-Type': 'application/json',
            'X-API-Key': self.api_key
        } if self.api_key else {}
        self.config_dir = Path("/data/adaptai/platform/dataops/dto/syncthing")
        
    def test_connection(self) -> bool:
        """Test Syncthing API connectivity"""
        if not self.api_key:
            print("❌ Syncthing API key not configured")
            return False
        
        try:
            response = requests.get(
                f"{self.base_url}/system/ping",
                headers=self.headers,
                timeout=10
            )
            
            if response.status_code == 200:
                system_info = self.get_system_status()
                print(f"βœ… Connected to Syncthing {system_info.get('version', 'unknown')}")
                return True
            else:
                print(f"❌ Syncthing connection failed: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error connecting to Syncthing: {e}")
            return False
    
    def get_system_status(self) -> Dict[str, Any]:
        """Get Syncthing system status"""
        try:
            response = requests.get(
                f"{self.base_url}/system/status",
                headers=self.headers
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                return {}
                
        except Exception as e:
            print(f"❌ Error getting system status: {e}")
            return {}
    
    def get_device_id(self) -> Optional[str]:
        """Get this Syncthing instance's device ID"""
        try:
            status = self.get_system_status()
            return status.get('myID')
        except Exception as e:
            print(f"❌ Error getting device ID: {e}")
            return None
    
    def add_device(self, device_id: str, device_name: str, introducer: bool = False) -> bool:
        """Add a device to Syncthing configuration"""
        try:
            # Get current config
            config_response = requests.get(
                f"{self.base_url}/system/config",
                headers=self.headers
            )
            
            if config_response.status_code != 200:
                print(f"❌ Failed to get config: {config_response.status_code}")
                return False
            
            config = config_response.json()
            
            # Check if device already exists
            for device in config.get('devices', []):
                if device['deviceID'] == device_id:
                    print(f"ℹ️ Device {device_name} already exists")
                    return True
            
            # Add new device
            new_device = {
                'deviceID': device_id,
                'name': device_name,
                'addresses': ['dynamic'],
                'compression': 'metadata',
                'certName': '',
                'introducer': introducer,
                'skipIntroductionRemovals': False,
                'introducedBy': '',
                'paused': False,
                'allowedNetworks': [],
                'autoAcceptFolders': False,
                'maxSendKbps': 0,
                'maxRecvKbps': 0,
                'ignoredFolders': [],
                'pendingFolders': [],
                'maxRequestKiB': 0
            }
            
            config['devices'].append(new_device)
            
            # Update config
            update_response = requests.post(
                f"{self.base_url}/system/config",
                headers=self.headers,
                data=json.dumps(config)
            )
            
            if update_response.status_code == 200:
                print(f"βœ… Added device: {device_name} ({device_id})")
                return True
            else:
                print(f"❌ Failed to add device: {update_response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error adding device: {e}")
            return False
    
    def create_folder(self, folder_id: str, folder_path: str, device_ids: List[str],
                     folder_type: str = "sendreceive", rescan_interval: int = 3600) -> bool:
        """Create a shared folder in Syncthing"""
        try:
            # Get current config
            config_response = requests.get(
                f"{self.base_url}/system/config",
                headers=self.headers
            )
            
            if config_response.status_code != 200:
                print(f"❌ Failed to get config: {config_response.status_code}")
                return False
            
            config = config_response.json()
            
            # Check if folder already exists
            for folder in config.get('folders', []):
                if folder['id'] == folder_id:
                    print(f"ℹ️ Folder {folder_id} already exists")
                    return True
            
            # Ensure directory exists
            Path(folder_path).mkdir(parents=True, exist_ok=True)
            
            # Create devices list for folder
            devices = [{'deviceID': device_id, 'introducedBy': '', 'encryptionPassword': ''} 
                      for device_id in device_ids]
            
            # Add new folder
            new_folder = {
                'id': folder_id,
                'label': folder_id,
                'filesystemType': 'basic',
                'path': folder_path,
                'type': folder_type,
                'devices': devices,
                'rescanIntervalS': rescan_interval,
                'fsWatcherEnabled': True,
                'fsWatcherDelayS': 10,
                'ignorePerms': False,
                'autoNormalize': True,
                'minDiskFree': {'value': 1, 'unit': '%'},
                'versioning': {
                    'type': 'simple',
                    'params': {'keep': '5'}
                },
                'copiers': 0,
                'pullerMaxPendingKiB': 0,
                'hashers': 0,
                'order': 'random',
                'ignoreDelete': False,
                'scanProgressIntervalS': 0,
                'pullerPauseS': 0,
                'maxConflicts': 10,
                'disableSparseFiles': False,
                'disableTempIndexes': False,
                'paused': False,
                'weakHashThresholdPct': 25,
                'markerName': '.stfolder'
            }
            
            config['folders'].append(new_folder)
            
            # Update config
            update_response = requests.post(
                f"{self.base_url}/system/config",
                headers=self.headers,
                data=json.dumps(config)
            )
            
            if update_response.status_code == 200:
                print(f"βœ… Created folder: {folder_id} -> {folder_path}")
                return True
            else:
                print(f"❌ Failed to create folder: {update_response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error creating folder: {e}")
            return False
    
    def get_folder_status(self, folder_id: str) -> Dict[str, Any]:
        """Get status of a specific folder"""
        try:
            response = requests.get(
                f"{self.base_url}/db/status",
                headers=self.headers,
                params={'folder': folder_id}
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                return {}
                
        except Exception as e:
            print(f"❌ Error getting folder status: {e}")
            return {}
    
    def get_folder_completion(self, folder_id: str, device_id: str) -> Dict[str, Any]:
        """Get folder completion status for a specific device"""
        try:
            response = requests.get(
                f"{self.base_url}/db/completion",
                headers=self.headers,
                params={'folder': folder_id, 'device': device_id}
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                return {}
                
        except Exception as e:
            print(f"❌ Error getting folder completion: {e}")
            return {}
    
    def setup_dto_mirror(self, mirror_config: Dict[str, Any]) -> bool:
        """Set up DTO data mirror for Class B/C transfers"""
        try:
            mirror_name = mirror_config['name']
            source_path = mirror_config['source_path']
            mirror_devices = mirror_config['devices']
            data_class = mirror_config.get('data_class', 'CLASS_B')
            
            print(f"πŸ”„ Setting up DTO mirror: {mirror_name}")
            
            # Create folder ID based on mirror name and data class
            folder_id = f"dto-{data_class.lower()}-{mirror_name}"
            
            # Add all devices if not already present
            for device in mirror_devices:
                device_id = device['device_id']
                device_name = device['name']
                self.add_device(device_id, device_name)
            
            # Create shared folder
            device_ids = [device['device_id'] for device in mirror_devices]
            folder_created = self.create_folder(
                folder_id, 
                source_path,
                device_ids,
                folder_type='sendreceive',
                rescan_interval=1800  # 30 minutes for Class B/C
            )
            
            if folder_created:
                print(f"βœ… DTO mirror setup completed: {mirror_name}")
                
                # Wait for initial scan
                print("πŸ” Waiting for initial folder scan...")
                time.sleep(10)
                
                # Get initial status
                status = self.get_folder_status(folder_id)
                if status:
                    print(f"πŸ“Š Initial scan: {status.get('localFiles', 0)} files, "
                          f"{status.get('localBytes', 0) / (1024**3):.2f} GB")
                
                return True
            else:
                print(f"❌ Failed to setup mirror: {mirror_name}")
                return False
                
        except Exception as e:
            print(f"❌ Error setting up mirror: {e}")
            return False
    
    def monitor_sync_progress(self, folder_id: str, device_ids: List[str]) -> Dict[str, Any]:
        """Monitor synchronization progress across devices"""
        try:
            sync_status = {
                'folder_id': folder_id,
                'timestamp': datetime.now(timezone.utc).isoformat(),
                'devices': {}
            }
            
            # Get folder status
            folder_status = self.get_folder_status(folder_id)
            sync_status['folder_status'] = folder_status
            
            # Get completion status for each device
            for device_id in device_ids:
                completion = self.get_folder_completion(folder_id, device_id)
                sync_status['devices'][device_id] = {
                    'completion_percent': completion.get('completion', 0),
                    'bytes_total': completion.get('globalBytes', 0),
                    'bytes_done': completion.get('needBytes', 0),
                    'items_total': completion.get('globalItems', 0),
                    'items_done': completion.get('needItems', 0)
                }
            
            return sync_status
            
        except Exception as e:
            print(f"❌ Error monitoring sync progress: {e}")
            return {}
    
    def get_sync_statistics(self) -> Dict[str, Any]:
        """Get overall synchronization statistics"""
        try:
            # Get system statistics
            stats_response = requests.get(
                f"{self.base_url}/system/status",
                headers=self.headers
            )
            
            if stats_response.status_code != 200:
                return {}
            
            stats = stats_response.json()
            
            # Get connections info
            connections_response = requests.get(
                f"{self.base_url}/system/connections",
                headers=self.headers
            )
            
            connections = {}
            if connections_response.status_code == 200:
                connections = connections_response.json()
            
            return {
                'system_stats': stats,
                'connections': connections,
                'timestamp': datetime.now(timezone.utc).isoformat()
            }
            
        except Exception as e:
            print(f"❌ Error getting sync statistics: {e}")
            return {}
    
    def pause_folder(self, folder_id: str) -> bool:
        """Pause synchronization for a folder"""
        try:
            response = requests.post(
                f"{self.base_url}/db/pause",
                headers=self.headers,
                params={'folder': folder_id}
            )
            
            if response.status_code == 200:
                print(f"⏸️ Paused folder: {folder_id}")
                return True
            else:
                print(f"❌ Failed to pause folder: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error pausing folder: {e}")
            return False
    
    def resume_folder(self, folder_id: str) -> bool:
        """Resume synchronization for a folder"""
        try:
            response = requests.post(
                f"{self.base_url}/db/resume",
                headers=self.headers,
                params={'folder': folder_id}
            )
            
            if response.status_code == 200:
                print(f"▢️ Resumed folder: {folder_id}")
                return True
            else:
                print(f"❌ Failed to resume folder: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error resuming folder: {e}")
            return False
    
    def scan_folder(self, folder_id: str) -> bool:
        """Trigger manual scan of a folder"""
        try:
            response = requests.post(
                f"{self.base_url}/db/scan",
                headers=self.headers,
                params={'folder': folder_id}
            )
            
            if response.status_code == 200:
                print(f"πŸ” Triggered scan for folder: {folder_id}")
                return True
            else:
                print(f"❌ Failed to scan folder: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error scanning folder: {e}")
            return False

# Test function
def test_syncthing_integration():
    """Test Syncthing integration with mock mirror setup"""
    client = DTOSyncthingClient()
    
    if not client.test_connection():
        print("❌ Syncthing integration test failed (expected without proper setup)")
        return False
    
    # Test mirror setup
    test_mirror = {
        'name': 'test-research-data',
        'source_path': '/data/adaptai/platform/dataops/dto/test/class_b',
        'data_class': 'CLASS_B',
        'devices': [
            {
                'device_id': 'ABCDEFG-HIJKLMN-OPQRSTU-VWXYZ12-3456789-ABCDEFG-HIJKLMN-OPQRSTU',
                'name': 'vast1-mirror'
            },
            {
                'device_id': 'BCDEFGH-IJKLMNO-PQRSTUV-WXYZ123-456789A-BCDEFGH-IJKLMNO-PQRSTUV',
                'name': 'vast2-mirror'
            }
        ]
    }
    
    # Create test directory
    Path(test_mirror['source_path']).mkdir(parents=True, exist_ok=True)
    
    # Setup mirror
    if client.setup_dto_mirror(test_mirror):
        print("βœ… Syncthing mirror setup test completed")
        
        # Test monitoring
        device_ids = [device['device_id'] for device in test_mirror['devices']]
        sync_status = client.monitor_sync_progress('dto-class_b-test-research-data', device_ids)
        
        if sync_status:
            print("βœ… Sync monitoring test completed")
        
        return True
    else:
        print("❌ Failed to setup test mirror")
        return False

if __name__ == "__main__":
    print("Testing DTO Syncthing Integration...")
    print("=" * 50)
    
    test_syncthing_integration()
    print("\nTo use Syncthing integration, set these environment variables:")
    print("export SYNCTHING_API_KEY=your-api-key")
    print("And ensure Syncthing is running on localhost:8384")