"""
Python refactoring assistance logic for Storm Logger development
"""

import json
import ast
import re
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple


def refactor_code(
    file_path: str,
    refactor_type: str = "comprehensive",
    safety_level: str = "moderate",
    apply_changes: bool = False
) -> str:
    """
    Intelligent refactoring suggestions and automated improvements
    
    Args:
        file_path: Path to Python file or directory
        refactor_type: "modernize", "extract", "optimize", "type_hints", "comprehensive"
        safety_level: "conservative", "moderate", "aggressive"
        apply_changes: Whether to apply changes or just preview
        
    Returns:
        JSON string with refactoring suggestions and results
    """
    path = Path(file_path)
    
    if not path.exists():
        return json.dumps({"error": f"Path {file_path} does not exist"}, indent=2)
    
    refactoring = {
        "file_path": str(path),
        "refactor_type": refactor_type,
        "safety_level": safety_level,
        "apply_changes": apply_changes,
        "timestamp": "2025-01-18",
        "suggestions": [],
        "applied_changes": [],
        "warnings": [],
        "summary": {}
    }
    
    if path.is_file():
        file_refactoring = refactor_single_file(path, refactor_type, safety_level, apply_changes)
        refactoring.update(file_refactoring)
    else:
        directory_refactoring = refactor_directory(path, refactor_type, safety_level, apply_changes)
        refactoring.update(directory_refactoring)
    
    return json.dumps(refactoring, indent=2)


def refactor_single_file(
    file_path: Path,
    refactor_type: str,
    safety_level: str,
    apply_changes: bool
) -> Dict[str, Any]:
    """
    Refactor a single Python file
    
    Args:
        file_path: Path to Python file
        refactor_type: Type of refactoring
        safety_level: Safety level
        apply_changes: Whether to apply changes
        
    Returns:
        File refactoring results
    """
    if not file_path.suffix == '.py':
        return {"error": f"File {file_path} is not a Python file"}
    
    try:
        original_content = file_path.read_text(encoding='utf-8')
    except Exception as e:
        return {"error": f"Cannot read file {file_path}: {str(e)}"}
    
    try:
        tree = ast.parse(original_content)
    except SyntaxError as e:
        return {"error": f"Syntax error in {file_path}: {str(e)}"}
    
    refactoring = {
        "file_type": "single_file",
        "original_size": len(original_content),
        "original_lines": len(original_content.splitlines()),
        "suggestions": [],
        "applied_changes": [],
        "warnings": [],
        "summary": {}
    }
    
    # Generate refactoring suggestions based on type
    if refactor_type in ["modernize", "comprehensive"]:
        modernize_suggestions = generate_modernization_suggestions(original_content, tree, safety_level)
        refactoring["suggestions"].extend(modernize_suggestions)
    
    if refactor_type in ["extract", "comprehensive"]:
        extract_suggestions = generate_extraction_suggestions(original_content, tree, safety_level)
        refactoring["suggestions"].extend(extract_suggestions)
    
    if refactor_type in ["optimize", "comprehensive"]:
        optimize_suggestions = generate_optimization_suggestions(original_content, tree, safety_level)
        refactoring["suggestions"].extend(optimize_suggestions)
    
    if refactor_type in ["type_hints", "comprehensive"]:
        type_hint_suggestions = generate_type_hint_suggestions(original_content, tree, safety_level)
        refactoring["suggestions"].extend(type_hint_suggestions)
    
    # Apply changes if requested
    if apply_changes:
        refactored_content = apply_refactoring_suggestions(
            original_content, refactoring["suggestions"], safety_level
        )
        
        if refactored_content != original_content:
            try:
                file_path.write_text(refactored_content, encoding='utf-8')
                refactoring["applied_changes"] = [
                    {"type": "file_updated", "path": str(file_path)}
                ]
                refactoring["new_size"] = len(refactored_content)
                refactoring["new_lines"] = len(refactored_content.splitlines())
            except Exception as e:
                refactoring["warnings"].append(f"Failed to write changes: {str(e)}")
    
    # Generate summary
    refactoring["summary"] = generate_refactoring_summary(refactoring["suggestions"])
    
    return refactoring


def refactor_directory(
    dir_path: Path,
    refactor_type: str,
    safety_level: str,
    apply_changes: bool
) -> Dict[str, Any]:
    """
    Refactor a directory of Python files
    
    Args:
        dir_path: Path to directory
        refactor_type: Type of refactoring
        safety_level: Safety level
        apply_changes: Whether to apply changes
        
    Returns:
        Directory refactoring results
    """
    python_files = list(dir_path.glob("**/*.py"))
    
    if not python_files:
        return {"error": f"No Python files found in {dir_path}"}
    
    refactoring = {
        "file_type": "directory",
        "total_files": len(python_files),
        "files_processed": [],
        "suggestions": [],
        "applied_changes": [],
        "warnings": [],
        "summary": {}
    }
    
    for py_file in python_files[:5]:  # Limit to first 5 files for performance
        file_refactoring = refactor_single_file(py_file, refactor_type, safety_level, apply_changes)
        if "error" not in file_refactoring:
            refactoring["files_processed"].append({
                "file": str(py_file.relative_to(dir_path)),
                "suggestions": len(file_refactoring["suggestions"]),
                "applied_changes": len(file_refactoring["applied_changes"])
            })
            refactoring["suggestions"].extend(file_refactoring["suggestions"])
            refactoring["applied_changes"].extend(file_refactoring["applied_changes"])
    
    # Generate summary
    refactoring["summary"] = generate_directory_refactoring_summary(refactoring["files_processed"])
    
    return refactoring


def generate_modernization_suggestions(
    content: str,
    tree: ast.AST,
    safety_level: str
) -> List[Dict[str, Any]]:
    """
    Generate modernization suggestions
    
    Args:
        content: File content
        tree: AST tree
        safety_level: Safety level
        
    Returns:
        List of modernization suggestions
    """
    suggestions = []
    
    # String formatting modernization
    string_format_suggestions = modernize_string_formatting(content, tree)
    suggestions.extend(string_format_suggestions)
    
    # Dictionary comprehension suggestions
    dict_comp_suggestions = modernize_dict_comprehensions(tree)
    suggestions.extend(dict_comp_suggestions)
    
    # Exception handling modernization
    exception_suggestions = modernize_exception_handling(tree)
    suggestions.extend(exception_suggestions)
    
    # Import modernization
    import_suggestions = modernize_imports(content, tree)
    suggestions.extend(import_suggestions)
    
    # Class definition modernization
    class_suggestions = modernize_class_definitions(tree)
    suggestions.extend(class_suggestions)
    
    return suggestions


def generate_extraction_suggestions(
    content: str,
    tree: ast.AST,
    safety_level: str
) -> List[Dict[str, Any]]:
    """
    Generate extraction suggestions for functions and classes
    
    Args:
        content: File content
        tree: AST tree
        safety_level: Safety level
        
    Returns:
        List of extraction suggestions
    """
    suggestions = []
    
    # Function extraction suggestions
    function_suggestions = suggest_function_extraction(tree)
    suggestions.extend(function_suggestions)
    
    # Class extraction suggestions
    class_suggestions = suggest_class_extraction(tree)
    suggestions.extend(class_suggestions)
    
    # Variable extraction suggestions
    variable_suggestions = suggest_variable_extraction(tree)
    suggestions.extend(variable_suggestions)
    
    # Magic number extraction
    magic_number_suggestions = suggest_magic_number_extraction(tree)
    suggestions.extend(magic_number_suggestions)
    
    return suggestions


def generate_optimization_suggestions(
    content: str,
    tree: ast.AST,
    safety_level: str
) -> List[Dict[str, Any]]:
    """
    Generate optimization suggestions
    
    Args:
        content: File content
        tree: AST tree
        safety_level: Safety level
        
    Returns:
        List of optimization suggestions
    """
    suggestions = []
    
    # Loop optimization
    loop_suggestions = suggest_loop_optimizations(tree)
    suggestions.extend(loop_suggestions)
    
    # Data structure optimization
    data_structure_suggestions = suggest_data_structure_optimizations(tree)
    suggestions.extend(data_structure_suggestions)
    
    # Import optimization
    import_suggestions = suggest_import_optimizations(content, tree)
    suggestions.extend(import_suggestions)
    
    # Algorithm optimization
    algorithm_suggestions = suggest_algorithm_optimizations(tree)
    suggestions.extend(algorithm_suggestions)
    
    return suggestions


def generate_type_hint_suggestions(
    content: str,
    tree: ast.AST,
    safety_level: str
) -> List[Dict[str, Any]]:
    """
    Generate type hint suggestions
    
    Args:
        content: File content
        tree: AST tree
        safety_level: Safety level
        
    Returns:
        List of type hint suggestions
    """
    suggestions = []
    
    # Function type hints
    function_hints = suggest_function_type_hints(tree)
    suggestions.extend(function_hints)
    
    # Variable type hints
    variable_hints = suggest_variable_type_hints(tree)
    suggestions.extend(variable_hints)
    
    # Class attribute type hints
    class_hints = suggest_class_attribute_type_hints(tree)
    suggestions.extend(class_hints)
    
    # Return type hints
    return_hints = suggest_return_type_hints(tree)
    suggestions.extend(return_hints)
    
    return suggestions


# Modernization functions

def modernize_string_formatting(content: str, tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest f-string modernization"""
    suggestions = []
    
    # Look for % formatting
    percent_patterns = re.finditer(r'["\'][^"\']*%[sd][^"\']*["\']', content)
    for match in percent_patterns:
        line_num = content[:match.start()].count('\n') + 1
        suggestions.append({
            "type": "modernize_string_formatting",
            "line": line_num,
            "priority": "medium",
            "description": "Replace % formatting with f-strings",
            "original": match.group(),
            "suggested": "Use f-string: f\"...{variable}...\"",
            "reason": "F-strings are more readable and performant"
        })
    
    # Look for .format() calls
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Attribute) and node.func.attr == 'format':
                suggestions.append({
                    "type": "modernize_string_formatting",
                    "line": node.lineno,
                    "priority": "medium",
                    "description": "Replace .format() with f-strings",
                    "original": f"Line {node.lineno}",
                    "suggested": "Use f-string syntax",
                    "reason": "F-strings are more readable and performant"
                })
    
    return suggestions


def modernize_dict_comprehensions(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest dictionary comprehension modernization"""
    suggestions = []
    
    # Look for dict() calls with comprehensions
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name) and node.func.id == 'dict':
                if len(node.args) == 1 and isinstance(node.args[0], ast.GeneratorExp):
                    suggestions.append({
                        "type": "modernize_dict_comprehension",
                        "line": node.lineno,
                        "priority": "low",
                        "description": "Use dict comprehension syntax",
                        "original": f"dict(...) on line {node.lineno}",
                        "suggested": "{key: value for ...}",
                        "reason": "Dict comprehensions are more pythonic"
                    })
    
    return suggestions


def modernize_exception_handling(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest exception handling modernization"""
    suggestions = []
    
    # Look for old-style exception handling
    for node in ast.walk(tree):
        if isinstance(node, ast.Try):
            for handler in node.handlers:
                if handler.type is None:
                    suggestions.append({
                        "type": "modernize_exception_handling",
                        "line": node.lineno,
                        "priority": "high",
                        "description": "Specify exception type in except clause",
                        "original": "except:",
                        "suggested": "except SpecificException:",
                        "reason": "Bare except clauses can mask errors"
                    })
    
    return suggestions


def modernize_imports(content: str, tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest import modernization"""
    suggestions = []
    
    # Look for deprecated imports
    deprecated_imports = {
        'imp': 'importlib',
        'optparse': 'argparse',
        'distutils': 'setuptools'
    }
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name in deprecated_imports:
                    suggestions.append({
                        "type": "modernize_imports",
                        "line": node.lineno,
                        "priority": "medium",
                        "description": f"Replace deprecated import {alias.name}",
                        "original": f"import {alias.name}",
                        "suggested": f"import {deprecated_imports[alias.name]}",
                        "reason": f"{alias.name} is deprecated"
                    })
    
    return suggestions


def modernize_class_definitions(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest class definition modernization"""
    suggestions = []
    
    # Look for old-style class definitions
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            if not node.bases:  # No base classes
                suggestions.append({
                    "type": "modernize_class_definition",
                    "line": node.lineno,
                    "priority": "low",
                    "description": "Consider explicit object inheritance",
                    "original": f"class {node.name}:",
                    "suggested": f"class {node.name}:",
                    "reason": "In Python 3, explicit object inheritance is optional but clear"
                })
    
    return suggestions


# Extraction functions

def suggest_function_extraction(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest function extraction opportunities"""
    suggestions = []
    
    # Look for long functions
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            # Count statements in function
            statements = [n for n in ast.walk(node) if isinstance(n, ast.stmt)]
            if len(statements) > 20:  # Arbitrary threshold
                suggestions.append({
                    "type": "extract_function",
                    "line": node.lineno,
                    "priority": "medium",
                    "description": f"Function {node.name} is long ({len(statements)} statements)",
                    "original": f"Function {node.name}",
                    "suggested": "Consider breaking into smaller functions",
                    "reason": "Smaller functions are easier to test and understand"
                })
    
    return suggestions


def suggest_class_extraction(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest class extraction opportunities"""
    suggestions = []
    
    # Look for large classes
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            methods = [n for n in node.body if isinstance(n, ast.FunctionDef)]
            if len(methods) > 10:  # Arbitrary threshold
                suggestions.append({
                    "type": "extract_class",
                    "line": node.lineno,
                    "priority": "medium",
                    "description": f"Class {node.name} has many methods ({len(methods)})",
                    "original": f"Class {node.name}",
                    "suggested": "Consider splitting into multiple classes",
                    "reason": "Smaller classes follow single responsibility principle"
                })
    
    return suggestions


def suggest_variable_extraction(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest variable extraction opportunities"""
    suggestions = []
    
    # Look for complex expressions that could be extracted
    for node in ast.walk(tree):
        if isinstance(node, ast.BinOp):
            # Check if this is a complex expression
            if isinstance(node.left, ast.BinOp) and isinstance(node.right, ast.BinOp):
                suggestions.append({
                    "type": "extract_variable",
                    "line": node.lineno,
                    "priority": "low",
                    "description": "Complex expression could be extracted to variable",
                    "original": f"Complex expression on line {node.lineno}",
                    "suggested": "Extract to descriptive variable",
                    "reason": "Named variables improve readability"
                })
    
    return suggestions


def suggest_magic_number_extraction(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest magic number extraction"""
    suggestions = []
    
    # Look for magic numbers (constants that should be named)
    for node in ast.walk(tree):
        if isinstance(node, ast.Constant):
            if isinstance(node.value, (int, float)):
                # Skip common numbers
                if node.value not in [0, 1, -1, 2, 10, 100]:
                    suggestions.append({
                        "type": "extract_magic_number",
                        "line": node.lineno,
                        "priority": "low",
                        "description": f"Magic number {node.value} should be named",
                        "original": str(node.value),
                        "suggested": "DESCRIPTIVE_CONSTANT_NAME",
                        "reason": "Named constants improve maintainability"
                    })
    
    return suggestions


# Optimization functions

def suggest_loop_optimizations(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest loop optimizations"""
    suggestions = []
    
    # Look for inefficient loops
    for node in ast.walk(tree):
        if isinstance(node, ast.For):
            # Check for nested loops
            nested_loops = [n for n in ast.walk(node) if isinstance(n, ast.For) and n != node]
            if len(nested_loops) > 1:
                suggestions.append({
                    "type": "optimize_nested_loops",
                    "line": node.lineno,
                    "priority": "high",
                    "description": "Deeply nested loops detected",
                    "original": f"Nested loops starting at line {node.lineno}",
                    "suggested": "Consider algorithmic optimization or vectorization",
                    "reason": "Nested loops can have poor performance characteristics"
                })
    
    return suggestions


def suggest_data_structure_optimizations(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest data structure optimizations"""
    suggestions = []
    
    # Look for inefficient data structure usage
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Attribute):
                # Check for list.append in loops
                if node.func.attr == 'append':
                    # Check if we're in a loop
                    parent = node
                    while parent:
                        if isinstance(parent, ast.For):
                            suggestions.append({
                                "type": "optimize_data_structure",
                                "line": node.lineno,
                                "priority": "medium",
                                "description": "List append in loop",
                                "original": f"list.append() in loop at line {node.lineno}",
                                "suggested": "Consider list comprehension or preallocating",
                                "reason": "List comprehensions are often faster"
                            })
                            break
                        parent = getattr(parent, 'parent', None)
    
    return suggestions


def suggest_import_optimizations(content: str, tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest import optimizations"""
    suggestions = []
    
    # Look for unused imports
    imported_names = set()
    used_names = set()
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                imported_names.add(alias.name)
        elif isinstance(node, ast.ImportFrom):
            for alias in node.names:
                imported_names.add(alias.name)
        elif isinstance(node, ast.Name):
            used_names.add(node.id)
    
    unused_imports = imported_names - used_names
    if unused_imports:
        suggestions.append({
            "type": "optimize_imports",
            "line": 1,
            "priority": "low",
            "description": f"Unused imports detected: {', '.join(list(unused_imports)[:3])}",
            "original": f"{len(unused_imports)} unused imports",
            "suggested": "Remove unused imports",
            "reason": "Unused imports increase startup time and memory usage"
        })
    
    return suggestions


def suggest_algorithm_optimizations(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest algorithm optimizations"""
    suggestions = []
    
    # Look for inefficient patterns
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                # Check for sorted() on already sorted data
                if node.func.id == 'sorted':
                    suggestions.append({
                        "type": "optimize_algorithm",
                        "line": node.lineno,
                        "priority": "low",
                        "description": "sorted() call detected",
                        "original": f"sorted() at line {node.lineno}",
                        "suggested": "Verify if sorting is necessary",
                        "reason": "Avoid unnecessary sorting operations"
                    })
    
    return suggestions


# Type hint functions

def suggest_function_type_hints(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest function type hints"""
    suggestions = []
    
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            # Check if function lacks type hints
            missing_hints = []
            
            if not node.returns:
                missing_hints.append("return type")
            
            for arg in node.args.args:
                if not arg.annotation:
                    missing_hints.append(f"parameter {arg.arg}")
            
            if missing_hints:
                suggestions.append({
                    "type": "add_type_hints",
                    "line": node.lineno,
                    "priority": "medium",
                    "description": f"Function {node.name} missing type hints",
                    "original": f"def {node.name}(...)",
                    "suggested": f"def {node.name}(...) -> ReturnType:",
                    "reason": "Type hints improve code reliability and IDE support",
                    "missing_hints": missing_hints
                })
    
    return suggestions


def suggest_variable_type_hints(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest variable type hints"""
    suggestions = []
    
    # Look for complex variable assignments that could benefit from type hints
    for node in ast.walk(tree):
        if isinstance(node, ast.Assign):
            # Check if it's a complex assignment
            if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
                var_name = node.targets[0].id
                if isinstance(node.value, (ast.Dict, ast.List, ast.Set)):
                    suggestions.append({
                        "type": "add_variable_type_hint",
                        "line": node.lineno,
                        "priority": "low",
                        "description": f"Variable {var_name} could benefit from type hint",
                        "original": f"{var_name} = ...",
                        "suggested": f"{var_name}: TypeHint = ...",
                        "reason": "Type hints clarify expected data types"
                    })
    
    return suggestions


def suggest_class_attribute_type_hints(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest class attribute type hints"""
    suggestions = []
    
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            # Look for class attributes without type hints
            for item in node.body:
                if isinstance(item, ast.Assign):
                    for target in item.targets:
                        if isinstance(target, ast.Name):
                            suggestions.append({
                                "type": "add_class_attribute_type_hint",
                                "line": item.lineno,
                                "priority": "low",
                                "description": f"Class attribute {target.id} lacks type hint",
                                "original": f"{target.id} = ...",
                                "suggested": f"{target.id}: TypeHint = ...",
                                "reason": "Type hints improve class documentation"
                            })
    
    return suggestions


def suggest_return_type_hints(tree: ast.AST) -> List[Dict[str, Any]]:
    """Suggest return type hints"""
    suggestions = []
    
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            if not node.returns:
                # Analyze return statements to suggest type
                return_types = []
                for stmt in ast.walk(node):
                    if isinstance(stmt, ast.Return) and stmt.value:
                        if isinstance(stmt.value, ast.Constant):
                            return_types.append(type(stmt.value.value).__name__)
                        elif isinstance(stmt.value, ast.List):
                            return_types.append("List")
                        elif isinstance(stmt.value, ast.Dict):
                            return_types.append("Dict")
                
                if return_types:
                    most_common_type = max(set(return_types), key=return_types.count)
                    suggestions.append({
                        "type": "add_return_type_hint",
                        "line": node.lineno,
                        "priority": "medium",
                        "description": f"Function {node.name} should specify return type",
                        "original": f"def {node.name}(...):",
                        "suggested": f"def {node.name}(...) -> {most_common_type}:",
                        "reason": "Return type hints improve function documentation"
                    })
    
    return suggestions


def apply_refactoring_suggestions(
    content: str,
    suggestions: List[Dict[str, Any]],
    safety_level: str
) -> str:
    """
    Apply refactoring suggestions to content
    
    Args:
        content: Original content
        suggestions: List of suggestions to apply
        safety_level: Safety level for applying changes
        
    Returns:
        Refactored content
    """
    # This is a placeholder implementation
    # In practice, you'd implement specific transformations
    # For now, just return original content
    
    lines = content.splitlines()
    modified_lines = lines.copy()
    
    # Apply safe transformations based on safety level
    if safety_level == "aggressive":
        # Apply more transformations
        pass
    elif safety_level == "moderate":
        # Apply medium-risk transformations
        pass
    else:  # conservative
        # Apply only safe transformations
        pass
    
    # For demonstration, we'll just return the original content
    # In a real implementation, you'd apply the actual transformations
    return content


def generate_refactoring_summary(suggestions: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Generate summary of refactoring suggestions
    
    Args:
        suggestions: List of suggestions
        
    Returns:
        Summary dictionary
    """
    summary = {
        "total_suggestions": len(suggestions),
        "by_type": {},
        "by_priority": {},
        "estimated_impact": "low"
    }
    
    # Group by type
    for suggestion in suggestions:
        suggestion_type = suggestion.get("type", "unknown")
        if suggestion_type not in summary["by_type"]:
            summary["by_type"][suggestion_type] = 0
        summary["by_type"][suggestion_type] += 1
    
    # Group by priority
    for suggestion in suggestions:
        priority = suggestion.get("priority", "unknown")
        if priority not in summary["by_priority"]:
            summary["by_priority"][priority] = 0
        summary["by_priority"][priority] += 1
    
    # Estimate impact
    high_priority = summary["by_priority"].get("high", 0)
    if high_priority > 3:
        summary["estimated_impact"] = "high"
    elif high_priority > 1:
        summary["estimated_impact"] = "medium"
    
    return summary


def generate_directory_refactoring_summary(files_processed: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Generate summary for directory refactoring
    
    Args:
        files_processed: List of processed files
        
    Returns:
        Summary dictionary
    """
    total_suggestions = sum(file_info["suggestions"] for file_info in files_processed)
    total_changes = sum(file_info["applied_changes"] for file_info in files_processed)
    
    return {
        "files_processed": len(files_processed),
        "total_suggestions": total_suggestions,
        "total_changes_applied": total_changes,
        "average_suggestions_per_file": total_suggestions / len(files_processed) if files_processed else 0,
        "files_with_suggestions": len([f for f in files_processed if f["suggestions"] > 0])
    }