"""
Hybrid Generator - Context-Aware Code Generation for Mixed Architectures

This module provides intelligent code generation that adapts to mixed
modern/legacy Anvil architectures, enabling respectful enhancement
while preserving existing functionality.
"""

from __future__ import annotations

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

from ..models.project_context import ProjectContext
from ..analyzers.project_analyzer import ProjectAnalyzer
from ..patterns.pattern_matcher import PatternMatcher
from ..analyzers.performance_analyzer import PerformanceAnalyzer
from ..validators.project_validator import ProjectValidator
from ..responses.response_builder import ResponseBuilder
from ..errors.hephaestus_errors import GenerationError, ValidationError

if TYPE_CHECKING:
    from ..dependencies.container import FileSystem, ProjectManager


@dataclass
class HybridGenerationConfig:
    """Configuration for hybrid code generation."""

    respect_legacy: bool = True
    gradual_enhancement: bool = True
    backward_compatibility: bool = True
    performance_optimization: bool = True
    risk_tolerance: str = "low"  # low, medium, high
    enhancement_strategy: str = "adaptive"  # adaptive, conservative, aggressive


@dataclass
class GenerationDecision:
    """Decision made during hybrid generation."""

    component_name: str
    pattern_detected: str
    modernization_level: str  # none, minimal, moderate, full
    rationale: str
    risks: List[str] = field(default_factory=list)
    benefits: List[str] = field(default_factory=list)
    implementation_approach: str = "compatible"


class HybridGenerator:
    """
    Context-aware code generator for mixed Anvil architectures.

    This generator analyzes existing patterns and makes intelligent decisions
    about how to enhance code while respecting legacy constraints and ensuring
    backward compatibility.
    """

    def __init__(
        self,
        file_system: "FileSystem",
        project_manager: "ProjectManager",
        project_path: Union[str, Path] | None = None,
    ):
        self.file_system = file_system
        self.project_manager = project_manager
        self.project_path = Path(project_path) if project_path else Path.cwd()
        self.logger = logging.getLogger(__name__)

        # Initialize analyzers with proper dependencies
        self.project_analyzer = ProjectAnalyzer(file_system, project_manager)
        self.pattern_matcher = PatternMatcher(file_system, project_manager)
        self.performance_analyzer = PerformanceAnalyzer(file_system, project_manager)
        self.validator = ProjectValidator(file_system, project_manager)
        self.response_builder = ResponseBuilder()

        # Generation state
        self.generation_decisions: List[GenerationDecision] = []
        self.context_cache: Dict[str, Any] = {}

    def generate_hybrid_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        config: Optional[HybridGenerationConfig] = None,
    ) -> Dict[str, Any]:
        """
        Generate a component using hybrid approach based on project context.

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

        Returns:
            Generated component definition with hybrid considerations
        """
        try:
            if config is None:
                config = HybridGenerationConfig()

            # Analyze project context
            context = self._analyze_project_context()

            # Detect existing patterns
            patterns = self._detect_existing_patterns(component_name, component_type)

            # Make generation decisions
            decision = self._make_generation_decision(
                component_name, component_type, patterns, context, config
            )

            # Generate component based on decision
            component_def = self._generate_component_by_approach(
                component_name, component_type, properties, decision, context
            )

            # Record decision for transparency
            self.generation_decisions.append(decision)

            return self.response_builder.success_response(
                data=component_def,
                message=f"Generated hybrid component: {component_name}",
                metadata={
                    "decision": decision.__dict__,
                    "context": context.__dict__
                    if hasattr(context, "__dict__")
                    else context,
                    "patterns": patterns,
                },
            )

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

    def enhance_existing_form(
        self,
        form_path: Union[str, Path],
        enhancement_type: str = "adaptive",
        config: Optional[HybridGenerationConfig] = None,
    ) -> Dict[str, Any]:
        """
        Enhance an existing form with hybrid patterns.

        Args:
            form_path: Path to the existing form
            enhancement_type: Type of enhancement (adaptive, conservative, aggressive)
            config: Hybrid generation configuration

        Returns:
            Enhanced form definition with changes applied
        """
        try:
            if config is None:
                config = HybridGenerationConfig()

            form_path = Path(form_path)

            # Analyze existing form
            form_analysis = self._analyze_existing_form(form_path)

            # Determine enhancement strategy
            strategy = self._determine_enhancement_strategy(
                form_analysis, enhancement_type, config
            )

            # Apply enhancements
            enhanced_form = self._apply_form_enhancements(
                form_analysis, strategy, config
            )

            return self.response_builder.success_response(
                data=enhanced_form,
                message=f"Enhanced form: {form_path.name}",
                metadata={
                    "original_analysis": form_analysis,
                    "strategy": strategy,
                    "enhancements_applied": len(enhanced_form.get("changes", [])),
                },
            )

        except Exception as e:
            self.logger.error(f"Error enhancing form {form_path}: {e}")
            raise GenerationError(f"Failed to enhance form: {e}")

    def create_migration_enhancement_plan(
        self,
        target_components: List[str],
        migration_goals: List[str],
        config: Optional[HybridGenerationConfig] = None,
    ) -> Dict[str, Any]:
        """
        Create a comprehensive enhancement plan for mixed architecture migration.

        Args:
            target_components: List of components to enhance
            migration_goals: List of modernization goals
            config: Hybrid generation configuration

        Returns:
            Detailed enhancement plan with phases and steps
        """
        try:
            if config is None:
                config = HybridGenerationConfig()

            # Analyze all target components
            component_analyses = {}
            for component in target_components:
                component_analyses[component] = self._analyze_component_context(
                    component
                )

            # Create enhancement phases
            phases = self._create_enhancement_phases(
                component_analyses, migration_goals, config
            )

            # Generate risk assessment
            risk_assessment = self._assess_enhancement_risks(
                component_analyses, phases, config
            )

            # Create rollback plan
            rollback_plan = self._create_rollback_plan(component_analyses, phases)

            plan = {
                "target_components": target_components,
                "migration_goals": migration_goals,
                "phases": phases,
                "risk_assessment": risk_assessment,
                "rollback_plan": rollback_plan,
                "estimated_timeline": self._estimate_timeline(phases),
                "success_criteria": self._define_success_criteria(migration_goals),
            }

            return self.response_builder.success_response(
                data=plan,
                message="Created migration enhancement plan",
                metadata={
                    "components_analyzed": len(component_analyses),
                    "phases_planned": len(phases),
                    "risk_level": risk_assessment.get("overall_risk", "medium"),
                },
            )

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

    def _analyze_project_context(self) -> Dict[str, Any]:
        """Analyze project context for hybrid generation decisions."""
        cache_key = "project_context"
        if cache_key in self.context_cache:
            return self.context_cache[cache_key]

        try:
            # Get project analysis
            project_analysis = self.project_analyzer.analyze_project()

            # Extract relevant context for hybrid generation
            context = {
                "modernization_score": getattr(
                    project_analysis, "modernization_score", 0.5
                ),
                "architecture_type": getattr(
                    project_analysis, "architecture_type", "mixed"
                ),
                "legacy_patterns": getattr(project_analysis, "legacy_patterns", []),
                "modern_patterns": getattr(project_analysis, "modern_patterns", []),
                "performance_profile": getattr(
                    project_analysis, "performance_profile", {}
                ),
                "dependencies": getattr(project_analysis, "dependencies", {}),
                "risk_factors": getattr(project_analysis, "risk_factors", []),
            }

            self.context_cache[cache_key] = context
            return context

        except Exception as e:
            self.logger.warning(f"Error analyzing project context: {e}")
            return {"modernization_score": 0.5, "architecture_type": "unknown"}

    def _detect_existing_patterns(
        self, component_name: str, component_type: str
    ) -> Dict[str, Any]:
        """Detect existing patterns in the project related to the component."""
        try:
            patterns = {
                "component_patterns": [],
                "data_patterns": [],
                "layout_patterns": [],
                "styling_patterns": [],
                "event_patterns": [],
            }

            # Search for similar components
            similar_components = self.pattern_matcher.find_similar_components(
                component_name, component_type
            )
            patterns["component_patterns"] = similar_components

            # Analyze data access patterns
            data_patterns = self.pattern_matcher.analyze_data_patterns()
            patterns["data_patterns"] = data_patterns

            # Analyze layout patterns
            layout_patterns = self.pattern_matcher.analyze_layout_patterns()
            patterns["layout_patterns"] = layout_patterns

            # Analyze styling patterns
            styling_patterns = self.pattern_matcher.analyze_styling_patterns()
            patterns["styling_patterns"] = styling_patterns

            # Analyze event handling patterns
            event_patterns = self.pattern_matcher.analyze_event_patterns()
            patterns["event_patterns"] = event_patterns

            return patterns

        except Exception as e:
            self.logger.warning(f"Error detecting patterns for {component_name}: {e}")
            return {"error": str(e)}

    def _make_generation_decision(
        self,
        component_name: str,
        component_type: str,
        patterns: Dict[str, Any],
        context: Dict[str, Any],
        config: HybridGenerationConfig,
    ) -> GenerationDecision:
        """Make intelligent decision about how to generate the component."""

        # Analyze modernization level based on context
        modernization_score = context.get("modernization_score", 0.5)
        architecture_type = context.get("architecture_type", "mixed")

        # Determine modernization level
        if modernization_score >= 0.8 and architecture_type == "modern":
            modernization_level = "full"
        elif modernization_score >= 0.6:
            modernization_level = "moderate"
        elif modernization_score >= 0.4:
            modernization_level = "minimal"
        else:
            modernization_level = "none"

        # Adjust based on configuration
        if config.enhancement_strategy == "conservative":
            if modernization_level == "full":
                modernization_level = "moderate"
            elif modernization_level == "moderate":
                modernization_level = "minimal"
        elif config.enhancement_strategy == "aggressive":
            if modernization_level == "minimal":
                modernization_level = "moderate"
            elif modernization_level == "none":
                modernization_level = "minimal"

        # Determine implementation approach
        if config.backward_compatibility and modernization_score < 0.7:
            implementation_approach = "compatible"
        elif config.gradual_enhancement:
            implementation_approach = "gradual"
        else:
            implementation_approach = "direct"

        # Generate rationale
        rationale_parts = [
            f"Project modernization score: {modernization_score:.2f}",
            f"Architecture type: {architecture_type}",
            f"Enhancement strategy: {config.enhancement_strategy}",
        ]

        # Analyze risks and benefits
        risks = []
        benefits = []

        if modernization_level in ["moderate", "full"]:
            risks.append("Potential breaking changes with existing code")
            risks.append("Learning curve for new patterns")
            benefits.append("Improved performance and maintainability")
            benefits.append("Better alignment with modern Anvil practices")

        if modernization_level in ["minimal", "none"]:
            risks.append("Limited performance improvements")
            benefits.append("Maximum compatibility with existing code")
            benefits.append("Minimal disruption to development workflow")

        return GenerationDecision(
            component_name=component_name,
            pattern_detected=f"{component_type}_hybrid",
            modernization_level=modernization_level,
            rationale="; ".join(rationale_parts),
            risks=risks,
            benefits=benefits,
            implementation_approach=implementation_approach,
        )

    def _generate_component_by_approach(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        decision: GenerationDecision,
        context: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generate component based on the decided approach."""

        if decision.modernization_level == "full":
            return self._generate_modern_component(
                component_name, component_type, properties, context
            )
        elif decision.modernization_level == "moderate":
            return self._generate_hybrid_component(
                component_name, component_type, properties, decision, context
            )
        elif decision.modernization_level == "minimal":
            return self._generate_minimal_enhancement(
                component_name, component_type, properties, decision, context
            )
        else:  # none
            return self._generate_legacy_component(
                component_name, component_type, properties, context
            )

    def _generate_modern_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        context: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generate a fully modern component."""

        if component_type == "form":
            return self._generate_modern_form(component_name, properties, context)
        elif component_type == "custom_component":
            return self._generate_modern_custom_component(
                component_name, properties, context
            )
        else:
            return self._generate_generic_component(
                component_name, component_type, properties, "modern"
            )

    def _generate_hybrid_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        decision: GenerationDecision,
        context: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generate a hybrid component that balances modern and legacy patterns."""

        # Base component structure
        component = {
            "name": component_name,
            "type": component_type,
            "properties": properties.copy(),
            "hybrid_features": [],
            "compatibility_notes": [],
            "migration_path": [],
        }

        # Add hybrid features based on context
        if context.get("modern_patterns", {}).get("has_reactive", False):
            component["hybrid_features"].append("reactive_data_binding")
            component["migration_path"].append("upgrade_to_full_reactive")

        if context.get("modern_patterns", {}).get("has_m3_theme", False):
            component["hybrid_features"].append("material_3_compatible")
            component["migration_path"].append("upgrade_to_full_m3")

        if context.get("modern_patterns", {}).get("has_routing", False):
            component["hybrid_features"].append("routing_ready")
            component["migration_path"].append("integrate_with_routing")

        # Add compatibility notes
        if decision.implementation_approach == "compatible":
            component["compatibility_notes"].append(
                "Designed for backward compatibility with existing code"
            )
            component["compatibility_notes"].append(
                "Can coexist with legacy components"
            )

        return component

    def _generate_minimal_enhancement(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        decision: GenerationDecision,
        context: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generate a component with minimal modern enhancements."""

        component = {
            "name": component_name,
            "type": component_type,
            "properties": properties.copy(),
            "minimal_enhancements": [],
            "legacy_compatibility": True,
        }

        # Add minimal enhancements that won't break existing code
        component["minimal_enhancements"].append("improved_naming_conventions")
        component["minimal_enhancements"].append("basic_performance_optimizations")
        component["minimal_enhancements"].append("enhanced_error_handling")

        return component

    def _generate_legacy_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        context: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generate a component using legacy patterns for maximum compatibility."""

        component = {
            "name": component_name,
            "type": component_type,
            "properties": properties.copy(),
            "legacy_mode": True,
            "compatibility_level": "maximum",
        }

        return component

    def _analyze_existing_form(self, form_path: Path) -> Dict[str, Any]:
        """Analyze an existing form to understand its structure and patterns."""
        try:
            # Read form file
            if form_path.suffix == ".yaml":
                with open(form_path, "r", encoding="utf-8") as f:
                    form_content = f.read()
            else:
                # For Python forms, we'd need to parse the Python code
                # This is a simplified implementation
                form_content = ""

            analysis = {
                "form_path": str(form_path),
                "form_type": "yaml" if form_path.suffix == ".yaml" else "python",
                "components": [],
                "patterns": {},
                "modernization_potential": 0.5,
            }

            # Analyze YAML form structure
            if form_content:
                analysis["components"] = self._extract_components_from_yaml(
                    form_content
                )
                analysis["patterns"] = self._analyze_form_patterns(form_content)
                analysis["modernization_potential"] = (
                    self._calculate_modernization_potential(
                        analysis["components"], analysis["patterns"]
                    )
                )

            return analysis

        except Exception as e:
            self.logger.error(f"Error analyzing form {form_path}: {e}")
            return {"error": str(e), "form_path": str(form_path)}

    def _determine_enhancement_strategy(
        self,
        form_analysis: Dict[str, Any],
        enhancement_type: str,
        config: HybridGenerationConfig,
    ) -> Dict[str, Any]:
        """Determine the best enhancement strategy for the form."""

        modernization_potential = form_analysis.get("modernization_potential", 0.5)

        strategy = {
            "type": enhancement_type,
            "modernization_level": "minimal",
            "enhancements": [],
            "risks": [],
            "timeline": "short",
        }

        if enhancement_type == "aggressive" and modernization_potential > 0.7:
            strategy["modernization_level"] = "full"
            strategy["enhancements"] = [
                "convert_to_reactive",
                "upgrade_to_m3_components",
                "implement_modern_layout",
                "add_data_validation",
            ]
            strategy["timeline"] = "medium"
        elif enhancement_type == "conservative":
            strategy["modernization_level"] = "minimal"
            strategy["enhancements"] = [
                "improve_naming",
                "add_error_handling",
                "basic_performance_optimization",
            ]
        else:  # adaptive
            if modernization_potential > 0.6:
                strategy["modernization_level"] = "moderate"
                strategy["enhancements"] = [
                    "add_reactive_data_binding",
                    "upgrade_key_components",
                    "improve_layout_structure",
                ]
            else:
                strategy["modernization_level"] = "minimal"
                strategy["enhancements"] = [
                    "improve_naming_conventions",
                    "add_basic_validation",
                ]

        return strategy

    def _apply_form_enhancements(
        self,
        form_analysis: Dict[str, Any],
        strategy: Dict[str, Any],
        config: HybridGenerationConfig,
    ) -> Dict[str, Any]:
        """Apply the determined enhancements to the form."""

        enhanced_form = form_analysis.copy()
        enhanced_form["enhancements_applied"] = []
        enhanced_form["changes"] = []

        for enhancement in strategy["enhancements"]:
            if enhancement == "convert_to_reactive":
                change = self._add_reactive_patterns(form_analysis)
                enhanced_form["changes"].append(change)
                enhanced_form["enhancements_applied"].append("reactive_patterns")

            elif enhancement == "upgrade_to_m3_components":
                change = self._upgrade_components_to_m3(form_analysis)
                enhanced_form["changes"].append(change)
                enhanced_form["enhancements_applied"].append("m3_components")

            elif enhancement == "improve_naming":
                change = self._improve_component_naming(form_analysis)
                enhanced_form["changes"].append(change)
                enhanced_form["enhancements_applied"].append("improved_naming")

            # Add more enhancement implementations as needed

        return enhanced_form

    def _create_enhancement_phases(
        self,
        component_analyses: Dict[str, Any],
        migration_goals: List[str],
        config: HybridGenerationConfig,
    ) -> List[Dict[str, Any]]:
        """Create phased enhancement plan."""

        phases = []

        # Phase 1: Preparation and Analysis
        phases.append(
            {
                "name": "Preparation and Analysis",
                "description": "Analyze existing code and prepare for enhancement",
                "tasks": [
                    "Complete component analysis",
                    "Identify dependencies and risks",
                    "Create backup strategy",
                    "Set up testing framework",
                ],
                "estimated_duration": "1-2 days",
                "priority": "high",
            }
        )

        # Phase 2: Minimal Enhancements
        phases.append(
            {
                "name": "Minimal Enhancements",
                "description": "Apply safe, non-breaking enhancements",
                "tasks": [
                    "Improve naming conventions",
                    "Add error handling",
                    "Basic performance optimizations",
                    "Documentation improvements",
                ],
                "estimated_duration": "2-3 days",
                "priority": "high",
            }
        )

        # Phase 3: Moderate Modernization
        if config.enhancement_strategy in ["adaptive", "aggressive"]:
            phases.append(
                {
                    "name": "Moderate Modernization",
                    "description": "Apply moderate modernization while maintaining compatibility",
                    "tasks": [
                        "Add reactive data binding where appropriate",
                        "Upgrade key components to M3",
                        "Improve layout structure",
                        "Add data validation",
                    ],
                    "estimated_duration": "3-5 days",
                    "priority": "medium",
                }
            )

        # Phase 4: Full Modernization (if aggressive)
        if config.enhancement_strategy == "aggressive":
            phases.append(
                {
                    "name": "Full Modernization",
                    "description": "Complete modernization to latest patterns",
                    "tasks": [
                        "Convert to fully reactive architecture",
                        "Implement modern layout system",
                        "Add comprehensive testing",
                        "Performance optimization",
                    ],
                    "estimated_duration": "5-7 days",
                    "priority": "low",
                }
            )

        return phases

    def _assess_enhancement_risks(
        self,
        component_analyses: Dict[str, Any],
        phases: List[Dict[str, Any]],
        config: HybridGenerationConfig,
    ) -> Dict[str, Any]:
        """Assess risks associated with the enhancement plan."""

        risks = {
            "overall_risk": config.risk_tolerance,
            "technical_risks": [],
            "business_risks": [],
            "mitigation_strategies": [],
        }

        # Analyze technical risks
        for component_name, analysis in component_analyses.items():
            modernization_potential = analysis.get("modernization_potential", 0.5)

            if modernization_potential < 0.4:
                risks["technical_risks"].append(
                    f"Component {component_name} has low modernization potential"
                )

        # Add general risks based on strategy
        if config.enhancement_strategy == "aggressive":
            risks["technical_risks"].append("High potential for breaking changes")
            risks["business_risks"].append("Extended development timeline")

        # Mitigation strategies
        risks["mitigation_strategies"] = [
            "Comprehensive testing before each phase",
            "Backup and rollback procedures",
            "Gradual rollout with monitoring",
            "Team training and documentation",
        ]

        return risks

    def _create_rollback_plan(
        self, component_analyses: Dict[str, Any], phases: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """Create rollback plan for the enhancement process."""

        return {
            "backup_strategy": "Full project backup before each phase",
            "rollback_triggers": [
                "Critical functionality broken",
                "Performance degradation > 20%",
                "Team unable to maintain new patterns",
            ],
            "rollback_procedures": [
                "Restore from backup",
                "Verify functionality",
                "Document lessons learned",
                "Adjust enhancement strategy",
            ],
            "rollback_timeline": "2-4 hours for complete rollback",
        }

    def _estimate_timeline(self, phases: List[Dict[str, Any]]) -> str:
        """Estimate total timeline for enhancement plan."""
        total_days = 0
        for phase in phases:
            duration_str = phase.get("estimated_duration", "1 day")
            # Extract number from duration string
            if "-" in duration_str:
                min_days, max_days = duration_str.split("-")
                # Use average for estimation
                days = (int(min_days) + int(max_days.split()[0])) / 2
            else:
                days = int(duration_str.split()[0])
            total_days += days

        return f"{int(total_days)}-{int(total_days * 1.2)} days"

    def _define_success_criteria(self, migration_goals: List[str]) -> List[str]:
        """Define success criteria for the enhancement plan."""

        criteria = [
            "All enhancements applied without breaking existing functionality",
            "Performance improvements measurable and significant",
            "Code maintainability improved",
            "Team successfully adopts new patterns",
        ]

        # Add goal-specific criteria
        if "performance" in migration_goals:
            criteria.append("Page load times reduced by at least 20%")

        if "maintainability" in migration_goals:
            criteria.append("Code complexity reduced by at least 15%")

        if "modernization" in migration_goals:
            criteria.append("Modernization score increased by at least 0.3")

        return criteria

    # Helper methods for form analysis
    def _extract_components_from_yaml(self, yaml_content: str) -> List[Dict[str, Any]]:
        """Extract component information from YAML content."""
        components = []

        # Simple regex-based extraction (in real implementation, use YAML parser)
        component_pattern = r"- name:\s*(\w+)\s*\n\s*type:\s*(\w+)"
        matches = re.findall(component_pattern, yaml_content)

        for name, comp_type in matches:
            components.append({"name": name, "type": comp_type})

        return components

    def _analyze_form_patterns(self, yaml_content: str) -> Dict[str, Any]:
        """Analyze patterns used in the form."""
        patterns = {
            "has_legacy_components": False,
            "has_modern_components": False,
            "layout_type": "unknown",
            "data_binding": False,
        }

        # Check for legacy components
        legacy_components = ["ColumnPanel", "FlowPanel", "GridPanel"]
        for comp in legacy_components:
            if comp in yaml_content:
                patterns["has_legacy_components"] = True
                patterns["layout_type"] = "legacy"
                break

        # Check for modern components
        modern_components = ["NavigationDrawerLayout", "NavigationRailLayout"]
        for comp in modern_components:
            if comp in yaml_content:
                patterns["has_modern_components"] = True
                patterns["layout_type"] = "modern"
                break

        # Check for data binding
        if "data_bindings" in yaml_content:
            patterns["data_binding"] = True

        return patterns

    def _calculate_modernization_potential(
        self, components: List[Dict[str, Any]], patterns: Dict[str, Any]
    ) -> float:
        """Calculate modernization potential for the form."""

        potential = 0.5  # Base score

        # Adjust based on patterns
        if patterns.get("has_legacy_components", False):
            potential += 0.2  # Room for improvement

        if patterns.get("has_modern_components", False):
            potential += 0.1  # Already partially modern

        if not patterns.get("data_binding", False):
            potential += 0.1  # Can add data binding

        # Adjust based on component count
        if len(components) > 10:
            potential += 0.1  # Complex form benefits more from modernization

        return min(potential, 1.0)

    def _add_reactive_patterns(self, form_analysis: Dict[str, Any]) -> Dict[str, Any]:
        """Add reactive patterns to form analysis."""
        return {
            "type": "reactive_enhancement",
            "description": "Added reactive data binding capabilities",
            "components_affected": len(form_analysis.get("components", [])),
        }

    def _upgrade_components_to_m3(
        self, form_analysis: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Upgrade components to Material 3."""
        return {
            "type": "m3_upgrade",
            "description": "Upgraded components to Material 3 specifications",
            "components_upgraded": len(form_analysis.get("components", [])),
        }

    def _improve_component_naming(
        self, form_analysis: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Improve component naming conventions."""
        return {
            "type": "naming_improvement",
            "description": "Improved component naming for better maintainability",
            "components_renamed": len(form_analysis.get("components", [])),
        }

    def _generate_modern_form(
        self, component_name: str, properties: Dict[str, Any], context: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Generate a fully modern form."""
        return {
            "name": component_name,
            "type": "form",
            "properties": properties,
            "modern_features": [
                "reactive_data_binding",
                "material_3_components",
                "modern_layout",
                "responsive_design",
                "accessibility_features",
            ],
            "architecture": "modern",
        }

    def _generate_modern_custom_component(
        self, component_name: str, properties: Dict[str, Any], context: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Generate a modern custom component."""
        return {
            "name": component_name,
            "type": "custom_component",
            "properties": properties,
            "modern_features": [
                "slot_based_architecture",
                "material_3_styling",
                "reactive_properties",
                "event_handling",
                "accessibility_support",
            ],
            "architecture": "modern",
        }

    def _generate_generic_component(
        self,
        component_name: str,
        component_type: str,
        properties: Dict[str, Any],
        architecture: str,
    ) -> Dict[str, Any]:
        """Generate a generic component."""
        return {
            "name": component_name,
            "type": component_type,
            "properties": properties,
            "architecture": architecture,
        }
