"""
Form Migrator for Hephaestus

Migrates existing forms to reactive patterns while preserving
functionality and enabling gradual enhancement.
"""

from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
import re
import yaml

from ..models.project_context import ProjectContext


class MigrationStrategy(Enum):
    """Migration strategies for forms."""

    PRESERVE_EXISTING = "preserve_existing"
    ENHANCE_GRADUALLY = "enhance_gradually"
    FULL_REACTIVE = "full_reactive"
    HYBRID_APPROACH = "hybrid_approach"


class ComponentType(Enum):
    """Types of components to migrate."""

    INPUT = "input"
    DISPLAY = "display"
    CONTAINER = "container"
    INTERACTIVE = "interactive"
    LAYOUT = "layout"


@dataclass
class FormComponent:
    """Represents a form component for migration."""

    name: str
    component_type: str
    properties: Dict[str, Any]
    event_handlers: Dict[str, str]
    data_bindings: List[Dict[str, Any]]
    layout_properties: Dict[str, Any]
    children: List["FormComponent"]
    migration_notes: List[str]


@dataclass
class ReactiveBinding:
    """Represents a reactive data binding."""

    component_property: str
    data_source: str
    binding_type: str  # "one_way", "two_way", "computed"
    transform: Optional[str] = None
    validation: Optional[str] = None
    writeback: bool = True


@dataclass
class MigrationResult:
    """Result of form migration."""

    success: bool
    original_form: Path
    migrated_form: Path
    components_migrated: int
    reactive_bindings_added: int
    breaking_changes: List[str]
    enhancements: List[str]
    warnings: List[str]
    migration_strategy: MigrationStrategy
    validation_results: Dict[str, Any]


class FormMigrator:
    """Migrates existing forms to reactive patterns."""

    def __init__(self, file_system, project_manager):
        self.file_system = file_system
        self.project_manager = project_manager

        # Component migration rules
        self._component_migration_rules = self._initialize_component_rules()

        # Reactive binding patterns
        self._binding_patterns = self._initialize_binding_patterns()

        # Event handler migration patterns
        self._event_migration_patterns = self._initialize_event_patterns()

        # Validation strategies
        self._validation_strategies = self._initialize_validation_strategies()

    def migrate_form_to_reactive(
        self,
        form_path: Path,
        project_context: ProjectContext,
        strategy: Optional[MigrationStrategy] = None,
        options: Optional[Dict[str, Any]] = None,
    ) -> MigrationResult:
        """
        Migrate an existing form to reactive patterns.

        Args:
            form_path: Path to form YAML file
            project_context: Project context information
            strategy: Migration strategy to use
            options: Additional migration options

        Returns:
            Migration result with details
        """
        if not form_path.exists():
            raise FileNotFoundError(f"Form not found: {form_path}")

        options = options or {}
        strategy = strategy or self._determine_optimal_strategy(project_context)

        # Parse original form
        original_form = self._parse_form_yaml(form_path)

        # Analyze form structure
        form_analysis = self._analyze_form_structure(original_form)

        # Create migration plan
        migration_plan = self._create_migration_plan(
            form_analysis, project_context, strategy, options
        )

        # Execute migration
        migrated_form = self._execute_migration_plan(
            original_form, migration_plan, project_context
        )

        # Validate migration
        validation_results = self._validate_migrated_form(
            migrated_form, original_form, project_context
        )

        # Generate migration result
        result = self._generate_migration_result(
            form_path, migrated_form, migration_plan, validation_results, strategy
        )

        # Save migrated form
        if result.success:
            self._save_migrated_form(form_path, migrated_form, options)

        return result

    def analyze_form_migration_feasibility(
        self, form_path: Path, project_context: ProjectContext
    ) -> Dict[str, Any]:
        """
        Analyze feasibility of migrating a form to reactive patterns.

        Args:
            form_path: Path to form YAML file
            project_context: Project context information

        Returns:
            Feasibility analysis with recommendations
        """
        if not form_path.exists():
            return {"feasible": False, "reason": "Form file not found"}

        # Parse and analyze form
        original_form = self._parse_form_yaml(form_path)
        form_analysis = self._analyze_form_structure(original_form)

        # Assess migration complexity
        complexity_score = self._assess_migration_complexity(form_analysis)

        # Identify potential issues
        potential_issues = self._identify_migration_issues(
            form_analysis, project_context
        )

        # Recommend strategy
        recommended_strategy = self._recommend_migration_strategy(
            form_analysis, project_context, complexity_score
        )

        # Estimate effort
        effort_estimate = self._estimate_migration_effort(
            form_analysis, complexity_score
        )

        return {
            "feasible": True,
            "complexity_score": complexity_score,
            "complexity_level": self._score_to_complexity_level(complexity_score),
            "potential_issues": potential_issues,
            "recommended_strategy": recommended_strategy.value,
            "estimated_effort": effort_estimate,
            "form_analysis": form_analysis,
            "migration_benefits": self._identify_migration_benefits(form_analysis),
            "prerequisites": self._identify_migration_prerequisites(
                form_analysis, project_context
            ),
        }

    def create_reactive_enhancement_plan(
        self,
        form_path: Path,
        target_enhancements: List[str],
        project_context: ProjectContext,
    ) -> Dict[str, Any]:
        """
        Create plan for enhancing a form with reactive features.

        Args:
            form_path: Path to form YAML file
            target_enhancements: List of desired enhancements
            project_context: Project context information

        Returns:
            Enhancement plan with implementation steps
        """
        original_form = self._parse_form_yaml(form_path)
        form_analysis = self._analyze_form_structure(original_form)

        enhancement_plan = {
            "form_path": form_path,
            "target_enhancements": target_enhancements,
            "current_state": form_analysis,
            "enhancement_steps": [],
            "reactive_bindings": [],
            "component_upgrades": [],
            "estimated_effort": "",
            "breaking_changes": [],
            "validation_requirements": [],
        }

        # Plan each enhancement
        for enhancement in target_enhancements:
            enhancement_steps = self._plan_enhancement(
                enhancement, form_analysis, project_context
            )
            enhancement_plan["enhancement_steps"].extend(enhancement_steps)

        # Calculate total effort
        enhancement_plan["estimated_effort"] = self._calculate_enhancement_effort(
            enhancement_plan["enhancement_steps"]
        )

        # Identify breaking changes
        enhancement_plan["breaking_changes"] = (
            self._identify_enhancement_breaking_changes(
                enhancement_plan["enhancement_steps"]
            )
        )

        return enhancement_plan

    def _initialize_component_rules(self) -> Dict[str, Dict[str, Any]]:
        """Initialize component migration rules."""
        return {
            "TextBox": {
                "reactive_properties": ["text", "placeholder", "enabled"],
                "binding_pattern": "text",
                "event_handlers": ["change", "focus", "blur"],
                "migration_rules": {
                    "preserve_value": True,
                    "add_writeback": True,
                    "add_validation": True,
                },
            },
            "Button": {
                "reactive_properties": ["enabled", "text", "visible"],
                "binding_pattern": "enabled",
                "event_handlers": ["click"],
                "migration_rules": {
                    "preserve_functionality": True,
                    "add_conditional_enable": True,
                },
            },
            "Label": {
                "reactive_properties": ["text", "visible", "foreground_color"],
                "binding_pattern": "text",
                "event_handlers": [],
                "migration_rules": {
                    "preserve_content": True,
                    "add_dynamic_text": True,
                },
            },
            "CheckBox": {
                "reactive_properties": ["checked", "enabled", "visible"],
                "binding_pattern": "checked",
                "event_handlers": ["change"],
                "migration_rules": {
                    "preserve_state": True,
                    "add_writeback": True,
                },
            },
            "DropDown": {
                "reactive_properties": [
                    "selected_value",
                    "enabled",
                    "visible",
                    "items",
                ],
                "binding_pattern": "selected_value",
                "event_handlers": ["change"],
                "migration_rules": {
                    "preserve_selection": True,
                    "add_writeback": True,
                    "add_items_binding": True,
                },
            },
            "DataGrid": {
                "reactive_properties": ["rows", "columns", "selected_row"],
                "binding_pattern": "rows",
                "event_handlers": ["row_selected", "cell_edited"],
                "migration_rules": {
                    "preserve_data": True,
                    "add_reactive_rows": True,
                    "add_selection_binding": True,
                },
            },
            "ColumnPanel": {
                "reactive_properties": ["visible", "spacing", "padding"],
                "binding_pattern": None,
                "event_handlers": ["show", "hide"],
                "migration_rules": {
                    "preserve_layout": True,
                    "add_conditional_visibility": True,
                },
            },
            "FlowPanel": {
                "reactive_properties": ["visible", "spacing", "wrap"],
                "binding_pattern": None,
                "event_handlers": ["show", "hide"],
                "migration_rules": {
                    "preserve_layout": True,
                    "add_responsive_behavior": True,
                },
            },
        }

    def _initialize_binding_patterns(self) -> Dict[str, Dict[str, Any]]:
        """Initialize reactive binding patterns."""
        return {
            "simple_binding": {
                "pattern": "{property}: {data_source}",
                "writeback": True,
                "validation": None,
            },
            "computed_binding": {
                "pattern": "{property}: lambda: {expression}",
                "writeback": False,
                "validation": None,
            },
            "transformed_binding": {
                "pattern": "{property}: lambda: {transform_function}({data_source})",
                "writeback": True,
                "validation": None,
            },
            "validated_binding": {
                "pattern": "{property}: {data_source} if {validation_condition} else None",
                "writeback": True,
                "validation": "custom",
            },
        }

    def _initialize_event_patterns(self) -> Dict[str, Dict[str, Any]]:
        """Initialize event handler migration patterns."""
        return {
            "click_handler": {
                "pattern": "def {component}_{event}(self, **event_args):",
                "reactive_enhancement": "Add state updates and validation",
            },
            "change_handler": {
                "pattern": "def {component}_{event}(self, **event_args):",
                "reactive_enhancement": "Add reactive state updates",
            },
            "form_handler": {
                "pattern": "def {event}_handler(self, **event_args):",
                "reactive_enhancement": "Add form-level reactive behavior",
            },
        }

    def _initialize_validation_strategies(self) -> Dict[str, List[str]]:
        """Initialize validation strategies for reactive forms."""
        return {
            "input_validation": [
                "Add real-time validation feedback",
                "Use reactive validation signals",
                "Implement validation error display",
            ],
            "form_validation": [
                "Add form-level validation state",
                "Implement conditional submission",
                "Add validation summary display",
            ],
            "data_validation": [
                "Add type checking",
                "Implement range validation",
                "Add custom validation rules",
            ],
        }

    def _determine_optimal_strategy(
        self, project_context: ProjectContext
    ) -> MigrationStrategy:
        """Determine optimal migration strategy based on project context."""
        if project_context.has_reactive:
            return MigrationStrategy.ENHANCE_GRADUALLY
        elif project_context.modernisation_score >= 0.6:
            return MigrationStrategy.HYBRID_APPROACH
        elif project_context.modernisation_score >= 0.3:
            return MigrationStrategy.PRESERVE_EXISTING
        else:
            return MigrationStrategy.FULL_REACTIVE

    def _parse_form_yaml(self, form_path: Path) -> Dict[str, Any]:
        """Parse form YAML file."""
        try:
            content = self.file_system.read_text(form_path)
            return yaml.safe_load(content) or {}
        except yaml.YAMLError as e:
            raise ValueError(f"Invalid YAML in {form_path}: {e}")

    def _analyze_form_structure(self, form_yaml: Dict[str, Any]) -> Dict[str, Any]:
        """Analyze form structure and components."""
        analysis = {
            "components": [],
            "component_count": 0,
            "component_types": {},
            "has_data_bindings": False,
            "has_event_handlers": False,
            "complexity_score": 0.0,
            "migration_challenges": [],
        }

        # Analyze container
        container = form_yaml.get("container", {})
        analysis["container_type"] = container.get("type", "ColumnPanel")

        # Analyze components
        components = form_yaml.get("components", [])
        for component in components:
            component_analysis = self._analyze_component(component)
            analysis["components"].append(component_analysis)
            analysis["component_count"] += 1

            # Track component types
            comp_type = component.get("type", "Unknown")
            analysis["component_types"][comp_type] = (
                analysis["component_types"].get(comp_type, 0) + 1
            )

            # Check for data bindings
            if component.get("data_bindings"):
                analysis["has_data_bindings"] = True

            # Check for event handlers
            if component.get("event_bindings"):
                analysis["has_event_handlers"] = True

            # Update complexity score
            analysis["complexity_score"] += component_analysis[
                "complexity_contribution"
            ]

        # Identify migration challenges
        analysis["migration_challenges"] = self._identify_component_challenges(
            analysis["components"]
        )

        return analysis

    def _analyze_component(self, component: Dict[str, Any]) -> Dict[str, Any]:
        """Analyze individual component for migration."""
        component_type = component.get("type", "Unknown")
        name = component.get("name", "unnamed")

        analysis = {
            "name": name,
            "type": component_type,
            "properties": component.get("properties", {}),
            "event_handlers": component.get("event_bindings", {}),
            "data_bindings": component.get("data_bindings", []),
            "layout_properties": component.get("layout_properties", {}),
            "complexity_contribution": 1.0,
            "migration_notes": [],
            "reactive_potential": "medium",
        }

        # Get migration rules for this component type
        migration_rules = self._component_migration_rules.get(component_type, {})

        # Assess reactive potential
        reactive_properties = migration_rules.get("reactive_properties", [])
        if reactive_properties:
            matching_properties = len(
                [prop for prop in reactive_properties if prop in analysis["properties"]]
            )
            if matching_properties > len(reactive_properties) / 2:
                analysis["reactive_potential"] = "high"
            elif matching_properties > 0:
                analysis["reactive_potential"] = "medium"
            else:
                analysis["reactive_potential"] = "low"

        # Calculate complexity contribution
        if analysis["event_handlers"]:
            analysis["complexity_contribution"] += len(analysis["event_handlers"]) * 0.5

        if analysis["data_bindings"]:
            analysis["complexity_contribution"] += len(analysis["data_bindings"]) * 0.3

        # Add migration notes
        if component_type not in self._component_migration_rules:
            analysis["migration_notes"].append(
                f"Unknown component type: {component_type}"
            )
            analysis["complexity_contribution"] += 2.0

        return analysis

    def _create_migration_plan(
        self,
        form_analysis: Dict[str, Any],
        project_context: ProjectContext,
        strategy: MigrationStrategy,
        options: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Create detailed migration plan."""
        plan = {
            "strategy": strategy.value,
            "components_to_migrate": [],
            "reactive_bindings_to_add": [],
            "event_handlers_to_update": [],
            "validation_to_add": [],
            "breaking_changes": [],
            "enhancements": [],
        }

        # Plan component migrations based on strategy
        for component in form_analysis["components"]:
            migration_plan_component = self._plan_component_migration(
                component, strategy, project_context
            )
            plan["components_to_migrate"].append(migration_plan_component)

        # Plan reactive bindings
        if strategy in [
            MigrationStrategy.ENHANCE_GRADUALLY,
            MigrationStrategy.FULL_REACTIVE,
        ]:
            for component in form_analysis["components"]:
                bindings = self._plan_reactive_bindings(component, strategy)
                plan["reactive_bindings_to_add"].extend(bindings)

        # Plan event handler updates
        if strategy != MigrationStrategy.PRESERVE_EXISTING:
            for component in form_analysis["components"]:
                event_updates = self._plan_event_handler_updates(component, strategy)
                plan["event_handlers_to_update"].extend(event_updates)

        # Plan validation additions
        if strategy in [
            MigrationStrategy.FULL_REACTIVE,
            MigrationStrategy.HYBRID_APPROACH,
        ]:
            validation_plan = self._plan_validation_additions(form_analysis, strategy)
            plan["validation_to_add"] = validation_plan

        # Identify breaking changes
        plan["breaking_changes"] = self._identify_breaking_changes(
            plan, strategy, project_context
        )

        # Identify enhancements
        plan["enhancements"] = self._identify_enhancements(plan, strategy)

        return plan

    def _execute_migration_plan(
        self,
        original_form: Dict[str, Any],
        migration_plan: Dict[str, Any],
        project_context: ProjectContext,
    ) -> Dict[str, Any]:
        """Execute migration plan on form."""
        migrated_form = original_form.copy()

        # Migrate components
        migrated_components = []
        for component_plan in migration_plan["components_to_migrate"]:
            migrated_component = self._migrate_component(
                component_plan, migration_plan["strategy"]
            )
            migrated_components.append(migrated_component)

        migrated_form["components"] = migrated_components

        # Add reactive bindings
        if migration_plan["reactive_bindings_to_add"]:
            migrated_form = self._add_reactive_bindings(
                migrated_form, migration_plan["reactive_bindings_to_add"]
            )

        # Update event handlers
        if migration_plan["event_handlers_to_update"]:
            migrated_form = self._update_event_handlers(
                migrated_form, migration_plan["event_handlers_to_update"]
            )

        # Add validation
        if migration_plan["validation_to_add"]:
            migrated_form = self._add_validation(
                migrated_form, migration_plan["validation_to_add"]
            )

        # Add reactive class decorator if needed
        if migration_plan["strategy"] in [
            MigrationStrategy.FULL_REACTIVE,
            MigrationStrategy.HYBRID_APPROACH,
        ]:
            migrated_form = self._add_reactive_class_decorator(migrated_form)

        return migrated_form

    def _plan_component_migration(
        self,
        component: Dict[str, Any],
        strategy: MigrationStrategy,
        project_context: ProjectContext,
    ) -> Dict[str, Any]:
        """Plan migration for individual component."""
        component_type = component["type"]
        migration_rules = self._component_migration_rules.get(component_type, {})

        plan = {
            "original_component": component,
            "component_type": component_type,
            "strategy": strategy.value,
            "properties_to_update": [],
            "bindings_to_add": [],
            "events_to_update": [],
            "migration_rules": migration_rules.get("migration_rules", {}),
        }

        # Plan property updates based on strategy
        if strategy != MigrationStrategy.PRESERVE_EXISTING:
            reactive_properties = migration_rules.get("reactive_properties", [])
            for prop in reactive_properties:
                if prop in component["properties"]:
                    plan["properties_to_update"].append(
                        {
                            "property": prop,
                            "current_value": component["properties"][prop],
                            "reactive_enhancement": f"Add reactive binding for {prop}",
                        }
                    )

        return plan

    def _plan_reactive_bindings(
        self, component: Dict[str, Any], strategy: MigrationStrategy
    ) -> List[Dict[str, Any]]:
        """Plan reactive bindings for a component."""
        bindings = []
        component_type = component["type"]

        # Get binding pattern for this component type
        migration_rules = self._component_migration_rules.get(component_type, {})
        binding_pattern = migration_rules.get("binding_pattern")

        if not binding_pattern:
            return bindings

        # Create binding based on component properties
        if component["properties"]:
            for prop_name, prop_value in component["properties"].items():
                if prop_name in migration_rules.get("reactive_properties", []):
                    binding = {
                        "component_name": component["name"],
                        "property": prop_name,
                        "data_source": f"self.{prop_name}_signal",
                        "binding_type": "two_way"
                        if strategy == MigrationStrategy.FULL_REACTIVE
                        else "one_way",
                        "writeback": migration_rules.get("migration_rules", {}).get(
                            "add_writeback", True
                        ),
                    }
                    bindings.append(binding)

        return bindings

    def _plan_event_handler_updates(
        self, component: Dict[str, Any], strategy: MigrationStrategy
    ) -> List[Dict[str, Any]]:
        """Plan event handler updates for a component."""
        updates = []

        if strategy == MigrationStrategy.PRESERVE_EXISTING:
            return updates

        component_name = component["name"]
        component_type = component["type"]

        for event_name, event_handler in component["event_handlers"].items():
            update = {
                "component_name": component_name,
                "event": event_name,
                "current_handler": event_handler,
                "enhancement": f"Add reactive state updates to {event_name} handler",
                "reactive_pattern": self._event_migration_patterns.get(
                    f"{event_name}_handler", {}
                ),
            }
            updates.append(update)

        return updates

    def _migrate_component(
        self, component_plan: Dict[str, Any], strategy: MigrationStrategy
    ) -> Dict[str, Any]:
        """Migrate individual component based on plan."""
        original_component = component_plan["original_component"]
        migrated_component = original_component.copy()

        # Update properties
        for prop_update in component_plan["properties_to_update"]:
            prop_name = prop_update["property"]
            if strategy == MigrationStrategy.FULL_REACTIVE:
                # Add reactive binding
                if "data_bindings" not in migrated_component:
                    migrated_component["data_bindings"] = []

                binding = {
                    "property": prop_name,
                    "code": f"self.{prop_name}_signal",
                    "writeback": True,
                }
                migrated_component["data_bindings"].append(binding)

        return migrated_component

    def _add_reactive_bindings(
        self, form: Dict[str, Any], bindings: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """Add reactive bindings to form."""
        for binding in bindings:
            component_name = binding["component_name"]
            property_name = binding["property"]
            data_source = binding["data_source"]

            # Find the component
            for component in form.get("components", []):
                if component.get("name") == component_name:
                    if "data_bindings" not in component:
                        component["data_bindings"] = []

                    # Add or update binding
                    existing_binding = None
                    for i, existing in enumerate(component["data_bindings"]):
                        if existing["property"] == property_name:
                            existing_binding = i
                            break

                    binding_data = {
                        "property": property_name,
                        "code": data_source,
                        "writeback": binding.get("writeback", True),
                    }

                    if existing_binding is not None:
                        component["data_bindings"][existing_binding] = binding_data
                    else:
                        component["data_bindings"].append(binding_data)

                    break

        return form

    def _update_event_handlers(
        self, form: Dict[str, Any], event_updates: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """Update event handlers in form."""
        for update in event_updates:
            component_name = update["component_name"]
            event_name = update["event"]

            # Find the component
            for component in form.get("components", []):
                if component.get("name") == component_name:
                    if "event_bindings" not in component:
                        component["event_bindings"] = {}

                    # Update event handler with reactive enhancement
                    component["event_bindings"][event_name] = (
                        f"{update['current_handler']} # Enhanced with reactive patterns"
                    )
                    break

        return form

    def _add_validation(
        self, form: Dict[str, Any], validation_plan: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """Add validation to form."""
        # Add form-level validation
        if "form_validation" not in form:
            form["form_validation"] = {}

        for validation in validation_plan:
            validation_type = validation["type"]
            validation_rules = validation["rules"]

            form["form_validation"][validation_type] = validation_rules

        return form

    def _add_reactive_class_decorator(self, form: Dict[str, Any]) -> Dict[str, Any]:
        """Add reactive class decorator to form."""
        # This would be implemented in the actual Python code generation
        # For YAML migration, we add metadata
        if "metadata" not in form:
            form["metadata"] = {}

        form["metadata"]["reactive_class"] = True
        form["metadata"]["reactive_imports"] = [
            "from anvil_extras.reactive import reactive_class, signal, render_effect, bind"
        ]

        return form

    def _validate_migrated_form(
        self,
        migrated_form: Dict[str, Any],
        original_form: Dict[str, Any],
        project_context: ProjectContext,
    ) -> Dict[str, Any]:
        """Validate migrated form for correctness."""
        validation_results = {
            "is_valid": True,
            "errors": [],
            "warnings": [],
            "enhancements": [],
            "compatibility_issues": [],
        }

        # Check component count preservation
        original_count = len(original_form.get("components", []))
        migrated_count = len(migrated_form.get("components", []))
        if original_count != migrated_count:
            validation_results["errors"].append(
                f"Component count mismatch: {original_count} -> {migrated_count}"
            )
            validation_results["is_valid"] = False

        # Check reactive binding syntax
        for component in migrated_form.get("components", []):
            bindings = component.get("data_bindings", [])
            for binding in bindings:
                if not binding.get("property") or not binding.get("code"):
                    validation_results["errors"].append(
                        f"Invalid binding in component {component.get('name')}"
                    )
                    validation_results["is_valid"] = False

        # Check project compatibility
        if not project_context.has_reactive:
            validation_results["warnings"].append(
                "Reactive patterns added but project doesn't have reactive library"
            )

        return validation_results

    def _generate_migration_result(
        self,
        original_form_path: Path,
        migrated_form: Dict[str, Any],
        migration_plan: Dict[str, Any],
        validation_results: Dict[str, Any],
        strategy: MigrationStrategy,
    ) -> MigrationResult:
        """Generate migration result object."""
        components_migrated = len(migration_plan["components_to_migrate"])
        reactive_bindings_added = len(migration_plan["reactive_bindings_to_add"])

        return MigrationResult(
            success=validation_results["is_valid"],
            original_form=original_form_path,
            migrated_form=original_form_path,  # Would be different path in real implementation
            components_migrated=components_migrated,
            reactive_bindings_added=reactive_bindings_added,
            breaking_changes=migration_plan["breaking_changes"],
            enhancements=migration_plan["enhancements"],
            warnings=validation_results["warnings"],
            migration_strategy=strategy,
            validation_results=validation_results,
        )

    def _save_migrated_form(
        self,
        original_path: Path,
        migrated_form: Dict[str, Any],
        options: Dict[str, Any],
    ) -> None:
        """Save migrated form to file."""
        # In a real implementation, this would save to a new file
        # For now, we'll just validate the YAML structure
        try:
            yaml.dump(migrated_form, default_flow_style=False)
        except yaml.YAMLError as e:
            raise ValueError(f"Invalid YAML in migrated form: {e}")

    def _assess_migration_complexity(self, form_analysis: Dict[str, Any]) -> float:
        """Assess complexity of migrating a form."""
        base_score = form_analysis["complexity_score"]

        # Add complexity for data bindings
        if form_analysis["has_data_bindings"]:
            base_score += 2.0

        # Add complexity for event handlers
        if form_analysis["has_event_handlers"]:
            base_score += 1.5

        # Add complexity for component diversity
        component_types = len(form_analysis["component_types"])
        if component_types > 5:
            base_score += component_types * 0.2

        return base_score

    def _identify_migration_issues(
        self, form_analysis: Dict[str, Any], project_context: ProjectContext
    ) -> List[str]:
        """Identify potential migration issues."""
        issues = []

        # Check for unknown components
        for comp_type in form_analysis["component_types"]:
            if comp_type not in self._component_migration_rules:
                issues.append(f"Unknown component type: {comp_type}")

        # Check for complex event handling
        for component in form_analysis["components"]:
            event_count = len(component["event_handlers"])
            if event_count > 3:
                issues.append(f"Complex event handling in {component['name']}")

        # Check project compatibility
        if not project_context.has_reactive:
            issues.append("Project doesn't have reactive library installed")

        return issues

    def _recommend_migration_strategy(
        self,
        form_analysis: Dict[str, Any],
        project_context: ProjectContext,
        complexity_score: float,
    ) -> MigrationStrategy:
        """Recommend optimal migration strategy."""
        if project_context.has_reactive:
            return MigrationStrategy.ENHANCE_GRADUALLY
        elif complexity_score > 10:
            return MigrationStrategy.PRESERVE_EXISTING
        elif complexity_score > 5:
            return MigrationStrategy.HYBRID_APPROACH
        else:
            return MigrationStrategy.FULL_REACTIVE

    def _estimate_migration_effort(
        self, form_analysis: Dict[str, Any], complexity_score: float
    ) -> str:
        """Estimate migration effort."""
        base_hours = complexity_score * 2  # 2 hours per complexity point

        if base_hours <= 4:
            return f"{base_hours} hours"
        elif base_hours <= 24:
            return f"{base_hours / 8:.1f} days"
        else:
            return f"{base_hours / 8:.1f} days"

    def _identify_migration_benefits(self, form_analysis: Dict[str, Any]) -> List[str]:
        """Identify benefits of migrating to reactive patterns."""
        benefits = [
            "Automatic UI updates when data changes",
            "Simplified state management",
            "Better separation of concerns",
            "Improved testability",
        ]

        # Add specific benefits based on components
        if form_analysis["has_data_bindings"]:
            benefits.append("Elimination of manual data binding code")

        if form_analysis["has_event_handlers"]:
            benefits.append("Enhanced event handling with reactive patterns")

        return benefits

    def _identify_migration_prerequisites(
        self, form_analysis: Dict[str, Any], project_context: ProjectContext
    ) -> List[str]:
        """Identify prerequisites for migration."""
        prerequisites = [
            "Backup original form files",
            "Install reactive library if not present",
            "Test current form functionality",
        ]

        if not project_context.has_reactive:
            prerequisites.append("Add anvil-extras.reactive dependency")

        return prerequisites

    def _score_to_complexity_level(self, score: float) -> str:
        """Convert complexity score to level."""
        if score <= 3:
            return "low"
        elif score <= 7:
            return "medium"
        elif score <= 12:
            return "high"
        else:
            return "very_high"

    def _identify_component_challenges(
        self, components: List[Dict[str, Any]]
    ) -> List[str]:
        """Identify challenges in migrating components."""
        challenges = []

        for component in components:
            component_type = component["type"]

            # Check for custom components
            if component_type.startswith("form:"):
                challenges.append(f"Custom component: {component_type}")

            # Check for complex property configurations
            properties = component.get("properties", {})
            if len(properties) > 10:
                challenges.append(f"Complex properties in {component['name']}")

            # Check for nested event handlers
            event_handlers = component.get("event_handlers", {})
            if len(event_handlers) > 5:
                challenges.append(f"Complex event handling in {component['name']}")

        return challenges

    def _plan_enhancement(
        self,
        enhancement: str,
        form_analysis: Dict[str, Any],
        project_context: ProjectContext,
    ) -> List[Dict[str, Any]]:
        """Plan specific enhancement for form."""
        steps = []

        if enhancement == "reactive_bindings":
            steps = self._plan_reactive_bindings_enhancement(form_analysis)
        elif enhancement == "validation":
            steps = self._plan_validation_enhancement(form_analysis)
        elif enhancement == "conditional_display":
            steps = self._plan_conditional_display_enhancement(form_analysis)
        elif enhancement == "state_management":
            steps = self._plan_state_management_enhancement(form_analysis)

        return steps

    def _plan_reactive_bindings_enhancement(
        self, form_analysis: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Plan reactive bindings enhancement."""
        steps = []

        for component in form_analysis["components"]:
            if component["reactive_potential"] in ["high", "medium"]:
                step = {
                    "type": "add_reactive_binding",
                    "component": component["name"],
                    "description": f"Add reactive bindings to {component['name']}",
                    "complexity": "low",
                }
                steps.append(step)

        return steps

    def _plan_validation_enhancement(
        self, form_analysis: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Plan validation enhancement."""
        return [
            {
                "type": "add_form_validation",
                "description": "Add form-level validation",
                "complexity": "medium",
            },
            {
                "type": "add_input_validation",
                "description": "Add input field validation",
                "complexity": "medium",
            },
        ]

    def _plan_conditional_display_enhancement(
        self, form_analysis: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Plan conditional display enhancement."""
        steps = []

        for component in form_analysis["components"]:
            if component["type"] in ["ColumnPanel", "FlowPanel"]:
                step = {
                    "type": "add_conditional_visibility",
                    "component": component["name"],
                    "description": f"Add conditional visibility to {component['name']}",
                    "complexity": "medium",
                }
                steps.append(step)

        return steps

    def _plan_state_management_enhancement(
        self, form_analysis: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Plan state management enhancement."""
        return [
            {
                "type": "add_form_state",
                "description": "Add form-level state management",
                "complexity": "high",
            },
            {
                "type": "add_reactive_signals",
                "description": "Add reactive signals for form data",
                "complexity": "medium",
            },
        ]

    def _calculate_enhancement_effort(
        self, enhancement_steps: List[Dict[str, Any]]
    ) -> str:
        """Calculate total effort for enhancements."""
        complexity_hours = {
            "low": 2,
            "medium": 4,
            "high": 8,
        }

        total_hours = sum(
            complexity_hours.get(step.get("complexity", "medium"), 4)
            for step in enhancement_steps
        )

        if total_hours <= 8:
            return f"{total_hours} hours"
        elif total_hours <= 40:
            return f"{total_hours / 8:.1f} days"
        else:
            return f"{total_hours / 8:.1f} days"

    def _identify_enhancement_breaking_changes(
        self, enhancement_steps: List[Dict[str, Any]]
    ) -> List[str]:
        """Identify breaking changes in enhancements."""
        breaking_changes = []

        for step in enhancement_steps:
            if step.get("complexity") == "high":
                breaking_changes.append(
                    f"High complexity enhancement: {step['description']}"
                )

        return breaking_changes

    def _identify_breaking_changes(
        self,
        migration_plan: Dict[str, Any],
        strategy: MigrationStrategy,
        project_context: ProjectContext,
    ) -> List[str]:
        """Identify breaking changes in migration plan."""
        breaking_changes = []

        if strategy == MigrationStrategy.FULL_REACTIVE:
            breaking_changes.append(
                "Full reactive conversion may change component behavior"
            )
            breaking_changes.append("Event handlers will be modified")

        if migration_plan["reactive_bindings_to_add"]:
            breaking_changes.append("New reactive bindings will change data flow")

        return breaking_changes

    def _identify_enhancements(
        self, migration_plan: Dict[str, Any], strategy: MigrationStrategy
    ) -> List[str]:
        """Identify enhancements in migration plan."""
        enhancements = []

        if migration_plan["reactive_bindings_to_add"]:
            enhancements.append("Added reactive data bindings")

        if migration_plan["validation_to_add"]:
            enhancements.append("Added form validation")

        if strategy == MigrationStrategy.FULL_REACTIVE:
            enhancements.append("Converted to fully reactive form")

        return enhancements

    def _plan_validation_additions(
        self, form_analysis: Dict[str, Any], strategy: MigrationStrategy
    ) -> List[Dict[str, Any]]:
        """Plan validation additions for form."""
        validation_plan = []

        # Add input validation
        for component in form_analysis["components"]:
            if component["type"] in ["TextBox", "DropDown", "CheckBox"]:
                validation = {
                    "type": "input_validation",
                    "component": component["name"],
                    "rules": ["required", "type_check"],
                }
                validation_plan.append(validation)

        # Add form-level validation
        if strategy == MigrationStrategy.FULL_REACTIVE:
            form_validation = {
                "type": "form_validation",
                "rules": ["overall_validity", "error_display"],
            }
            validation_plan.append(form_validation)

        return validation_plan
