"""
Capability Compatibility Generator - Cross-Capability Support for Anvil Development

This module provides capability-agnostic code generation that works across
different Anvil capability levels, with fallback patterns and progressive enhancement.
"""

from typing import Dict, List, Optional, Any, Union, Tuple
from dataclasses import dataclass, field
from pathlib import Path
import logging
import re

from ..responses.response_builder import ResponseBuilder
from ..errors.hephaestus_errors import GenerationError


@dataclass
class CapabilityCompatibilityConfig:
    """Configuration for capability compatibility generation."""

    target_capability_levels: List[str] = field(
        default_factory=lambda: [
            "basic",
            "enhanced",
            "intermediate",
            "advanced",
            "modern",
            "cutting-edge",
        ]
    )
    fallback_strategy: str = "graceful"  # graceful, strict, progressive
    enable_progressive_enhancement: bool = True
    compatibility_level: str = "broad"  # broad, moderate, strict
    feature_detection: bool = True


@dataclass
class CapabilityFeature:
    """Represents a feature available in specific Anvil capability levels."""

    name: str
    min_capability_level: str
    max_capability_level: Optional[str] = None
    fallback_alternative: Optional[str] = None
    description: str = ""
    deprecated_in: Optional[str] = None


@dataclass
class CapabilityMatrix:
    """Matrix for tracking feature compatibility across capability levels."""

    features: List[CapabilityFeature] = field(default_factory=list)
    capability_support: Dict[str, List[str]] = field(default_factory=dict)
    fallback_mappings: Dict[str, str] = field(default_factory=dict)


class CapabilityCompatibilityGenerator:
    """
    Cross-capability code generator for Anvil development.

    This generator creates code that works across multiple Anvil capability levels,
    with intelligent fallbacks and progressive enhancement capabilities.
    """

    def __init__(self, project_path: Union[str, Path]):
        self.project_path = Path(project_path)
        self.logger = logging.getLogger(__name__)
        self.response_builder = ResponseBuilder()

        # Initialize compatibility matrix
        self.compatibility_matrix = self._build_compatibility_matrix()

        # Capability level detection cache
        self._capability_cache: Dict[str, str] = {}

    def generate_capability_compatible_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        config: Optional[CapabilityCompatibilityConfig] = None,
    ) -> Dict[str, Any]:
        """
        Generate a component that's compatible across multiple Anvil capability levels.

        Args:
            component_name: Name of component to generate
            component_type: Type of component (form, custom_component, etc.)
            properties: Component properties and configuration
            config: Compatibility configuration

        Returns:
            Generated component with cross-capability compatibility
        """
        try:
            if config is None:
                config = CapabilityCompatibilityConfig()

            # Detect target capability level
            target_capability = self._detect_capability_level()

            # Analyze required features
            required_features = self._analyze_required_features(
                component_type, properties
            )

            # Generate capability-compatible code
            component_def = self._generate_capability_aware_component(
                component_name,
                component_type,
                properties,
                required_features,
                target_capability,
                config,
            )

            # Add progressive enhancement if enabled
            if config.enable_progressive_enhancement:
                component_def = self._add_progressive_enhancement(
                    component_def, required_features, config
                )

            # Validate compatibility
            compatibility_report = self._validate_compatibility(
                component_def, config.target_capability_levels
            )

            return self.response_builder.success(
                data=component_def,
                message=f"Generated compatible component: {component_name}",
            )

        except Exception as e:
            self.logger.error(
                f"Error generating compatible component {component_name}: {e}"
            )
            raise GenerationError(f"Failed to generate compatible component: {e}")

    def create_capability_upgrade_plan(
        self,
        current_capability: str,
        target_capability: str,
        components: List[str],
        config: Optional[CapabilityCompatibilityConfig] = None,
    ) -> Dict[str, Any]:
        """
        Create an upgrade plan between Anvil capability levels.

        Args:
            current_capability: Current capability level
            target_capability: Target capability level
            components: List of components to upgrade
            config: Compatibility configuration

        Returns:
            Upgrade plan with step-by-step instructions
        """
        try:
            if config is None:
                config = CapabilityCompatibilityConfig()

            # Analyze capability differences
            capability_diff = self._analyze_capability_differences(
                current_capability, target_capability
            )

            # Create upgrade steps
            upgrade_steps = self._create_upgrade_steps(
                components, capability_diff, config
            )

            # Generate compatibility matrix
            compatibility_matrix = self._generate_upgrade_matrix(
                current_capability, target_capability, components
            )

            # Create rollback plan
            rollback_plan = self._create_rollback_plan(
                current_capability, target_capability, components
            )

            upgrade_plan = {
                "current_capability": current_capability,
                "target_capability": target_capability,
                "components": components,
                "capability_differences": capability_diff,
                "upgrade_steps": upgrade_steps,
                "compatibility_matrix": compatibility_matrix,
                "rollback_plan": rollback_plan,
                "estimated_effort": self._estimate_upgrade_effort(
                    components, capability_diff
                ),
                "breaking_changes": self._identify_breaking_changes(capability_diff),
                "new_features": self._identify_new_features(capability_diff),
            }

            return self.response_builder.success(
                data=upgrade_plan,
                message=f"Created upgrade plan: {current_capability} → {target_capability}",
            )

        except Exception as e:
            self.logger.error(f"Error creating upgrade plan: {e}")
            raise GenerationError(f"Failed to create upgrade plan: {e}")

    def generate_capability_fallback_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        unsupported_features: List[str],
        config: Optional[CapabilityCompatibilityConfig] = None,
    ) -> Dict[str, Any]:
        """
        Generate a component with fallbacks for unsupported features.

        Args:
            component_name: Name of component
            component_type: Type of component
            properties: Component properties
            unsupported_features: List of features not supported in target capability level
            config: Compatibility configuration

        Returns:
            Component with fallback implementations
        """
        try:
            if config is None:
                config = CapabilityCompatibilityConfig()

            # Generate base component
            component_def = self._generate_base_component(
                component_name, component_type, properties
            )

            # Add fallback implementations
            fallbacks = self._generate_fallback_implementations(
                unsupported_features, config
            )

            # Add feature detection code
            feature_detection = self._generate_feature_detection(
                unsupported_features, config
            )

            # Combine everything
            compatible_component = {
                **component_def,
                "fallbacks": fallbacks,
                "feature_detection": feature_detection,
                "compatibility_mode": config.fallback_strategy,
                "unsupported_features": unsupported_features,
            }

            return self.response_builder.success(
                data=compatible_component,
                message=f"Generated fallback component: {component_name}",
            )

        except Exception as e:
            self.logger.error(
                f"Error generating fallback component {component_name}: {e}"
            )
            raise GenerationError(f"Failed to generate fallback component: {e}")

    def _build_compatibility_matrix(self) -> CapabilityMatrix:
        """Build comprehensive compatibility matrix."""
        features = [
            CapabilityFeature(
                name="material_3_components",
                min_capability_level="advanced",
                description="Material Design 3 components",
                fallback_alternative="classic_components",
            ),
            CapabilityFeature(
                name="official_routing",
                min_capability_level="intermediate",
                description="Official Anvil routing",
                fallback_alternative="hash_routing",
            ),
            CapabilityFeature(
                name="reactive_library",
                min_capability_level="intermediate",
                description="Reactive state management",
                fallback_alternative="manual_state_management",
            ),
            CapabilityFeature(
                name="model_classes",
                min_capability_level="intermediate",
                description="Type-safe model classes",
                fallback_alternative="data_tables",
            ),
            CapabilityFeature(
                name="layout_system",
                min_capability_level="advanced",
                description="Modern slot-based layouts",
                fallback_alternative="panel_layouts",
            ),
            CapabilityFeature(
                name="tabulator_integration",
                min_capability_level="intermediate",
                description="Advanced data tables",
                fallback_alternative="data_grid",
            ),
            CapabilityFeature(
                name="theme_system",
                min_capability_level="basic",
                description="Theme and styling system",
                fallback_alternative="inline_styles",
            ),
            CapabilityFeature(
                name="form_validation",
                min_capability_level="enhanced",
                description="Built-in form validation",
                fallback_alternative="manual_validation",
            ),
        ]

        # Build capability level support mapping
        capability_support = {}
        capability_levels = [
            "basic",
            "enhanced",
            "intermediate",
            "advanced",
            "modern",
            "cutting-edge",
        ]
        level_order = {level: i for i, level in enumerate(capability_levels)}

        for capability_level in capability_levels:
            supported_features = []
            for feature in features:
                feature_level_index = level_order.get(feature.min_capability_level, 0)
                current_level_index = level_order.get(capability_level, 0)
                if current_level_index >= feature_level_index:
                    if (
                        feature.max_capability_level is None
                        or level_order.get(feature.max_capability_level, float("inf"))
                        >= current_level_index
                    ):
                        supported_features.append(feature.name)
            capability_support[capability_level] = supported_features

        # Build fallback mappings
        fallback_mappings = {}
        for feature in features:
            if feature.fallback_alternative:
                fallback_mappings[feature.name] = feature.fallback_alternative

        return CapabilityMatrix(
            features=features,
            capability_support=capability_support,
            fallback_mappings=fallback_mappings,
        )

    def _detect_capability_level(self) -> str:
        """Detect capability level of current project."""
        cache_key = str(self.project_path)
        if cache_key in self._capability_cache:
            return self._capability_cache[cache_key]

        try:
            # Check for capability indicators in various files
            capability_files = [
                "anvil.yaml",
                "anvil.json",
                "requirements.txt",
                "pyproject.toml",
            ]

            for filename in capability_files:
                file_path = self.project_path / filename
                if file_path.exists():
                    capability = self._extract_capability_from_file(file_path)
                    if capability:
                        self._capability_cache[cache_key] = capability
                        return capability

            # Default to latest if no capability level found
            default_capability = "cutting-edge"
            self._capability_cache[cache_key] = default_capability
            return default_capability

        except Exception as e:
            self.logger.warning(f"Error detecting capability level: {e}")
            default_capability = "cutting-edge"
            self._capability_cache[cache_key] = default_capability
            return default_capability

    def _extract_capability_from_file(self, file_path: Path) -> Optional[str]:
        """Extract capability level information from a file."""
        try:
            content = file_path.read_text(encoding="utf-8")

            # Look for capability indicators
            if "material-3" in content.lower() or "@anvil/material-3" in content:
                return "advanced" if "layout" in content.lower() else "modern"
            elif "official-routing" in content.lower() or "anvil.routing" in content:
                return "intermediate"
            elif "reactive" in content.lower() or "anvil.reactive" in content:
                return "intermediate"
            elif "model_class" in content.lower() or "model_classes" in content:
                return "intermediate"
            elif "tabulator" in content.lower():
                return "intermediate"
            elif "validation" in content.lower():
                return "enhanced"
            elif "theme" in content.lower():
                return "basic"

            return None

        except Exception:
            return None

    def _analyze_required_features(
        self, component_type: str, properties: Dict[str, Any]
    ) -> List[str]:
        """Analyze which features are required for component."""
        required_features = []

        # Check for Material 3 components
        if any("role" in str(prop).lower() for prop in properties.values()):
            required_features.append("material_3_components")

        # Check for routing features
        if "routing" in str(properties).lower():
            required_features.append("official_routing")

        # Check for reactive features
        if any("reactive" in str(prop).lower() for prop in properties.values()):
            required_features.append("reactive_library")

        # Check for model features
        if any("model" in str(prop).lower() for prop in properties.values()):
            required_features.append("model_classes")

        # Check for layout features
        if "layout" in str(component_type).lower():
            required_features.append("layout_system")

        # Check for data table features
        if (
            "table" in str(component_type).lower()
            or "grid" in str(component_type).lower()
        ):
            required_features.append("tabulator_integration")

        # Check for theme features
        if any("theme" in str(prop).lower() for prop in properties.values()):
            required_features.append("theme_system")

        # Check for validation features
        if "validation" in str(properties).lower():
            required_features.append("form_validation")

        return required_features

    def _generate_capability_aware_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        required_features: List[str],
        target_capability: str,
        config: CapabilityCompatibilityConfig,
    ) -> Dict[str, Any]:
        """Generate a component aware of capability constraints."""

        # Filter properties based on capability compatibility
        compatible_properties = self._filter_properties_by_capability(
            properties, required_features, target_capability
        )

        # Generate base component structure
        component_def = {
            "name": component_name,
            "type": component_type,
            "properties": compatible_properties,
            "capability_level": target_capability,
            "compatibility_features": [],
        }

        # Add capability-specific code
        for feature in required_features:
            if self._is_feature_supported(feature, target_capability):
                component_def["compatibility_features"].append(
                    {"feature": feature, "supported": True, "implementation": "native"}
                )
            else:
                fallback = self._get_fallback_for_feature(feature)
                component_def["compatibility_features"].append(
                    {
                        "feature": feature,
                        "supported": False,
                        "fallback": fallback,
                        "implementation": "fallback",
                    }
                )

        return component_def

    def _filter_properties_by_capability(
        self,
        properties: Dict[str, Any],
        required_features: List[str],
        target_capability: str,
    ) -> Dict[str, Any]:
        """Filter properties based on capability compatibility."""
        filtered_properties = {}

        for key, value in properties.items():
            # Check if property requires unsupported features
            property_features = self._analyze_property_features(key, value)

            if all(
                self._is_feature_supported(f, target_capability)
                for f in property_features
            ):
                filtered_properties[key] = value
            else:
                # Add capability comment
                filtered_properties[f"{key}_fallback"] = value

        return filtered_properties

    def _analyze_property_features(self, key: str, value: Any) -> List[str]:
        """Analyze what features a property requires."""
        features = []
        value_str = str(value).lower()

        if "role" in key.lower() and "material" in value_str:
            features.append("material_3_components")

        if "reactive" in value_str:
            features.append("reactive_library")

        if "model" in value_str:
            features.append("model_classes")

        return features

    def _is_feature_supported(self, feature: str, capability_level: str) -> bool:
        """Check if a feature is supported in a given capability level."""
        if feature not in self.compatibility_matrix.fallback_mappings:
            return True  # No capability constraint

        # Find feature definition
        for feat in self.compatibility_matrix.features:
            if feat.name == feature:
                level_order = [
                    "basic",
                    "enhanced",
                    "intermediate",
                    "advanced",
                    "modern",
                    "cutting-edge",
                ]
                feature_index = level_order.index(feat.min_capability_level)
                current_index = level_order.index(capability_level)
                return current_index >= feature_index

        return False

    def _get_fallback_for_feature(self, feature: str) -> Optional[str]:
        """Get the fallback implementation for a feature."""
        return self.compatibility_matrix.fallback_mappings.get(feature)

    def _add_progressive_enhancement(
        self,
        component_def: Dict[str, Any],
        required_features: List[str],
        config: CapabilityCompatibilityConfig,
    ) -> Dict[str, Any]:
        """Add progressive enhancement capabilities to component."""

        enhancement_code = []

        for feature in required_features:
            if not self._is_feature_supported(feature, "basic"):
                # Add feature detection and progressive loading
                detection_code = self._generate_feature_detection_code(feature)
                enhancement_code.append(detection_code)

        component_def["progressive_enhancement"] = {
            "enabled": True,
            "code": enhancement_code,
            "features": required_features,
        }

        return component_def

    def _generate_feature_detection_code(self, feature: str) -> str:
        """Generate code to detect feature availability."""
        feature_checks = {
            "material_3_components": "typeof anvil.Material !== 'undefined'",
            "official_routing": "typeof anvil.routing !== 'undefined'",
            "reactive_library": "typeof anvil.reactive !== 'undefined'",
            "model_classes": "typeof anvil.server.model_class !== 'undefined'",
            "layout_system": "typeof anvil.Layout !== 'undefined'",
            "tabulator_integration": "typeof anvil.Tabulator !== 'undefined'",
            "theme_system": "typeof anvil.Theme !== 'undefined'",
            "form_validation": "typeof anvil.Form !== 'undefined'",
        }

        check = feature_checks.get(feature, "true")
        return f"if ({check}) {{ /* {feature} available */ }}"

    def _validate_compatibility(
        self, component_def: Dict[str, Any], target_capability_levels: List[str]
    ) -> Dict[str, Any]:
        """Validate component compatibility across target capability levels."""

        compatibility_report = {
            "compatible_levels": [],
            "incompatible_levels": [],
            "fallback_required": [],
            "issues": [],
        }

        for capability_level in target_capability_levels:
            level_issues = []

            # Check each feature
            for feature_info in component_def.get("compatibility_features", []):
                feature = feature_info["feature"]
                if not feature_info["supported"]:
                    if feature_info.get("fallback"):
                        compatibility_report["fallback_required"].append(
                            {
                                "capability_level": capability_level,
                                "feature": feature,
                                "fallback": feature_info["fallback"],
                            }
                        )
                    else:
                        level_issues.append(f"Feature {feature} not supported")

            if level_issues:
                compatibility_report["incompatible_levels"].append(
                    {"capability_level": capability_level, "issues": level_issues}
                )
                compatibility_report["issues"].extend(level_issues)
            else:
                compatibility_report["compatible_levels"].append(capability_level)

        return compatibility_report

    def _capability_level_compare(self, level1: str, level2: str) -> int:
        """Compare two capability level strings."""
        level_order = [
            "basic",
            "enhanced",
            "intermediate",
            "advanced",
            "modern",
            "cutting-edge",
        ]

        try:
            index1 = level_order.index(level1)
            index2 = level_order.index(level2)

            if index1 < index2:
                return -1
            elif index1 > index2:
                return 1
            else:
                return 0
        except ValueError:
            # If level not found, assume it's higher
            return 1

    def _analyze_capability_differences(
        self, current_capability: str, target_capability: str
    ) -> Dict[str, Any]:
        """Analyze differences between two capability levels."""

        comparison = self._capability_level_compare(
            current_capability, target_capability
        )

        if comparison == 0:
            return {
                "type": "same",
                "new_features": [],
                "deprecated_features": [],
                "breaking_changes": [],
            }
        elif comparison < 0:
            return {
                "type": "upgrade",
                "new_features": self._get_new_features_between(
                    current_capability, target_capability
                ),
                "deprecated_features": self._get_deprecated_features_between(
                    current_capability, target_capability
                ),
                "breaking_changes": self._get_breaking_changes_between(
                    current_capability, target_capability
                ),
            }
        else:
            return {
                "type": "downgrade",
                "lost_features": self._get_new_features_between(
                    target_capability, current_capability
                ),
                "compatibility_issues": self._get_compatibility_issues_between(
                    target_capability, current_capability
                ),
            }

    def _get_new_features_between(
        self, from_capability: str, to_capability: str
    ) -> List[str]:
        """Get features introduced between two capability levels."""
        new_features = []

        for feature in self.compatibility_matrix.features:
            if (
                self._capability_level_compare(
                    from_capability, feature.min_capability_level
                )
                < 0
                and self._capability_level_compare(
                    to_capability, feature.min_capability_level
                )
                >= 0
            ):
                new_features.append(feature.name)

        return new_features

    def _get_deprecated_features_between(
        self, from_capability: str, to_capability: str
    ) -> List[str]:
        """Get features deprecated between two capability levels."""
        deprecated = []

        for feature in self.compatibility_matrix.features:
            if feature.deprecated_in:
                if (
                    self._capability_level_compare(
                        from_capability, feature.deprecated_in
                    )
                    < 0
                    and self._capability_level_compare(
                        to_capability, feature.deprecated_in
                    )
                    >= 0
                ):
                    deprecated.append(feature.name)

        return deprecated

    def _get_breaking_changes_between(
        self, from_capability: str, to_capability: str
    ) -> List[str]:
        """Get breaking changes between two capability levels."""
        # This would be populated with actual breaking changes from Anvil release notes
        breaking_changes = []

        # Example breaking changes
        if (
            self._capability_level_compare(from_capability, "intermediate") < 0
            and self._capability_level_compare(to_capability, "intermediate") >= 0
        ):
            breaking_changes.append("Component property changes in intermediate")

        if (
            self._capability_level_compare(from_capability, "advanced") < 0
            and self._capability_level_compare(to_capability, "advanced") >= 0
        ):
            breaking_changes.append("Layout system changes in advanced")

        return breaking_changes

    def _get_compatibility_issues_between(
        self, from_capability: str, to_capability: str
    ) -> List[str]:
        """Get compatibility issues when downgrading."""
        issues = []

        for feature in self.compatibility_matrix.features:
            if (
                self._capability_level_compare(
                    to_capability, feature.min_capability_level
                )
                < 0
                and self._capability_level_compare(
                    from_capability, feature.min_capability_level
                )
                >= 0
            ):
                issues.append(
                    f"Feature {feature.name} not available in {to_capability}"
                )

        return issues

    def _create_upgrade_steps(
        self,
        components: List[str],
        capability_diff: Dict[str, Any],
        config: CapabilityCompatibilityConfig,
    ) -> List[Dict[str, Any]]:
        """Create step-by-step upgrade plan."""

        steps = []

        # Preparation steps
        steps.append(
            {
                "phase": "preparation",
                "title": "Backup Current Code",
                "description": "Create a complete backup of current project",
                "priority": "high",
            }
        )

        steps.append(
            {
                "phase": "preparation",
                "title": "Update Dependencies",
                "description": "Update Anvil dependencies to target capability level",
                "priority": "high",
            }
        )

        # Feature upgrade steps
        if capability_diff["type"] == "upgrade":
            for feature in capability_diff["new_features"]:
                steps.append(
                    {
                        "phase": "feature_migration",
                        "title": f"Migrate to {feature}",
                        "description": f"Update components to use {feature}",
                        "priority": "medium",
                        "affected_components": components,
                    }
                )

        # Breaking changes steps
        for breaking_change in capability_diff["breaking_changes"]:
            steps.append(
                {
                    "phase": "breaking_changes",
                    "title": f"Address: {breaking_change}",
                    "description": f"Fix breaking change: {breaking_change}",
                    "priority": "high",
                    "affected_components": components,
                }
            )

        # Testing steps
        steps.append(
            {
                "phase": "testing",
                "title": "Test Upgrade",
                "description": "Test all components with new capability level",
                "priority": "high",
            }
        )

        return steps

    def _generate_upgrade_matrix(
        self, current_capability: str, target_capability: str, components: List[str]
    ) -> Dict[str, Any]:
        """Generate a compatibility matrix for upgrade."""

        matrix = {
            "current_capability": current_capability,
            "target_capability": target_capability,
            "components": {},
        }

        for component in components:
            current_compat = self._check_component_compatibility(
                component, current_capability
            )
            target_compat = self._check_component_compatibility(
                component, target_capability
            )

            # Determine if upgrade is required
            upgrade_required = False
            upgrade_complexity = "low"

            if current_compat["compatible"] and not target_compat["compatible"]:
                upgrade_required = True
                upgrade_complexity = "medium"
            elif not current_compat["compatible"] and target_compat["compatible"]:
                upgrade_complexity = "low"
            elif not current_compat["compatible"] and not target_compat["compatible"]:
                upgrade_complexity = "high"

            matrix["components"][component] = {
                "current_compatibility": current_compat,
                "target_compatibility": target_compat,
                "upgrade_required": upgrade_required,
                "upgrade_complexity": upgrade_complexity,
            }

        return matrix

    def _check_component_compatibility(
        self, component: str, capability_level: str
    ) -> Dict[str, Any]:
        """Check if a component is compatible with a capability level."""
        # This would analyze actual component code
        # For now, return a basic compatibility check
        return {"compatible": True, "issues": [], "features_used": []}

    def _create_rollback_plan(
        self, current_capability: str, target_capability: str, components: List[str]
    ) -> Dict[str, Any]:
        """Create a rollback plan for upgrade."""

        return {
            "rollback_available": True,
            "rollback_steps": [
                "Restore backup from preparation phase",
                "Revert dependency changes",
                "Test rollback functionality",
            ],
            "rollback_triggers": [
                "Critical functionality broken",
                "Performance degradation > 20%",
                "Compatibility issues with dependencies",
            ],
            "estimated_rollback_time": "30-60 minutes",
        }

    def _estimate_upgrade_effort(
        self, components: List[str], capability_diff: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Estimate effort required for upgrade."""

        base_effort = len(components) * 2  # 2 hours per component

        # Add effort for breaking changes
        breaking_effort = (
            len(capability_diff["breaking_changes"]) * 4
        )  # 4 hours per breaking change

        # Add effort for new features
        feature_effort = (
            len(capability_diff["new_features"]) * 1
        )  # 1 hour per new feature

        total_effort = base_effort + breaking_effort + feature_effort

        return {
            "total_hours": total_effort,
            "component_effort": base_effort,
            "breaking_change_effort": breaking_effort,
            "feature_effort": feature_effort,
            "complexity": "medium" if total_effort < 20 else "high",
        }

    def _identify_breaking_changes(self, capability_diff: Dict[str, Any]) -> List[str]:
        """Identify breaking changes from capability differences."""
        return capability_diff.get("breaking_changes", [])

    def _identify_new_features(self, capability_diff: Dict[str, Any]) -> List[str]:
        """Identify new features from capability differences."""
        return capability_diff.get("new_features", [])

    def _generate_base_component(
        self, component_name: str, component_type: str, properties: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Generate a basic component structure."""
        return {
            "name": component_name,
            "type": component_type,
            "properties": properties,
            "base_generation": True,
        }

    def _generate_fallback_implementations(
        self, unsupported_features: List[str], config: CapabilityCompatibilityConfig
    ) -> List[Dict[str, Any]]:
        """Generate fallback implementations for unsupported features."""

        fallbacks = []

        for feature in unsupported_features:
            fallback_impl = self._get_fallback_for_feature(feature)
            if fallback_impl:
                fallbacks.append(
                    {
                        "feature": feature,
                        "fallback": fallback_impl,
                        "strategy": config.fallback_strategy,
                    }
                )

        return fallbacks

    def _generate_feature_detection(
        self, unsupported_features: List[str], config: CapabilityCompatibilityConfig
    ) -> Dict[str, Any]:
        """Generate feature detection code."""

        detection_code = {}

        for feature in unsupported_features:
            detection_code[feature] = self._generate_feature_detection_code(feature)

        return {
            "enabled": config.feature_detection,
            "code": detection_code,
            "features": unsupported_features,
        }
