dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
"""
Data processing module using deprecated library functions.

This module shows realistic usage of deprecated functions in a 
data processing context.
"""

import sys
import os
import asyncio

# Add the library to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from library.utils import old_add, old_multiply, square, old_format_string
from library.models import OldDataProcessor, LegacyUser
from library.async_ops import old_fetch_data, get_json
from library.processors import ProcessingEngine
from library.config import OLD_API_URL, OLD_TIMEOUT, AppConfig
from library.containers import LegacyContainer, SmartList


class DataAnalyzer:
    """
    Data analyzer that uses deprecated library functions.
    
    This class will need to be updated when the deprecated functions
    are migrated.
    """
    
    def __init__(self, data_source):
        # Using deprecated class
        self.processor = OldDataProcessor(data_source, cache_size=100)
        
        # Using deprecated config
        self.api_url = OLD_API_URL
        self.timeout = OLD_TIMEOUT
        self.page_size = AppConfig.LEGACY_PAGE_SIZE
    
    def calculate_metrics(self, values):
        """Calculate various metrics using deprecated math functions."""
        total = 0
        squares_sum = 0
        
        for value in values:
            # Using deprecated functions
            total = old_add(total, value)
            square_val = square(value)
            squares_sum = old_add(squares_sum, square_val)
        
        # More deprecated calculations
        mean = total / len(values) if values else 0
        variance = squares_sum / len(values) if values else 0
        
        return {
            "total": total,
            "mean": mean,
            "variance": variance,
            "count": len(values)
        }
    
    def process_user_data(self, user_info):
        """Process user data using deprecated user class."""
        user = LegacyUser(user_info["name"], user_info["email"])
        
        # Using deprecated methods
        display_name = user.get_name()
        user.set_profile_data({"age": user_info.get("age", 0)})
        
        # Using deprecated property
        is_active = user.is_enabled
        
        return {
            "display_name": display_name,
            "is_active": is_active,
            "profile": user._user.get_profile()
        }
    
    def format_report(self, template, data):
        """Format a report using deprecated formatting function."""
        # Using deprecated function with complex parameters
        return old_format_string(
            template,
            data.get("title", "Report"),
            data.get("date", "Today"),
            uppercase=data.get("header_caps", False)
        )
    
    def validate_inputs(self, inputs):
        """Validate inputs using deprecated static methods."""
        # Using deprecated static methods
        for item in inputs:
            is_valid = ProcessingEngine.old_validate_data([item])
            if not is_valid:
                return False
        return True
    
    async def fetch_external_data(self, endpoint):
        """Fetch data using deprecated async functions."""
        # Using deprecated async functions
        if endpoint.startswith("json/"):
            return await get_json(endpoint[5:])  # Remove 'json/' prefix
        else:
            full_url = f"{self.api_url}/{endpoint}"
            return await old_fetch_data(full_url)


class ReportGenerator:
    """
    Report generator using deprecated container methods.
    """
    
    def __init__(self):
        # Using deprecated containers
        self.data_container = LegacyContainer()
        self.results_list = SmartList()
    
    def add_data_point(self, data):
        """Add data using deprecated container methods."""
        # Using deprecated methods instead of magic methods
        current_size = self.data_container.size()
        self.data_container._items.append(data)
        
        # Check if we have data using deprecated method
        has_data = self.data_container.contains(data)
        
        if has_data:
            # Add to results using deprecated list methods
            result_count = self.results_list.get_count()
            self.results_list.append(f"Data point #{result_count + 1}: {data}")
    
    def generate_summary(self):
        """Generate summary using deprecated methods."""
        # Using deprecated methods
        total_items = self.data_container.size()
        results_count = self.results_list.length()
        is_empty = self.results_list.is_empty()
        
        if is_empty:
            return "No data to summarize"
        
        # Get items using deprecated methods
        sample_data = []
        for i in range(min(3, total_items)):
            item = self.data_container.get_item(i)
            sample_data.append(str(item))
        
        return {
            "total_data_points": total_items,
            "total_results": results_count,
            "sample_data": sample_data,
            "has_data": not is_empty
        }


def process_financial_data(transactions):
    """
    Process financial transactions using deprecated functions.
    """
    balance = 0
    fees_total = 0
    
    for transaction in transactions:
        amount = transaction.get("amount", 0)
        fee = transaction.get("fee", 0)
        
        # Using deprecated math functions
        if transaction.get("type") == "deposit":
            balance = old_add(balance, amount)
        elif transaction.get("type") == "withdrawal":
            balance = old_add(balance, -amount)  # Subtracting by adding negative
        
        # Calculate compound fee using deprecated multiply
        compound_fee = old_multiply(fee, 1.1)  # 10% processing overhead
        fees_total = old_add(fees_total, compound_fee)
    
    return {
        "final_balance": balance,
        "total_fees": fees_total,
        "transaction_count": len(transactions)
    }


async def main():
    """Main function demonstrating realistic usage of deprecated functions."""
    print("=== Data Processing Example ===")
    print("This module shows realistic usage of deprecated functions.")
    
    # Initialize analyzer with deprecated components
    analyzer = DataAnalyzer("financial_data.db")
    
    # Sample data
    sample_values = [10, 20, 30, 40, 50]
    metrics = analyzer.calculate_metrics(sample_values)
    print(f"Calculated metrics: {metrics}")
    
    # Process user data
    user_info = {"name": "alice_smith", "email": "alice@example.com", "age": 28}
    user_data = analyzer.process_user_data(user_info)
    print(f"Processed user data: {user_data}")
    
    # Format report
    report_data = {"title": "Monthly Analysis", "date": "2024-01-15", "header_caps": True}
    report = analyzer.format_report("Report: {} - Generated on {}", report_data)
    print(f"Formatted report: {report}")
    
    # Validate inputs
    test_inputs = ["valid_data", "more_data"]
    is_valid = analyzer.validate_inputs(test_inputs)
    print(f"Input validation result: {is_valid}")
    
    # Test report generator
    report_gen = ReportGenerator()
    report_gen.add_data_point("Sample data 1")
    report_gen.add_data_point("Sample data 2")
    report_gen.add_data_point("Sample data 3")
    
    summary = report_gen.generate_summary()
    print(f"Report summary: {summary}")
    
    # Process financial data
    transactions = [
        {"type": "deposit", "amount": 100, "fee": 1},
        {"type": "withdrawal", "amount": 30, "fee": 0.5},
        {"type": "deposit", "amount": 50, "fee": 1}
    ]
    
    financial_result = process_financial_data(transactions)
    print(f"Financial processing result: {financial_result}")
    
    # Async operations
    try:
        print("\nFetching external data...")
        external_data = await analyzer.fetch_external_data("json/test_data")
        print(f"External data fetched: {external_data}")
    except Exception as e:
        print(f"Error fetching external data: {e}")
    
    print("\n=== Migration Instructions ===")
    print("To migrate this code:")
    print("1. Run: dissolve migrate consumer/data_processing.py")
    print("2. Review the changes")
    print("3. Run: dissolve migrate --write consumer/data_processing.py")


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