"""
Code Comparator Utility for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import difflib
from typing import Dict, List, Any, Tuple

class CodeComparator:
    """
    Utility class for comparing code differences
    """
    
    def __init__(self):
        pass
    
    def compare_code(self, code1: str, code2: str, language: str = 'auto') -> Dict[str, Any]:
        """
        Compare two code snippets and show differences
        """
        try:
            lines1 = code1.splitlines(keepends=True)
            lines2 = code2.splitlines(keepends=True)
            
            # Use difflib to find differences
            diff = list(difflib.unified_diff(
                lines1, lines2,
                fromfile='Original',
                tofile='Modified',
                lineterm=''
            ))
            
            # Calculate statistics
            added_lines = sum(1 for line in diff if line.startswith('+') and not line.startswith('+++'))
            removed_lines = sum(1 for line in diff if line.startswith('-') and not line.startswith('---'))
            modified_blocks = self._count_modified_blocks(diff)
            
            # Generate HTML diff
            html_diff = self._generate_html_diff(lines1, lines2)
            
            # Generate side-by-side comparison
            side_by_side = self._generate_side_by_side(lines1, lines2)
            
            return {
                'success': True,
                'diff': diff,
                'html_diff': html_diff,
                'side_by_side': side_by_side,
                'statistics': {
                    'total_lines_original': len(lines1),
                    'total_lines_modified': len(lines2),
                    'lines_added': added_lines,
                    'lines_removed': removed_lines,
                    'lines_unchanged': len(lines1) - removed_lines,
                    'modified_blocks': modified_blocks,
                    'similarity_ratio': difflib.SequenceMatcher(None, code1, code2).ratio()
                }
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'Code comparison failed: {str(e)}',
                'diff': [],
                'statistics': {}
            }
    
    def _count_modified_blocks(self, diff: List[str]) -> int:
        """Count number of modified blocks in diff"""
        blocks = 0
        in_block = False
        
        for line in diff:
            if line.startswith('@@'):
                if in_block:
                    blocks += 1
                in_block = True
            elif line.startswith(' ') and in_block:
                in_block = False
        
        if in_block:
            blocks += 1
        
        return blocks
    
    def _generate_html_diff(self, lines1: List[str], lines2: List[str]) -> str:
        """Generate HTML formatted diff"""
        diff = list(difflib.unified_diff(
            lines1, lines2,
            fromfile='Original',
            tofile='Modified',
            lineterm=''
        ))
        
        html = '<div class="diff-container">\n'
        html += '<pre class="diff">\n'
        
        for line in diff:
            if line.startswith('+++') or line.startswith('---'):
                html += f'<span class="diff-header">{line}</span>\n'
            elif line.startswith('@@'):
                html += f'<span class="diff-hunk">{line}</span>\n'
            elif line.startswith('+'):
                html += f'<span class="diff-added">{line}</span>\n'
            elif line.startswith('-'):
                html += f'<span class="diff-removed">{line}</span>\n'
            else:
                html += f'<span class="diff-context">{line}</span>\n'
        
        html += '</pre>\n'
        html += '</div>\n'
        
        return html
    
    def _generate_side_by_side(self, lines1: List[str], lines2: List[str]) -> List[Dict[str, Any]]:
        """Generate side-by-side comparison"""
        matcher = difflib.SequenceMatcher(None, lines1, lines2)
        comparison = []
        
        for tag, i1, i2, j1, j2 in matcher.get_opcodes():
            if tag == 'equal':
                for i in range(i1, i2):
                    comparison.append({
                        'type': 'equal',
                        'left': lines1[i],
                        'right': lines2[i1 + (i - i1)],
                        'line_number_left': i + 1,
                        'line_number_right': i1 + (i - i1) + 1
                    })
            elif tag == 'delete':
                for i in range(i1, i2):
                    comparison.append({
                        'type': 'delete',
                        'left': lines1[i],
                        'right': '',
                        'line_number_left': i + 1,
                        'line_number_right': None
                    })
            elif tag == 'insert':
                for j in range(j1, j2):
                    comparison.append({
                        'type': 'insert',
                        'left': '',
                        'right': lines2[j],
                        'line_number_left': None,
                        'line_number_right': j + 1
                    })
            elif tag == 'replace':
                max_len = max(i2 - i1, j2 - j1)
                for k in range(max_len):
                    comparison.append({
                        'type': 'replace',
                        'left': lines1[i1 + k] if k < (i2 - i1) else '',
                        'right': lines2[j1 + k] if k < (j2 - j1) else '',
                        'line_number_left': i1 + k + 1 if k < (i2 - i1) else None,
                        'line_number_right': j1 + k + 1 if k < (j2 - j1) else None
                    })
        
        return comparison
