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
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
#!/usr/bin/env python3
"""
DTO Syncthing Automation - Event-driven sync management for Class B/C transfers
Automatically manages Syncthing mirrors based on DTO events and manifest requirements
"""

import asyncio
import json
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone
from nats.aio.client import Client as NATS
from syncthing_client import DTOSyncthingClient
from pathlib import Path

class DTOSyncthingAutomation:
    def __init__(self, nats_servers: list = ["nats://localhost:4222"]):
        self.nats_servers = nats_servers
        self.nats_client = NATS()
        self.syncthing_client = DTOSyncthingClient()
        self.active_mirrors = {}  # Track active mirror configurations
        self.sync_jobs = {}      # Track ongoing sync jobs
        
        # Default mirror configurations for different data classes
        self.mirror_configs = {
            'CLASS_B': {
                'rescan_interval': 1800,  # 30 minutes
                'folder_type': 'sendreceive',
                'versioning_keep': 3,
                'priority': 'low'
            },
            'CLASS_C': {
                'rescan_interval': 3600,  # 1 hour
                'folder_type': 'sendreceive', 
                'versioning_keep': 5,
                'priority': 'background'
            }
        }
        
    async def connect(self) -> bool:
        """Connect to NATS and Syncthing"""
        try:
            # Connect to NATS
            await self.nats_client.connect(servers=self.nats_servers)
            print("βœ… Connected to NATS for Syncthing automation")
            
            # Test Syncthing connection
            if not self.syncthing_client.test_connection():
                print("⚠️ Syncthing not available - running in monitoring mode only")
            
            return True
            
        except Exception as e:
            print(f"❌ Syncthing automation connection failed: {e}")
            return False
    
    async def handle_run_planned(self, event_data: Dict[str, Any]):
        """Handle RUN_PLANNED event - setup mirrors for Class B/C runs"""
        run_id = event_data.get('run_id')
        data_class = event_data.get('data_class', '').upper()
        manifest_path = event_data.get('manifest_path')
        environment = event_data.get('environment')
        
        # Only handle Class B and C transfers
        if data_class not in ['CLASS_B', 'CLASS_C']:
            print(f"ℹ️ Skipping Syncthing setup for {data_class} run: {run_id}")
            return
        
        print(f"πŸ”„ Setting up Syncthing mirror for {data_class} run: {run_id}")
        
        try:
            # Load manifest to get mirror requirements
            mirror_config = await self.parse_manifest_for_mirrors(manifest_path, data_class)
            
            if mirror_config:
                # Setup Syncthing mirror
                mirror_setup = await self.setup_run_mirror(run_id, mirror_config, data_class, environment)
                
                if mirror_setup:
                    self.active_mirrors[run_id] = mirror_config
                    print(f"βœ… Syncthing mirror configured for run: {run_id}")
                    
                    # Publish mirror setup event
                    await self.publish_mirror_event('SYNCTHING_MIRROR_SETUP', {
                        'run_id': run_id,
                        'data_class': data_class,
                        'mirror_config': mirror_config,
                        'environment': environment
                    })
                else:
                    print(f"❌ Failed to setup mirror for run: {run_id}")
            else:
                print(f"ℹ️ No mirror configuration required for run: {run_id}")
                
        except Exception as e:
            print(f"❌ Error setting up mirror for run {run_id}: {e}")
    
    async def parse_manifest_for_mirrors(self, manifest_path: str, data_class: str) -> Optional[Dict[str, Any]]:
        """Parse manifest file to extract mirror configuration"""
        try:
            # In a real implementation, this would parse YAML/JSON manifest
            # For now, create a default configuration based on data class
            
            base_path = f"/data/adaptai/platform/dataops/dto/mirrors/{data_class.lower()}"
            
            # Default mirror devices (would be configured per environment)
            default_devices = [
                {
                    'device_id': self.get_device_id_for_host('vast1.adapt.ai'),
                    'name': 'vast1-mirror',
                    'role': 'primary'
                },
                {
                    'device_id': self.get_device_id_for_host('vast2.adapt.ai'), 
                    'name': 'vast2-mirror',
                    'role': 'secondary'
                }
            ]
            
            mirror_config = {
                'name': f'{data_class.lower()}-auto-mirror',
                'source_path': base_path,
                'devices': default_devices,
                'data_class': data_class,
                'sync_mode': 'bidirectional',
                'schedule': self.mirror_configs[data_class]
            }
            
            return mirror_config
            
        except Exception as e:
            print(f"❌ Error parsing manifest: {e}")
            return None
    
    def get_device_id_for_host(self, hostname: str) -> str:
        """Get Syncthing device ID for a hostname (mock implementation)"""
        # In real implementation, this would look up actual device IDs
        # For now, generate deterministic mock IDs
        import hashlib
        hash_obj = hashlib.md5(hostname.encode())
        hex_hash = hash_obj.hexdigest().upper()
        
        # Format as Syncthing device ID (LUHN check digit format)
        device_id = '-'.join([hex_hash[i:i+7] for i in range(0, len(hex_hash), 7)])
        return device_id[:63]  # Syncthing device ID length limit
    
    async def setup_run_mirror(self, run_id: str, mirror_config: Dict[str, Any], 
                              data_class: str, environment: str) -> bool:
        """Set up Syncthing mirror for a specific run"""
        try:
            # Create run-specific mirror configuration
            run_mirror_config = mirror_config.copy()
            run_mirror_config['name'] = f"{run_id}-{data_class.lower()}"
            run_mirror_config['source_path'] = f"{mirror_config['source_path']}/{run_id}"
            
            # Ensure source directory exists
            Path(run_mirror_config['source_path']).mkdir(parents=True, exist_ok=True)
            
            # Setup mirror using Syncthing client
            success = self.syncthing_client.setup_dto_mirror(run_mirror_config)
            
            if success:
                # Store sync job details
                self.sync_jobs[run_id] = {
                    'folder_id': f"dto-{data_class.lower()}-{run_mirror_config['name']}",
                    'mirror_config': run_mirror_config,
                    'start_time': datetime.now(timezone.utc).isoformat(),
                    'status': 'active'
                }
                
                print(f"βœ… Mirror setup completed for run: {run_id}")
                return True
            else:
                print(f"❌ Mirror setup failed for run: {run_id}")
                return False
                
        except Exception as e:
            print(f"❌ Error setting up run mirror: {e}")
            return False
    
    async def handle_transfer_started(self, event_data: Dict[str, Any]):
        """Handle TRANSFER_STARTED event - begin sync monitoring"""
        run_id = event_data.get('run_id')
        
        if run_id not in self.sync_jobs:
            return
        
        print(f"πŸ“Š Starting sync monitoring for run: {run_id}")
        
        # Begin monitoring sync progress
        await self.start_sync_monitoring(run_id)
    
    async def start_sync_monitoring(self, run_id: str):
        """Start monitoring synchronization progress"""
        if run_id not in self.sync_jobs:
            return
        
        sync_job = self.sync_jobs[run_id]
        folder_id = sync_job['folder_id']
        mirror_config = sync_job['mirror_config']
        
        try:
            # Get device IDs for monitoring
            device_ids = [device['device_id'] for device in mirror_config['devices']]
            
            # Monitor sync progress
            sync_status = self.syncthing_client.monitor_sync_progress(folder_id, device_ids)
            
            if sync_status:
                # Publish sync progress event
                await self.publish_mirror_event('SYNCTHING_SYNC_PROGRESS', {
                    'run_id': run_id,
                    'folder_id': folder_id,
                    'sync_status': sync_status
                })
                
                print(f"πŸ“Š Sync progress monitored for run: {run_id}")
            
        except Exception as e:
            print(f"❌ Error monitoring sync for run {run_id}: {e}")
    
    async def handle_run_completed(self, event_data: Dict[str, Any]):
        """Handle RUN_COMPLETED event - finalize sync and cleanup"""
        run_id = event_data.get('run_id')
        final_status = event_data.get('final_status')
        
        if run_id not in self.sync_jobs:
            return
        
        print(f"🏁 Finalizing sync for completed run: {run_id}")
        
        try:
            sync_job = self.sync_jobs[run_id]
            folder_id = sync_job['folder_id']
            
            # Get final sync statistics
            final_stats = self.syncthing_client.get_sync_statistics()
            
            # Update sync job status
            sync_job['status'] = 'completed' if final_status == 'SUCCESS' else 'failed'
            sync_job['end_time'] = datetime.now(timezone.utc).isoformat()
            sync_job['final_stats'] = final_stats
            
            # For Class B/C, keep the mirror active for ongoing sync
            # Only pause if the run failed
            if final_status != 'SUCCESS':
                self.syncthing_client.pause_folder(folder_id)
                print(f"⏸️ Paused sync for failed run: {run_id}")
            else:
                # Trigger final scan to ensure all data is synced
                self.syncthing_client.scan_folder(folder_id)
                print(f"πŸ” Triggered final sync scan for run: {run_id}")
            
            # Publish sync completion event
            await self.publish_mirror_event('SYNCTHING_SYNC_COMPLETED', {
                'run_id': run_id,
                'folder_id': folder_id,
                'final_status': final_status,
                'sync_job': sync_job
            })
            
        except Exception as e:
            print(f"❌ Error finalizing sync for run {run_id}: {e}")
    
    async def handle_sync_request(self, event_data: Dict[str, Any]):
        """Handle manual sync requests"""
        folder_id = event_data.get('folder_id')
        action = event_data.get('action', 'scan')
        
        if not folder_id:
            print("⚠️ No folder ID provided for sync request")
            return
        
        print(f"πŸ”„ Processing sync request: {action} for folder {folder_id}")
        
        try:
            if action == 'scan':
                success = self.syncthing_client.scan_folder(folder_id)
            elif action == 'pause':
                success = self.syncthing_client.pause_folder(folder_id)
            elif action == 'resume':
                success = self.syncthing_client.resume_folder(folder_id)
            else:
                print(f"❌ Unknown sync action: {action}")
                return
            
            if success:
                await self.publish_mirror_event('SYNCTHING_ACTION_COMPLETED', {
                    'folder_id': folder_id,
                    'action': action,
                    'success': True
                })
            
        except Exception as e:
            print(f"❌ Error processing sync request: {e}")
    
    async def monitor_sync_health(self):
        """Periodic sync health monitoring"""
        try:
            print("πŸ₯ Monitoring Syncthing sync health...")
            
            # Get overall sync statistics
            sync_stats = self.syncthing_client.get_sync_statistics()
            
            if sync_stats:
                # Check for any sync issues
                connections = sync_stats.get('connections', {})
                
                # Count connected vs disconnected devices
                connected_devices = 0
                total_devices = 0
                
                for device_id, connection in connections.get('connections', {}).items():
                    total_devices += 1
                    if connection.get('connected'):
                        connected_devices += 1
                
                # Publish health status
                health_event = {
                    'event_type': 'SYNCTHING_HEALTH_CHECK',
                    'timestamp': datetime.now(timezone.utc).isoformat(),
                    'connected_devices': connected_devices,
                    'total_devices': total_devices,
                    'connection_rate': connected_devices / total_devices if total_devices > 0 else 0,
                    'active_mirrors': len(self.sync_jobs),
                    'sync_stats': sync_stats
                }
                
                await self.publish_mirror_event('SYNCTHING_HEALTH_STATUS', health_event)
                
                if connected_devices < total_devices:
                    print(f"⚠️ Sync health warning: {connected_devices}/{total_devices} devices connected")
                else:
                    print(f"βœ… Sync health OK: All {total_devices} devices connected")
            
        except Exception as e:
            print(f"❌ Error monitoring sync health: {e}")
    
    async def publish_mirror_event(self, event_type: str, event_data: Dict[str, Any]):
        """Publish Syncthing mirror event to NATS"""
        try:
            mirror_event = {
                'event_id': f"syncthing-{event_type.lower()}-{int(datetime.now().timestamp())}",
                'event_type': event_type,
                'timestamp': datetime.now(timezone.utc).isoformat(),
                'source': 'syncthing-automation',
                **event_data
            }
            
            await self.nats_client.publish(
                f"dto.events.syncthing.{event_type.lower()}",
                json.dumps(mirror_event).encode()
            )
            
            print(f"πŸ“€ Published {event_type} event")
            
        except Exception as e:
            print(f"❌ Error publishing mirror event: {e}")
    
    async def process_event(self, msg):
        """Process incoming NATS event for Syncthing automation"""
        try:
            event_data = json.loads(msg.data.decode())
            event_type = event_data.get('event_type')
            
            # Route to appropriate handler
            handlers = {
                'RUN_PLANNED': self.handle_run_planned,
                'TRANSFER_STARTED': self.handle_transfer_started,
                'RUN_COMPLETED': self.handle_run_completed,
                'SYNCTHING_SYNC_REQUEST': self.handle_sync_request
            }
            
            handler = handlers.get(event_type)
            if handler:
                await handler(event_data)
            else:
                # Log other events for debugging
                print(f"ℹ️ Syncthing automation ignoring event: {event_type}")
                
        except Exception as e:
            print(f"❌ Error processing Syncthing event: {e}")
    
    async def start_automation(self):
        """Start listening for DTO events and periodic monitoring"""
        try:
            # Subscribe to DTO events
            await self.nats_client.subscribe("dto.events.>", cb=self.process_event)
            print("βœ… Started Syncthing automation - listening for DTO events")
            
            # Start periodic health monitoring
            async def periodic_health_check():
                while True:
                    await asyncio.sleep(300)  # 5 minutes
                    await self.monitor_sync_health()
            
            # Run both event processing and health monitoring
            await asyncio.gather(
                periodic_health_check(),
                self.keep_alive()
            )
            
        except KeyboardInterrupt:
            print("\nπŸ›‘ Stopping Syncthing automation...")
        except Exception as e:
            print(f"❌ Syncthing automation error: {e}")
        finally:
            await self.nats_client.close()
    
    async def keep_alive(self):
        """Keep the automation running"""
        while True:
            await asyncio.sleep(1)

# CLI entry point
async def main():
    automation = DTOSyncthingAutomation()
    
    if await automation.connect():
        print("πŸ”„ DTO Syncthing Automation started")
        print("Monitoring events: RUN_PLANNED, TRANSFER_STARTED, RUN_COMPLETED")
        print("Managing distributed mirrors for Class B/C data transfers")
        print("Press Ctrl+C to stop\n")
        
        await automation.start_automation()
    else:
        print("❌ Failed to start Syncthing automation")

if __name__ == "__main__":
    asyncio.run(main())