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
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
#!/usr/bin/env python3
"""
DTO Jira Client - Automates ticket creation for Class-A data transfer runs
"""

import os
import json
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone
import requests
from requests.auth import HTTPBasicAuth

class DTOJiraClient:
    def __init__(self, server_url: Optional[str] = None, username: Optional[str] = None, 
                 api_token: Optional[str] = None):
        self.server_url = server_url or os.getenv('JIRA_SERVER_URL')
        self.username = username or os.getenv('JIRA_USERNAME')
        self.api_token = api_token or os.getenv('JIRA_API_TOKEN')
        self.auth = HTTPBasicAuth(self.username, self.api_token) if self.username and self.api_token else None
        self.headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        
    def test_connection(self) -> bool:
        """Test Jira API connectivity"""
        if not self.auth or not self.server_url:
            print("❌ Jira credentials not configured")
            return False
        
        try:
            response = requests.get(
                f"{self.server_url}/rest/api/3/myself",
                auth=self.auth,
                headers=self.headers,
                timeout=10
            )
            
            if response.status_code == 200:
                print("βœ… Connected to Jira API")
                return True
            else:
                print(f"❌ Jira connection failed: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error connecting to Jira: {e}")
            return False
    
    def create_class_a_ticket(self, run_data: Dict[str, Any]) -> Optional[str]:
        """Create Jira ticket for Class-A data transfer run"""
        if not self.auth:
            print("❌ Jira not configured")
            return None
        
        run_id = run_data.get('run_id', 'unknown')
        manifest_path = run_data.get('manifest_path', 'N/A')
        data_size_gb = round(run_data.get('data_size_bytes', 0) / (1024**3), 2)
        initiated_by = run_data.get('initiated_by', 'system')
        environment = run_data.get('environment', 'staging')
        
        # Format ticket summary and description
        summary = f"Class-A Data Transfer: {run_id}"
        
        description = f"""
*Automated Class-A Data Transfer Ticket*

*Run Details:*
β€’ Run ID: {run_id}
β€’ Manifest: {manifest_path}
β€’ Data Size: {data_size_gb} GB
β€’ Environment: {environment.upper()}
β€’ Initiated By: {initiated_by}
β€’ Created: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}

*Pre-flight Checklist:*
- [ ] Manifest validation completed
- [ ] Source data integrity verified
- [ ] Target storage capacity confirmed
- [ ] Network bandwidth reserved
- [ ] Approval workflow triggered

*Post-transfer Validation:*
- [ ] Checksum verification passed
- [ ] Data lineage recorded
- [ ] Performance metrics logged
- [ ] Cleanup procedures executed

*Links:*
β€’ DTO Dashboard: https://dto.adapt.ai/runs/{run_id}
β€’ Logs: /data/adaptai/platform/dataops/dto/logs/{run_id}/

This ticket tracks the execution and validation of a Class-A data transfer operation.
        """.strip()
        
        # Create ticket payload
        ticket_data = {
            "fields": {
                "project": {"key": "DTO"},
                "summary": summary,
                "description": {
                    "type": "doc",
                    "version": 1,
                    "content": [
                        {
                            "type": "paragraph",
                            "content": [
                                {"type": "text", "text": description}
                            ]
                        }
                    ]
                },
                "issuetype": {"name": "Task"},
                "priority": {"name": "High"},
                "labels": [
                    "dto",
                    "class-a",
                    "data-transfer",
                    f"env-{environment}",
                    f"run-{run_id}"
                ],
                "customfield_10001": run_id,  # DTO Run ID custom field
                "customfield_10002": data_size_gb,  # Data Size GB custom field
                "components": [{"name": "Data Transfer Operations"}]
            }
        }
        
        try:
            response = requests.post(
                f"{self.server_url}/rest/api/3/issue",
                auth=self.auth,
                headers=self.headers,
                data=json.dumps(ticket_data),
                timeout=30
            )
            
            if response.status_code == 201:
                ticket_key = response.json()['key']
                print(f"βœ… Created Jira ticket: {ticket_key} for run {run_id}")
                return ticket_key
            else:
                print(f"❌ Failed to create ticket: {response.status_code} - {response.text}")
                return None
                
        except Exception as e:
            print(f"❌ Error creating Jira ticket: {e}")
            return None
    
    def update_ticket_status(self, ticket_key: str, status: str, comment: Optional[str] = None) -> bool:
        """Update ticket status based on run progress"""
        if not self.auth:
            return False
        
        # Map DTO statuses to Jira transitions
        status_transitions = {
            "in_progress": "Start Progress",
            "validation": "Move to Validation", 
            "completed": "Done",
            "failed": "Move to Failed",
            "rolled_back": "Reopen"
        }
        
        transition_name = status_transitions.get(status)
        if not transition_name:
            print(f"❌ Unknown status: {status}")
            return False
        
        try:
            # Get available transitions
            transitions_response = requests.get(
                f"{self.server_url}/rest/api/3/issue/{ticket_key}/transitions",
                auth=self.auth,
                headers=self.headers
            )
            
            if transitions_response.status_code != 200:
                print(f"❌ Failed to get transitions: {transitions_response.status_code}")
                return False
            
            transitions = transitions_response.json()['transitions']
            transition_id = None
            
            for transition in transitions:
                if transition['name'].lower() == transition_name.lower():
                    transition_id = transition['id']
                    break
            
            if not transition_id:
                print(f"❌ Transition '{transition_name}' not available")
                return False
            
            # Perform transition
            transition_data = {
                "transition": {"id": transition_id}
            }
            
            if comment:
                transition_data["update"] = {
                    "comment": [
                        {
                            "add": {
                                "body": {
                                    "type": "doc",
                                    "version": 1,
                                    "content": [
                                        {
                                            "type": "paragraph",
                                            "content": [
                                                {"type": "text", "text": comment}
                                            ]
                                        }
                                    ]
                                }
                            }
                        }
                    ]
                }
            
            response = requests.post(
                f"{self.server_url}/rest/api/3/issue/{ticket_key}/transitions",
                auth=self.auth,
                headers=self.headers,
                data=json.dumps(transition_data)
            )
            
            if response.status_code == 204:
                print(f"βœ… Updated ticket {ticket_key} to {status}")
                return True
            else:
                print(f"❌ Failed to update ticket: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error updating ticket: {e}")
            return False
    
    def add_run_metrics(self, ticket_key: str, metrics: Dict[str, Any]) -> bool:
        """Add performance metrics as ticket comment"""
        if not self.auth:
            return False
        
        throughput = metrics.get('average_throughput_mbps', 0)
        duration = metrics.get('total_duration_seconds', 0)
        data_size_gb = metrics.get('data_size_gb', 0)
        
        duration_str = f"{duration//3600}h {(duration%3600)//60}m {duration%60}s"
        
        comment_text = f"""
*Run Completed - Performance Metrics:*

β€’ Average Throughput: {throughput:.1f} MB/s
β€’ Total Duration: {duration_str}
β€’ Data Transferred: {data_size_gb:.2f} GB
β€’ Transfer Method: {metrics.get('transfer_method', 'ssh+dd')}
β€’ Validation: {'βœ… PASSED' if metrics.get('validation_passed') else '❌ FAILED'}

*Artifacts Generated:*
{chr(10).join(f'β€’ {artifact}' for artifact in metrics.get('artifacts', []))}
        """.strip()
        
        comment_data = {
            "body": {
                "type": "doc",
                "version": 1,
                "content": [
                    {
                        "type": "paragraph",
                        "content": [
                            {"type": "text", "text": comment_text}
                        ]
                    }
                ]
            }
        }
        
        try:
            response = requests.post(
                f"{self.server_url}/rest/api/3/issue/{ticket_key}/comment",
                auth=self.auth,
                headers=self.headers,
                data=json.dumps(comment_data)
            )
            
            if response.status_code == 201:
                print(f"βœ… Added metrics to ticket {ticket_key}")
                return True
            else:
                print(f"❌ Failed to add comment: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error adding metrics: {e}")
            return False
    
    def link_to_confluence_report(self, ticket_key: str, confluence_url: str) -> bool:
        """Link Confluence post-run report to ticket"""
        if not self.auth:
            return False
        
        link_data = {
            "object": {
                "url": confluence_url,
                "title": f"Post-Run Report: {ticket_key}",
                "summary": "Detailed post-run analysis and validation report"
            }
        }
        
        try:
            response = requests.post(
                f"{self.server_url}/rest/api/3/issue/{ticket_key}/remotelink",
                auth=self.auth,
                headers=self.headers,
                data=json.dumps(link_data)
            )
            
            if response.status_code == 201:
                print(f"βœ… Linked Confluence report to {ticket_key}")
                return True
            else:
                print(f"❌ Failed to link report: {response.status_code}")
                return False
                
        except Exception as e:
            print(f"❌ Error linking report: {e}")
            return False
    
    def get_class_a_tickets(self, status: Optional[str] = None) -> List[Dict[str, Any]]:
        """Get all Class-A transfer tickets"""
        if not self.auth:
            return []
        
        jql = "project = DTO AND labels = class-a"
        if status:
            jql += f" AND status = '{status}'"
        
        try:
            response = requests.get(
                f"{self.server_url}/rest/api/3/search",
                auth=self.auth,
                headers=self.headers,
                params={
                    'jql': jql,
                    'fields': 'key,summary,status,created,updated,customfield_10001',
                    'maxResults': 100
                }
            )
            
            if response.status_code == 200:
                issues = response.json()['issues']
                return [
                    {
                        'key': issue['key'],
                        'summary': issue['fields']['summary'],
                        'status': issue['fields']['status']['name'],
                        'run_id': issue['fields'].get('customfield_10001'),
                        'created': issue['fields']['created'],
                        'updated': issue['fields']['updated']
                    }
                    for issue in issues
                ]
            else:
                print(f"❌ Failed to get tickets: {response.status_code}")
                return []
                
        except Exception as e:
            print(f"❌ Error getting tickets: {e}")
            return []

# Test function
def test_jira_integration():
    """Test Jira integration with mock Class-A run"""
    client = DTOJiraClient()
    
    if not client.test_connection():
        print("❌ Jira integration test failed (expected without proper credentials)")
        return False
    
    # Test ticket creation
    test_run = {
        'run_id': 'test-class-a-001',
        'manifest_path': '/manifests/class_a/critical_dataset.yaml',
        'data_size_bytes': 536870912000,  # 500 GB
        'initiated_by': 'data-engineer',
        'environment': 'production'
    }
    
    ticket_key = client.create_class_a_ticket(test_run)
    
    if ticket_key:
        # Test status update
        client.update_ticket_status(ticket_key, "in_progress", 
                                  "Data transfer initiated. Monitoring performance...")
        
        # Test metrics addition
        test_metrics = {
            'average_throughput_mbps': 847.3,
            'total_duration_seconds': 6480,
            'data_size_gb': 500.0,
            'transfer_method': 'ssh+dd',
            'validation_passed': True,
            'artifacts': [
                '/logs/test-class-a-001.log',
                '/reports/test-class-a-001.pdf',
                '/checksums/test-class-a-001.sha256'
            ]
        }
        
        client.add_run_metrics(ticket_key, test_metrics)
        client.update_ticket_status(ticket_key, "completed",
                                  "Data transfer completed successfully. All validations passed.")
        
        print(f"βœ… Jira integration test completed for ticket: {ticket_key}")
        return True
    
    return False

if __name__ == "__main__":
    print("Testing DTO Jira Integration...")
    print("=" * 50)
    
    test_jira_integration()
    print("\nTo use Jira integration, set these environment variables:")
    print("export JIRA_SERVER_URL=https://your-domain.atlassian.net")
    print("export JIRA_USERNAME=your-email@company.com")
    print("export JIRA_API_TOKEN=your-api-token")