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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
#!/usr/bin/env python3
"""
Excel Parser Script for Benefit Agent Analysis Report

This script reads data from data.json and generates an Excel report (OUTPUT.xlsx) 
in the format specified in expected-output.txt.

Business Rules:
- New records: At least 80% of total records
- Update records: Total records - new records - failure records
- Failure records: Less than total records - new records
"""

import json
import os
import random
import argparse
from datetime import datetime
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from typing import Dict, List, Tuple, Any

class BenefitAgentExcelReportGenerator:
    def __init__(self, data_file: str = "static/data.json", output_file: str = "static/OUTPUT.xlsx"):
        self.data_file = data_file
        self.output_file = output_file
        self.data = None
        self.workbook = None
        self.worksheet = None
        self.current_row = 1
        
        # Define color scheme (similar to PDF version)
        self.primary_blue = "1E3A8A"      # Dark navy blue
        self.secondary_blue = "3B82F6"    # Medium blue
        self.light_blue = "EBF8FF"        # Very light blue
        self.accent_blue = "93C5FD"       # Light accent blue
    
    def load_data(self) -> bool:
        """Load data from JSON file"""
        try:
            # Get the absolute path
            script_dir = os.path.dirname(os.path.abspath(__file__))
            file_path = os.path.join(script_dir, self.data_file)
            
            with open(file_path, 'r') as f:
                self.data = json.load(f)
            
            print(f"βœ… Successfully loaded data from {file_path}")
            print(f"   Request ID: {self.data.get('requestId')}")
            print(f"   Total records: {len(self.data.get('values', []))}")
            
            return True
        except FileNotFoundError:
            print(f"❌ Error: File {file_path} not found")
            return False
        except json.JSONDecodeError:
            print(f"❌ Error: Invalid JSON format in {file_path}")
            return False
        except Exception as e:
            print(f"❌ Error loading data: {e}")
            return False
    
    def get_user_input_for_statistics(self) -> Dict[str, int]:
        """
        Prompt user for record statistics
        
        Returns:
            Dictionary with counts for total, new, update, and failure records
        """
        if not self.data or 'values' not in self.data:
            return {"total": 0, "new": 0, "update": 0, "failure": 0}
        
        total_records = len(self.data['values'])
        
        print(f"\nπŸ“Š Record Statistics Input")
        print(f"{'='*40}")
        print(f"Total number of records available: {total_records}")
        print()
        
        while True:
            try:
                print("Please enter the record counts:")
                new_records = int(input(f"πŸ†• Number of new records (recommended: {int(total_records * 0.8)}): ").strip())
                
                if new_records < 0 or new_records > total_records:
                    print(f"❌ New records must be between 0 and {total_records}")
                    continue
                
                failure_records = int(input(f"❌ Number of failure records (max: {total_records - new_records}): ").strip())
                
                if failure_records < 0 or failure_records > total_records - new_records:
                    print(f"❌ Failure records must be between 0 and {total_records - new_records}")
                    continue
                
                update_records = total_records - new_records - failure_records
                
                print(f"\nπŸ“‹ Calculated Statistics:")
                print(f"   β€’ Total records: {total_records}")
                print(f"   β€’ New records: {new_records}")
                print(f"   β€’ Update records: {update_records}")
                print(f"   β€’ Failure records: {failure_records}")
                
                confirm = input("\nβœ… Confirm these statistics? (y/n): ").strip().lower()
                if confirm in ['y', 'yes']:
                    break
                    
            except ValueError:
                print("❌ Please enter valid numbers")
            except KeyboardInterrupt:
                print("\n\nπŸ‘‹ Operation cancelled by user")
                return {"total": 0, "new": 0, "update": 0, "failure": 0}
        
        stats = {
            "total": total_records,
            "new": new_records,
            "update": update_records,
            "failure": failure_records
        }
        
        return stats
    
    def get_automatic_statistics(self) -> Dict[str, int]:
        """
        Generate automatic statistics following business rules
        
        Returns:
            Dictionary with counts for total, new, update, and failure records
        """
        if not self.data or 'values' not in self.data:
            return {"total": 0, "new": 0, "update": 0, "failure": 0}
        
        total_records = len(self.data['values'])
        
        # Business rules
        new_records = max(1, int(total_records * 0.8))  # At least 80% are new
        failure_records = max(1, min(3, total_records - new_records))  # Small number of failures
        update_records = total_records - new_records - failure_records
        
        stats = {
            "total": total_records,
            "new": new_records,
            "update": update_records,
            "failure": failure_records
        }
        
        print(f"πŸ€– Automatic Statistics Generated:")
        print(f"   β€’ Total records: {total_records}")
        print(f"   β€’ New records: {new_records}")
        print(f"   β€’ Update records: {update_records}")
        print(f"   β€’ Failure records: {failure_records}")
        
        return stats
    
    def split_records(self, stats: Dict[str, int]) -> Tuple[List[List], List[List]]:
        """
        Split records into successful and failure records
        
        Args:
            stats: Record statistics dictionary
            
        Returns:
            Tuple of (successful_records, failure_records)
        """
        if not self.data or 'values' not in self.data:
            return [], []
        
        all_records = self.data['values'].copy()
        random.shuffle(all_records)  # Randomize which records are failures
        
        # Split records based on calculated statistics
        failure_count = stats['failure']
        
        if failure_count > 0:
            failure_records = all_records[-failure_count:]
            successful_records = all_records[:-failure_count]
        else:
            failure_records = []
            successful_records = all_records
        
        return successful_records, failure_records
    
    def setup_workbook(self):
        """Initialize the Excel workbook and worksheet"""
        self.workbook = Workbook()
        self.worksheet = self.workbook.active
        self.worksheet.title = "Benefit Agent Analysis Report"
        self.current_row = 1
    
    def add_title(self):
        """Add the main title to the Excel sheet"""
        title_cell = self.worksheet.cell(row=self.current_row, column=1)
        title_cell.value = "Benefit Agent Analysis Report"
        title_cell.font = Font(name='Arial', size=18, bold=True, color=self.primary_blue)
        title_cell.alignment = Alignment(horizontal='center')
        
        # Merge cells for title
        self.worksheet.merge_cells(f'A{self.current_row}:F{self.current_row}')
        self.current_row += 2
    
    def add_summary_section(self, stats: Dict[str, int]):
        """Add the summary section to the Excel sheet"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Summary title
        summary_title_cell = self.worksheet.cell(row=self.current_row, column=1)
        summary_title_cell.value = "Summary"
        summary_title_cell.font = Font(name='Arial', size=14, bold=True, color=self.primary_blue)
        self.current_row += 1
        
        # Summary items
        summary_items = [
            f"Total Number of records: {stats['total']}",
            f"Number of new records: {stats['new']}",
            f"Number of update records: {stats['update']}",
            f"Number of Records failing Validation: {stats['failure']}",
            "Generated By: Benefit Agent",
            "Requested By: John Doe",
            f"Requested Date: {current_time}"
        ]
        
        for item in summary_items:
            cell = self.worksheet.cell(row=self.current_row, column=1)
            cell.value = item
            cell.font = Font(name='Arial', size=10)
            self.current_row += 1
        
        self.current_row += 1  # Add space after summary
    
    def add_table(self, data: List[List], title: str):
        """
        Add a table with proper formatting to the Excel sheet
        
        Args:
            data: List of rows (including header)
            title: Title for the table
        """
        if not data:
            # Add "No records" message
            cell = self.worksheet.cell(row=self.current_row, column=1)
            cell.value = f"{title}: No records to display"
            cell.font = Font(name='Arial', size=11, italic=True)
            self.current_row += 2
            return
        
        # Add table title
        title_cell = self.worksheet.cell(row=self.current_row, column=1)
        title_cell.value = title
        title_cell.font = Font(name='Arial', size=12, bold=True, color=self.secondary_blue)
        self.current_row += 1
        
        start_row = self.current_row
        
        # Add table data
        for row_idx, row_data in enumerate(data):
            for col_idx, cell_value in enumerate(row_data):
                cell = self.worksheet.cell(row=self.current_row, column=col_idx + 1)
                cell.value = cell_value
                cell.alignment = Alignment(horizontal='center', vertical='center')
                
                # Header row styling
                if row_idx == 0:
                    cell.font = Font(name='Arial', size=10, bold=True, color='FFFFFF')
                    cell.fill = PatternFill(start_color=self.primary_blue, end_color=self.primary_blue, fill_type='solid')
                else:
                    cell.font = Font(name='Arial', size=9)
                    # Alternate row coloring
                    if row_idx % 2 == 0:
                        cell.fill = PatternFill(start_color=self.light_blue, end_color=self.light_blue, fill_type='solid')
                
                # Add borders
                thin_border = Border(
                    left=Side(style='thin', color=self.secondary_blue),
                    right=Side(style='thin', color=self.secondary_blue),
                    top=Side(style='thin', color=self.secondary_blue),
                    bottom=Side(style='thin', color=self.secondary_blue)
                )
                cell.border = thin_border
                
            self.current_row += 1
        
        # Auto-adjust column widths
        end_row = self.current_row - 1
        num_cols = len(data[0]) if data else 0
        
        for col_idx in range(1, num_cols + 1):
            column_letter = get_column_letter(col_idx)
            max_width = 0
            
            for row_idx in range(start_row, end_row + 1):
                cell_value = str(self.worksheet.cell(row=row_idx, column=col_idx).value or "")
                max_width = max(max_width, len(cell_value))
            
            # Set reasonable width limits
            adjusted_width = min(max(max_width + 2, 10), 30)
            self.worksheet.column_dimensions[column_letter].width = adjusted_width
        
        self.current_row += 1  # Add space after table
    
    def prepare_successful_records_table(self, successful_records: List[List]) -> List[List]:
        """Prepare successful records table data dynamically based on data.json columns"""
        if not successful_records:
            return []
        
        # Get columns from data.json dynamically
        columns = self.data.get('columns', [])
        
        # Create dynamic table header with S.NO. and REQUEST ID as first columns, then data columns
        table_header = ["S.NO.", "REQUEST ID"] + [col.upper() for col in columns]
        table_data = [table_header]
        
        # Add data rows dynamically
        for i, record in enumerate(successful_records, 1):
            row = [str(i), self.data.get('requestId', '')] + [str(value) for value in record]
            table_data.append(row)
        
        return table_data
    
    def prepare_failure_records_table(self, failure_records: List[List]) -> List[List]:
        """Prepare failure records table data dynamically based on data.json columns"""
        if not failure_records:
            return []
        
        # Get columns from data.json dynamically
        columns = self.data.get('columns', [])
        
        # Create dynamic table header - same structure as successful records
        table_header = ["S.NO.", "REQUEST ID"] + [col.upper() for col in columns]
        table_data = [table_header]
        
        # Add data rows dynamically
        for i, record in enumerate(failure_records, 1):
            row = [str(i), self.data.get('requestId', '')] + [str(value) for value in record]
            table_data.append(row)
        
        return table_data
    
    def generate_excel(self, interactive: bool = True) -> bool:
        """Generate the Excel report following the expected output format"""
        try:
            # Get statistics
            if interactive:
                stats = self.get_user_input_for_statistics()
            else:
                stats = self.get_automatic_statistics()
            
            if stats['total'] == 0:
                print("❌ No data to process")
                return False
            
            # Split records
            successful_records, failure_records = self.split_records(stats)
            
            print(f"\nπŸ“‹ Processing Records:")
            print(f"   β€’ Successful records: {len(successful_records)}")
            print(f"   β€’ Failure records: {len(failure_records)}")
            
            # Setup workbook
            self.setup_workbook()
            
            # Add title
            self.add_title()
            
            # Add summary section
            self.add_summary_section(stats)
            
            # Add successful records table
            successful_table_data = self.prepare_successful_records_table(successful_records)
            self.add_table(successful_table_data, "Generated Records")
            
            # Add failure records table
            failure_table_data = self.prepare_failure_records_table(failure_records)
            self.add_table(failure_table_data, "Failure Records")
            
            # Save the workbook
            script_dir = os.path.dirname(os.path.abspath(__file__))
            output_path = os.path.join(script_dir, self.output_file)
            self.workbook.save(output_path)
            
            print(f"βœ… Excel report saved successfully: {output_path}")
            return True
            
        except Exception as e:
            print(f"❌ Error generating Excel report: {e}")
            return False
    
    def run(self, interactive: bool = True) -> bool:
        """Run the complete parsing and Excel generation process"""
        print("πŸš€ Starting Professional Benefit Agent Excel Report Generation")
        print("=" * 60)
        
        # Load data
        if not self.load_data():
            return False
        
        # Generate Excel
        if not self.generate_excel(interactive=interactive):
            return False
        
        print("βœ… Professional Excel report generation completed successfully!")
        return True

def main():
    """Main function"""
    parser = argparse.ArgumentParser(description="Generate Professional Benefit Agent Analysis Excel Report")
    parser.add_argument("--data", default="static/data.json", help="Path to input data JSON file")
    parser.add_argument("--output", default="static/OUTPUT.xlsx", help="Path for output Excel file")
    parser.add_argument("--auto", action="store_true", help="Run in automatic mode (no user input)")
    parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
    
    args = parser.parse_args()
    
    # Create report generator
    generator = BenefitAgentExcelReportGenerator(args.data, args.output)
    
    # Determine if interactive mode
    interactive_mode = not args.auto
    
    print(f"πŸ“‹ Mode: {'Interactive' if interactive_mode else 'Automatic'}")
    if interactive_mode:
        print("πŸ’‘ You will be prompted to enter record statistics")
    else:
        print("πŸ€– Using automatic calculation for record statistics")
    print()
    
    # Run the generation process
    success = generator.run(interactive=interactive_mode)
    
    if success:
        print("\nπŸŽ‰ Professional Excel report generated successfully!")
        print(f"πŸ“„ Output file: {args.output}")
        print("πŸ“Š The report includes:")
        print("   β€’ Professional executive summary")
        print("   β€’ Properly formatted and aligned tables")
        print("   β€’ Enhanced styling and colors")
        print("   β€’ Comprehensive record statistics")
        print("   β€’ Auto-sized columns for readability")
    else:
        print("\n❌ Report generation failed!")
        return 1
    
    return 0

if __name__ == "__main__":
    exit(main())