"""
Python dependency management logic for Storm Logger development
"""

import json
import re
import subprocess
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from urllib.parse import urlparse


def manage_dependencies(
    project_path: str,
    operation: str = "analyze",
    update_strategy: str = "conservative",
    security_scan: bool = True
) -> str:
    """
    Comprehensive dependency management and analysis
    
    Args:
        project_path: Path to Python project directory
        operation: "analyze", "update", "security_scan", "cleanup", "comprehensive"
        update_strategy: "conservative", "moderate", "aggressive"
        security_scan: Whether to perform security vulnerability scanning
        
    Returns:
        JSON string with dependency analysis and recommendations
    """
    path = Path(project_path)
    
    if not path.exists():
        return json.dumps({"error": f"Project path {project_path} does not exist"}, indent=2)
    
    if not path.is_dir():
        return json.dumps({"error": f"Path {project_path} is not a directory"}, indent=2)
    
    dependency_analysis = {
        "project_path": str(path),
        "operation": operation,
        "update_strategy": update_strategy,
        "security_scan": security_scan,
        "timestamp": "2025-01-18",
        "requirements_files": [],
        "dependencies": {},
        "vulnerabilities": [],
        "outdated_packages": [],
        "recommendations": [],
        "storm_logger_integration": {},
        "summary": {}
    }
    
    try:
        # Find requirements files
        requirements_files = find_requirements_files(path)
        dependency_analysis["requirements_files"] = requirements_files
        
        # Analyze dependencies
        if operation in ["analyze", "comprehensive"]:
            dependency_analysis["dependencies"] = analyze_dependencies(path, requirements_files)
        
        # Check for outdated packages
        if operation in ["update", "comprehensive"]:
            dependency_analysis["outdated_packages"] = check_outdated_packages(path, update_strategy)
        
        # Security vulnerability scanning
        if security_scan and operation in ["security_scan", "comprehensive"]:
            dependency_analysis["vulnerabilities"] = scan_vulnerabilities(path)
        
        # Cleanup unused dependencies
        if operation in ["cleanup", "comprehensive"]:
            dependency_analysis["unused_dependencies"] = find_unused_dependencies(path)
        
        # Generate recommendations
        dependency_analysis["recommendations"] = generate_dependency_recommendations(
            dependency_analysis, update_strategy
        )
        
        # Storm Logger integration analysis
        dependency_analysis["storm_logger_integration"] = analyze_storm_logger_integration(
            dependency_analysis["dependencies"]
        )
        
        # Generate summary
        dependency_analysis["summary"] = generate_dependency_summary(dependency_analysis)
        
        return json.dumps(dependency_analysis, indent=2)
        
    except Exception as e:
        return json.dumps({"error": f"Dependency management failed: {str(e)}"}, indent=2)


def find_requirements_files(project_path: Path) -> List[Dict[str, Any]]:
    """
    Find all requirements files in the project
    
    Args:
        project_path: Path to project directory
        
    Returns:
        List of requirements files with metadata
    """
    requirements_files = []
    
    # Common requirements file patterns
    patterns = [
        "requirements.txt",
        "requirements*.txt",
        "dev-requirements.txt",
        "requirements-dev.txt",
        "test-requirements.txt",
        "requirements-test.txt",
        "pyproject.toml",
        "setup.py",
        "setup.cfg",
        "Pipfile",
        "poetry.lock",
        "environment.yml"
    ]
    
    for pattern in patterns:
        files = list(project_path.glob(pattern))
        for file_path in files:
            file_info = {
                "path": str(file_path.relative_to(project_path)),
                "type": detect_requirements_file_type(file_path),
                "size": file_path.stat().st_size,
                "last_modified": file_path.stat().st_mtime,
                "dependencies_count": count_dependencies_in_file(file_path)
            }
            requirements_files.append(file_info)
    
    return requirements_files


def detect_requirements_file_type(file_path: Path) -> str:
    """
    Detect the type of requirements file
    
    Args:
        file_path: Path to requirements file
        
    Returns:
        File type identifier
    """
    name = file_path.name.lower()
    
    if name == "pyproject.toml":
        return "pyproject_toml"
    elif name in ["setup.py", "setup.cfg"]:
        return "setuptools"
    elif name == "pipfile":
        return "pipenv"
    elif name == "poetry.lock":
        return "poetry"
    elif name == "environment.yml":
        return "conda"
    elif "requirements" in name:
        if "dev" in name or "test" in name:
            return "development"
        else:
            return "production"
    else:
        return "unknown"


def count_dependencies_in_file(file_path: Path) -> int:
    """
    Count dependencies in a requirements file
    
    Args:
        file_path: Path to requirements file
        
    Returns:
        Number of dependencies
    """
    try:
        content = file_path.read_text(encoding='utf-8')
        
        if file_path.name == "pyproject.toml":
            # Count dependencies in pyproject.toml
            import re
            dependencies_section = re.search(r'dependencies\s*=\s*\[(.*?)\]', content, re.DOTALL)
            if dependencies_section:
                deps = dependencies_section.group(1)
                return len(re.findall(r'"[^"]*"', deps))
        
        elif file_path.name in ["setup.py", "setup.cfg"]:
            # Count dependencies in setup files
            install_requires = re.search(r'install_requires\s*=\s*\[(.*?)\]', content, re.DOTALL)
            if install_requires:
                deps = install_requires.group(1)
                return len(re.findall(r'"[^"]*"', deps))
        
        else:
            # Count dependencies in requirements.txt format
            lines = content.splitlines()
            deps = [line.strip() for line in lines if line.strip() and not line.strip().startswith('#')]
            return len(deps)
    
    except Exception:
        return 0
    
    return 0


def analyze_dependencies(project_path: Path, requirements_files: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Analyze project dependencies comprehensively
    
    Args:
        project_path: Path to project directory
        requirements_files: List of requirements files
        
    Returns:
        Dependency analysis results
    """
    analysis = {
        "total_dependencies": 0,
        "direct_dependencies": [],
        "transitive_dependencies": [],
        "dependency_tree": {},
        "conflicts": [],
        "version_constraints": {},
        "license_analysis": {},
        "size_analysis": {}
    }
    
    # Parse dependencies from all requirements files
    all_dependencies = {}
    
    for req_file in requirements_files:
        file_path = project_path / req_file["path"]
        deps = parse_dependencies_from_file(file_path)
        
        for dep_name, dep_info in deps.items():
            if dep_name not in all_dependencies:
                all_dependencies[dep_name] = dep_info
            else:
                # Check for version conflicts
                existing_version = all_dependencies[dep_name].get("version")
                new_version = dep_info.get("version")
                
                if existing_version and new_version and existing_version != new_version:
                    conflict = {
                        "package": dep_name,
                        "version1": existing_version,
                        "version2": new_version,
                        "files": [all_dependencies[dep_name]["source"], req_file["path"]]
                    }
                    analysis["conflicts"].append(conflict)
    
    analysis["total_dependencies"] = len(all_dependencies)
    analysis["direct_dependencies"] = list(all_dependencies.keys())
    
    # Analyze version constraints
    analysis["version_constraints"] = analyze_version_constraints(all_dependencies)
    
    # Get dependency tree (if pip is available)
    try:
        analysis["dependency_tree"] = get_dependency_tree(project_path)
    except Exception:
        analysis["dependency_tree"] = {}
    
    return analysis


def parse_dependencies_from_file(file_path: Path) -> Dict[str, Any]:
    """
    Parse dependencies from a requirements file
    
    Args:
        file_path: Path to requirements file
        
    Returns:
        Dictionary of dependencies with metadata
    """
    dependencies = {}
    
    try:
        content = file_path.read_text(encoding='utf-8')
        
        if file_path.name == "pyproject.toml":
            dependencies = parse_pyproject_toml(content, file_path)
        elif file_path.name in ["setup.py", "setup.cfg"]:
            dependencies = parse_setup_file(content, file_path)
        else:
            dependencies = parse_requirements_txt(content, file_path)
    
    except Exception as e:
        print(f"Error parsing {file_path}: {e}")
    
    return dependencies


def parse_requirements_txt(content: str, file_path: Path) -> Dict[str, Any]:
    """
    Parse requirements.txt format
    
    Args:
        content: File content
        file_path: Path to file
        
    Returns:
        Dictionary of dependencies
    """
    dependencies = {}
    
    lines = content.splitlines()
    for line_num, line in enumerate(lines, 1):
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        
        # Parse requirement line
        dep_info = parse_requirement_line(line)
        if dep_info:
            dep_info["source"] = str(file_path)
            dep_info["line_number"] = line_num
            dependencies[dep_info["name"]] = dep_info
    
    return dependencies


def parse_requirement_line(line: str) -> Optional[Dict[str, Any]]:
    """
    Parse a single requirement line
    
    Args:
        line: Requirement line
        
    Returns:
        Dependency information or None
    """
    # Remove options and extras
    line = re.sub(r'\s*#.*$', '', line)  # Remove comments
    line = re.sub(r'\s*--.*$', '', line)  # Remove pip options
    
    # Handle different requirement formats
    if '==' in line:
        name, version = line.split('==', 1)
        constraint = '=='
    elif '>=' in line:
        name, version = line.split('>=', 1)
        constraint = '>='
    elif '>' in line:
        name, version = line.split('>', 1)
        constraint = '>'
    elif '<=' in line:
        name, version = line.split('<=', 1)
        constraint = '<='
    elif '<' in line:
        name, version = line.split('<', 1)
        constraint = '<'
    elif '~=' in line:
        name, version = line.split('~=', 1)
        constraint = '~='
    else:
        name = line
        version = None
        constraint = None
    
    name = name.strip()
    if not name:
        return None
    
    return {
        "name": name,
        "version": version.strip() if version else None,
        "constraint": constraint,
        "original_line": line
    }


def parse_pyproject_toml(content: str, file_path: Path) -> Dict[str, Any]:
    """
    Parse pyproject.toml dependencies
    
    Args:
        content: File content
        file_path: Path to file
        
    Returns:
        Dictionary of dependencies
    """
    dependencies = {}
    
    # Extract dependencies section
    deps_match = re.search(r'dependencies\s*=\s*\[(.*?)\]', content, re.DOTALL)
    if deps_match:
        deps_content = deps_match.group(1)
        
        # Find all quoted strings
        deps_list = re.findall(r'"([^"]*)"', deps_content)
        
        for dep in deps_list:
            dep_info = parse_requirement_line(dep)
            if dep_info:
                dep_info["source"] = str(file_path)
                dependencies[dep_info["name"]] = dep_info
    
    return dependencies


def parse_setup_file(content: str, file_path: Path) -> Dict[str, Any]:
    """
    Parse setup.py or setup.cfg dependencies
    
    Args:
        content: File content
        file_path: Path to file
        
    Returns:
        Dictionary of dependencies
    """
    dependencies = {}
    
    # Extract install_requires
    install_requires_match = re.search(r'install_requires\s*=\s*\[(.*?)\]', content, re.DOTALL)
    if install_requires_match:
        deps_content = install_requires_match.group(1)
        
        # Find all quoted strings
        deps_list = re.findall(r'"([^"]*)"', deps_content)
        
        for dep in deps_list:
            dep_info = parse_requirement_line(dep)
            if dep_info:
                dep_info["source"] = str(file_path)
                dependencies[dep_info["name"]] = dep_info
    
    return dependencies


def analyze_version_constraints(dependencies: Dict[str, Any]) -> Dict[str, Any]:
    """
    Analyze version constraints for dependencies
    
    Args:
        dependencies: Dictionary of dependencies
        
    Returns:
        Version constraint analysis
    """
    analysis = {
        "pinned_versions": 0,
        "flexible_versions": 0,
        "unconstrained_versions": 0,
        "problematic_constraints": []
    }
    
    for dep_name, dep_info in dependencies.items():
        constraint = dep_info.get("constraint")
        
        if constraint == "==":
            analysis["pinned_versions"] += 1
        elif constraint in [">=", ">", "<=", "<", "~="]:
            analysis["flexible_versions"] += 1
        else:
            analysis["unconstrained_versions"] += 1
        
        # Check for problematic constraints
        if constraint == ">=":
            analysis["problematic_constraints"].append({
                "package": dep_name,
                "issue": "Unbounded upper constraint",
                "suggestion": "Consider adding upper bound"
            })
    
    return analysis


def get_dependency_tree(project_path: Path) -> Dict[str, Any]:
    """
    Get dependency tree using pip
    
    Args:
        project_path: Path to project directory
        
    Returns:
        Dependency tree information
    """
    try:
        # Try to run pip show to get dependency information
        result = subprocess.run(
            ["pip", "list", "--format=json"],
            capture_output=True,
            text=True,
            cwd=project_path,
            timeout=30
        )
        
        if result.returncode == 0:
            installed_packages = json.loads(result.stdout)
            
            tree = {}
            for package in installed_packages:
                tree[package["name"]] = {
                    "version": package["version"],
                    "dependencies": []  # Would need pip-tools or similar for full tree
                }
            
            return tree
    
    except Exception:
        pass
    
    return {}


def check_outdated_packages(project_path: Path, update_strategy: str) -> List[Dict[str, Any]]:
    """
    Check for outdated packages
    
    Args:
        project_path: Path to project directory
        update_strategy: Update strategy
        
    Returns:
        List of outdated packages
    """
    outdated_packages = []
    
    try:
        # Try to run pip list --outdated
        result = subprocess.run(
            ["pip", "list", "--outdated", "--format=json"],
            capture_output=True,
            text=True,
            cwd=project_path,
            timeout=30
        )
        
        if result.returncode == 0:
            outdated_data = json.loads(result.stdout)
            
            for package in outdated_data:
                outdated_info = {
                    "name": package["name"],
                    "current_version": package["version"],
                    "latest_version": package["latest_version"],
                    "type": package.get("latest_filetype", "unknown"),
                    "update_priority": determine_update_priority(package, update_strategy)
                }
                outdated_packages.append(outdated_info)
    
    except Exception:
        # Fallback: generate mock data for demonstration
        outdated_packages = generate_mock_outdated_packages()
    
    return outdated_packages


def determine_update_priority(package: Dict[str, Any], update_strategy: str) -> str:
    """
    Determine update priority based on strategy
    
    Args:
        package: Package information
        update_strategy: Update strategy
        
    Returns:
        Update priority level
    """
    current_version = package["version"]
    latest_version = package["latest_version"]
    
    # Parse version numbers (simplified)
    try:
        current_parts = [int(x) for x in current_version.split('.')]
        latest_parts = [int(x) for x in latest_version.split('.')]
        
        # Check version difference
        if len(current_parts) >= 1 and len(latest_parts) >= 1:
            if latest_parts[0] > current_parts[0]:
                # Major version change
                if update_strategy == "aggressive":
                    return "high"
                else:
                    return "low"  # Major updates are risky
            elif len(current_parts) >= 2 and len(latest_parts) >= 2:
                if latest_parts[1] > current_parts[1]:
                    # Minor version change
                    return "medium"
                else:
                    # Patch version change
                    return "high"
    
    except ValueError:
        pass
    
    return "medium"


def generate_mock_outdated_packages() -> List[Dict[str, Any]]:
    """
    Generate mock outdated packages for demonstration
    
    Returns:
        List of mock outdated packages
    """
    return [
        {
            "name": "requests",
            "current_version": "2.28.1",
            "latest_version": "2.31.0",
            "type": "wheel",
            "update_priority": "medium"
        },
        {
            "name": "numpy",
            "current_version": "1.21.0",
            "latest_version": "1.26.0",
            "type": "wheel",
            "update_priority": "high"
        },
        {
            "name": "django",
            "current_version": "4.1.0",
            "latest_version": "5.0.0",
            "type": "wheel",
            "update_priority": "low"
        }
    ]


def scan_vulnerabilities(project_path: Path) -> List[Dict[str, Any]]:
    """
    Scan for security vulnerabilities
    
    Args:
        project_path: Path to project directory
        
    Returns:
        List of vulnerabilities found
    """
    vulnerabilities = []
    
    try:
        # Try to run pip-audit or safety
        result = subprocess.run(
            ["pip-audit", "--format=json"],
            capture_output=True,
            text=True,
            cwd=project_path,
            timeout=60
        )
        
        if result.returncode == 0:
            audit_data = json.loads(result.stdout)
            
            for vuln in audit_data.get("vulnerabilities", []):
                vulnerability = {
                    "package": vuln["package"],
                    "version": vuln["version"],
                    "vulnerability_id": vuln["id"],
                    "severity": vuln.get("severity", "unknown"),
                    "description": vuln.get("description", ""),
                    "fix_versions": vuln.get("fix_versions", []),
                    "more_info": vuln.get("more_info", "")
                }
                vulnerabilities.append(vulnerability)
    
    except Exception:
        # Fallback: generate mock vulnerabilities for demonstration
        vulnerabilities = generate_mock_vulnerabilities()
    
    return vulnerabilities


def generate_mock_vulnerabilities() -> List[Dict[str, Any]]:
    """
    Generate mock vulnerabilities for demonstration
    
    Returns:
        List of mock vulnerabilities
    """
    return [
        {
            "package": "requests",
            "version": "2.28.1",
            "vulnerability_id": "CVE-2023-32681",
            "severity": "medium",
            "description": "Potential vulnerability in certificate verification",
            "fix_versions": ["2.31.0"],
            "more_info": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-32681"
        },
        {
            "package": "pillow",
            "version": "9.0.0",
            "vulnerability_id": "CVE-2023-50447",
            "severity": "high",
            "description": "Arbitrary code execution vulnerability",
            "fix_versions": ["10.0.1"],
            "more_info": "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-50447"
        }
    ]


def find_unused_dependencies(project_path: Path) -> List[Dict[str, Any]]:
    """
    Find unused dependencies in the project
    
    Args:
        project_path: Path to project directory
        
    Returns:
        List of unused dependencies
    """
    unused_deps = []
    
    try:
        # This is a simplified implementation
        # In practice, would use tools like unimport or pipreqs
        
        # Find all Python files
        python_files = list(project_path.glob("**/*.py"))
        
        # Extract all import statements
        imported_packages = set()
        for py_file in python_files:
            try:
                content = py_file.read_text(encoding='utf-8')
                
                # Find import statements
                import_matches = re.findall(r'^import\s+([a-zA-Z_][a-zA-Z0-9_]*)', content, re.MULTILINE)
                from_matches = re.findall(r'^from\s+([a-zA-Z_][a-zA-Z0-9_]*)', content, re.MULTILINE)
                
                imported_packages.update(import_matches)
                imported_packages.update(from_matches)
            
            except Exception:
                continue
        
        # Compare with requirements (simplified)
        requirements_files = find_requirements_files(project_path)
        all_deps = set()
        
        for req_file in requirements_files:
            file_path = project_path / req_file["path"]
            deps = parse_dependencies_from_file(file_path)
            all_deps.update(deps.keys())
        
        # Find potentially unused dependencies
        for dep in all_deps:
            if dep.lower() not in [pkg.lower() for pkg in imported_packages]:
                unused_deps.append({
                    "name": dep,
                    "confidence": "medium",
                    "reason": "Not found in import statements"
                })
    
    except Exception:
        pass
    
    return unused_deps


def analyze_storm_logger_integration(dependencies: Dict[str, Any]) -> Dict[str, Any]:
    """
    Analyze Storm Logger integration in dependencies
    
    Args:
        dependencies: Dictionary of dependencies
        
    Returns:
        Storm Logger integration analysis
    """
    integration = {
        "storm_logger_present": False,
        "storm_logger_version": None,
        "compatible_versions": [],
        "integration_opportunities": [],
        "recommended_additions": []
    }
    
    # Check if Storm Logger is present
    direct_deps = dependencies.get("direct_dependencies", [])
    if "storm-logger" in direct_deps:
        integration["storm_logger_present"] = True
        # Would extract version from actual dependency info
        integration["storm_logger_version"] = "2.0.3"
    
    # Check for compatible packages
    compatible_packages = {
        "rich": "Enhanced console output",
        "colorama": "Cross-platform color support",
        "click": "CLI framework integration",
        "fastapi": "API framework integration",
        "django": "Web framework integration",
        "flask": "Web framework integration",
        "pytest": "Testing framework integration",
        "sqlalchemy": "Database ORM integration"
    }
    
    for pkg, description in compatible_packages.items():
        if pkg in direct_deps:
            integration["integration_opportunities"].append({
                "package": pkg,
                "description": description,
                "integration_available": True
            })
    
    # Recommend Storm Logger if not present
    if not integration["storm_logger_present"]:
        integration["recommended_additions"].append({
            "package": "storm-logger",
            "version": ">=2.0.0",
            "reason": "Enterprise-grade logging with business intelligence",
            "benefits": [
                "Professional console output",
                "Business metrics tracking",
                "Comprehensive error handling",
                "Framework integrations"
            ]
        })
    
    return integration


def generate_dependency_recommendations(
    analysis: Dict[str, Any],
    update_strategy: str
) -> List[Dict[str, Any]]:
    """
    Generate dependency management recommendations
    
    Args:
        analysis: Dependency analysis results
        update_strategy: Update strategy
        
    Returns:
        List of recommendations
    """
    recommendations = []
    
    # Security recommendations
    vulnerabilities = analysis.get("vulnerabilities", [])
    if vulnerabilities:
        high_severity_count = sum(1 for v in vulnerabilities if v.get("severity") == "high")
        
        if high_severity_count > 0:
            recommendations.append({
                "priority": "critical",
                "category": "security",
                "title": "Address Critical Security Vulnerabilities",
                "description": f"Found {high_severity_count} high-severity vulnerabilities",
                "action_items": [
                    "Update packages with known vulnerabilities",
                    "Run security audit regularly",
                    "Consider using dependabot or similar tools",
                    "Implement vulnerability monitoring"
                ]
            })
    
    # Update recommendations
    outdated_packages = analysis.get("outdated_packages", [])
    if outdated_packages:
        high_priority_updates = [p for p in outdated_packages if p.get("update_priority") == "high"]
        
        if high_priority_updates:
            recommendations.append({
                "priority": "high",
                "category": "updates",
                "title": "Update High-Priority Packages",
                "description": f"Found {len(high_priority_updates)} packages with high-priority updates",
                "action_items": [
                    "Update packages with patch versions",
                    "Test updates in development environment",
                    "Update CI/CD pipeline",
                    "Document breaking changes"
                ]
            })
    
    # Cleanup recommendations
    unused_deps = analysis.get("unused_dependencies", [])
    if unused_deps:
        recommendations.append({
            "priority": "medium",
            "category": "cleanup",
            "title": "Remove Unused Dependencies",
            "description": f"Found {len(unused_deps)} potentially unused dependencies",
            "action_items": [
                "Verify dependencies are actually unused",
                "Remove unused packages from requirements",
                "Clean up development environment",
                "Update documentation"
            ]
        })
    
    # Constraint recommendations
    version_constraints = analysis.get("dependencies", {}).get("version_constraints", {})
    if version_constraints:
        unconstrained = version_constraints.get("unconstrained_versions", 0)
        
        if unconstrained > 0:
            recommendations.append({
                "priority": "medium",
                "category": "constraints",
                "title": "Add Version Constraints",
                "description": f"Found {unconstrained} dependencies without version constraints",
                "action_items": [
                    "Add version constraints to requirements",
                    "Use lock files for reproducible builds",
                    "Consider using dependency management tools",
                    "Document version compatibility"
                ]
            })
    
    # Storm Logger recommendations
    storm_integration = analysis.get("storm_logger_integration", {})
    if not storm_integration.get("storm_logger_present"):
        recommendations.append({
            "priority": "low",
            "category": "integration",
            "title": "Add Storm Logger Integration",
            "description": "Consider adding Storm Logger for enterprise-grade logging",
            "action_items": [
                "Add storm-logger to dependencies",
                "Configure logging integration",
                "Set up business metrics tracking",
                "Add console output enhancements"
            ]
        })
    
    return recommendations


def generate_dependency_summary(analysis: Dict[str, Any]) -> Dict[str, Any]:
    """
    Generate dependency management summary
    
    Args:
        analysis: Dependency analysis results
        
    Returns:
        Summary dictionary
    """
    summary = {
        "total_dependencies": 0,
        "vulnerabilities_found": 0,
        "outdated_packages": 0,
        "unused_dependencies": 0,
        "overall_health": "good",
        "priority_actions": []
    }
    
    # Count totals
    dependencies = analysis.get("dependencies", {})
    summary["total_dependencies"] = dependencies.get("total_dependencies", 0)
    
    vulnerabilities = analysis.get("vulnerabilities", [])
    summary["vulnerabilities_found"] = len(vulnerabilities)
    
    outdated_packages = analysis.get("outdated_packages", [])
    summary["outdated_packages"] = len(outdated_packages)
    
    unused_deps = analysis.get("unused_dependencies", [])
    summary["unused_dependencies"] = len(unused_deps)
    
    # Determine overall health
    critical_issues = sum(1 for v in vulnerabilities if v.get("severity") == "high")
    
    if critical_issues > 0:
        summary["overall_health"] = "critical"
    elif len(vulnerabilities) > 0 or len(outdated_packages) > 5:
        summary["overall_health"] = "warning"
    elif len(outdated_packages) > 0 or len(unused_deps) > 0:
        summary["overall_health"] = "attention"
    else:
        summary["overall_health"] = "excellent"
    
    # Priority actions
    if critical_issues > 0:
        summary["priority_actions"].append(f"Address {critical_issues} critical security vulnerabilities")
    
    high_priority_updates = [p for p in outdated_packages if p.get("update_priority") == "high"]
    if high_priority_updates:
        summary["priority_actions"].append(f"Update {len(high_priority_updates)} high-priority packages")
    
    if len(unused_deps) > 3:
        summary["priority_actions"].append(f"Clean up {len(unused_deps)} unused dependencies")
    
    return summary