import re
import uuid

def add_detailed_logging(input_file, output_file):
    """Add detailed logging before and after each significant line"""
    
    with open(input_file, 'r') as f:
        content = f.read()
    
    lines = content.split('\n')
    new_lines = []
    
    # Skip these line patterns from logging
    skip_patterns = [
        r'^\s*#',          # Comments
        r'^\s*$',          # Empty lines
        r'^\s*import',     # Import statements
        r'^\s*from.*import', # From imports
        r'^\s*logger\.',   # Already logger lines
        r'^\s*"""',        # Docstrings
        r'^\s*\'\'\'',     # Docstrings
        r'^\s*def\s+\w+',  # Function definitions (we'll handle these separately)
        r'^\s*class\s+\w+', # Class definitions
        r'^\s*if\s+__name__', # Main block
        r'^\s*try:',       # Try blocks
        r'^\s*except',     # Except blocks
        r'^\s*finally:',   # Finally blocks
        r'^\s*else:',      # Else blocks
        r'^\s*elif',       # Elif blocks
        r'^\s*if.*:$',     # If statements
        r'^\s*for.*:$',    # For loops
        r'^\s*while.*:$',  # While loops
        r'^\s*with.*:$',   # With statements
    ]
    
    # Lines that should have detailed logging
    important_patterns = [
        r'=.*\(',          # Function calls
        r'\..*\(',         # Method calls
        r'return\s+',      # Return statements
        r'raise\s+',       # Raise statements
        r'self\.\w+\s*=',  # Attribute assignments
        r'\w+\s*=.*',      # Variable assignments
    ]
    
    in_docstring = False
    current_function = None
    line_number = 0
    
    for line in lines:
        line_number += 1
        stripped = line.strip()
        
        # Handle docstrings
        if '"""' in line or "'''" in line:
            in_docstring = not in_docstring
            new_lines.append(line)
            continue
            
        if in_docstring:
            new_lines.append(line)
            continue
        
        # Check if we should skip this line
        should_skip = False
        for pattern in skip_patterns:
            if re.match(pattern, line):
                should_skip = True
                break
        
        if should_skip:
            new_lines.append(line)
            continue
        
        # Check for function definitions
        func_match = re.match(r'(\s*)def\s+(\w+)', line)
        if func_match:
            current_function = func_match.group(2)
            new_lines.append(line)
            continue
        
        # Check if this is an important line that needs logging
        is_important = False
        for pattern in important_patterns:
            if re.search(pattern, stripped):
                is_important = True
                break
        
        if is_important and stripped and not stripped.startswith(('logger.', 'logging.')):
            # Get indentation
            indent = len(line) - len(line.lstrip())
            indent_str = ' ' * indent
            
            # Create unique identifier for this line
            line_id = f"L{line_number}"
            
            # Add before logging
            new_lines.append(f'{indent_str}logger.debug(f"[{line_id}] Executing: {stripped[:50]}...")')
            
            # Add the original line
            new_lines.append(line)
            
            # Add after logging for assignments and method calls
            if '=' in stripped and not any(op in stripped for op in ['==', '!=', '<=', '>=']):
                var_name = stripped.split('=')[0].strip()
                new_lines.append(f'{indent_str}logger.debug(f"[{line_id}] Completed assignment to: {var_name}")')
            elif '(' in stripped and ')' in stripped:
                new_lines.append(f'{indent_str}logger.debug(f"[{line_id}] Completed method/function call")')
        else:
            new_lines.append(line)
    
    # Write to output file
    with open(output_file, 'w') as f:
        f.write('\n'.join(new_lines))
    
    print(f"Added detailed logging to {output_file}")

if __name__ == "__main__":
    add_detailed_logging('services/google-search/main.py', 'services/google-search/main.py.logged')
