"""Tool registry for Hephaestus MCP server."""

from __future__ import annotations

from typing import Callable

from ..dependencies.container import DIContainer, FileSystem
from ..generators.component_manager import ComponentManager
from ..analyzers.component_dependency_analyzer import ComponentDependencyAnalyzer


class ToolRegistry:
    """Registry for MCP tools with validation and metadata."""

    def __init__(self, container: DIContainer):
        self.container = container
        self._tools: dict[str, dict] = {}
        self._tool_functions: dict[str, Callable] = {}

    def register_tool(
        self,
        name: str,
        func: Callable,
        description: str,
        parameters: dict | None = None,
        tags: set[str] | None = None,
    ) -> None:
        """Register a tool with the registry."""
        if name in self._tools:
            raise ValueError(f"Tool {name} is already registered")

        self._tools[name] = {
            "name": name,
            "description": description,
            "parameters": parameters or {},
            "tags": tags or set(),
            "function": func,
        }
        self._tool_functions[name] = func

    def get_tool(self, name: str) -> dict | None:
        """Get tool metadata by name."""
        return self._tools.get(name)

    def get_tool_function(self, name: str) -> Callable | None:
        """Get tool function by name."""
        return self._tool_functions.get(name)

    def list_tools(self) -> list[dict]:
        """List all registered tools."""
        return list(self._tools.values())

    def get_tools_by_tag(self, tag: str) -> list[dict]:
        """Get all tools with a specific tag."""
        return [tool for tool in self._tools.values() if tag in tool["tags"]]

    def validate_tools(self) -> tuple[bool, list[str]]:
        """Validate all registered tools."""
        errors = []

        for name, tool in self._tools.items():
            if not tool["description"]:
                errors.append(f"Tool {name}: Description is required")

            if not callable(tool["function"]):
                errors.append(f"Tool {name}: Function is not callable")

            params = tool["parameters"]
            if params and not isinstance(params, dict):
                errors.append(f"Tool {name}: Parameters must be a dictionary")

        return len(errors) == 0, errors

    def register_anvil_tools(self, mcp) -> None:
        """Register all Anvil development tools with MCP server."""
        from ..analyzers.project_analyzer import ProjectAnalyzer
        from ..dependencies.container import FileSystem, ProjectManager
        from ..validators.project_validator import ProjectValidator
        from ..validators.pattern_validator import PatternValidator
        from ..analyzers.performance_analyzer import PerformanceAnalyzer
        from ..patterns.pattern_matcher import PatternMatcher
        from .component_tools import register_component_management_tools

        # Register component management tools
        register_component_management_tools(mcp, self.container)

        analyzer = ProjectAnalyzer(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )
        validator = ProjectValidator(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )
        pattern_validator = PatternValidator()
        performance_analyzer = PerformanceAnalyzer(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )
        pattern_matcher = PatternMatcher(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )

        @mcp.tool()
        def analyse_project_context(project_path: str) -> dict:
            """Analyze existing Anvil project to determine patterns and modernisation opportunities."""
            try:
                from pathlib import Path

                context = analyzer.analyze_project(Path(project_path))
                return {
                    "success": True,
                    "context": {
                        "theme_type": context.theme_type,
                        "routing_system": context.routing_system,
                        "has_reactive": context.has_reactive,
                        "data_layer": context.data_layer,
                        "layout_system": context.layout_system,
                        "modernisation_score": context.modernisation_score,
                        "generation_mode": context.generation_mode,
                        "performance_opportunities": context.performance_opportunities,
                        "breaking_change_risks": context.breaking_change_risks,
                    },
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "analyse_project_context",
            analyse_project_context,
            "Analyze Anvil project structure and patterns",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"analysis", "project", "context"},
        )

        @mcp.tool()
        def validate_project_structure(project_path: str) -> dict:
            """Validate Anvil project structure and requirements."""
            try:
                from pathlib import Path

                is_valid, errors = validator.validate_project_structure(
                    Path(project_path)
                )
                return {
                    "success": is_valid,
                    "errors": errors,
                    "error_count": len(errors),
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "validate_project_structure",
            validate_project_structure,
            "Validate Anvil project structure and requirements",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"validation", "project", "structure"},
        )

        @mcp.tool()
        def validate_patterns(project_path: str, patterns: list[str]) -> dict:
            """Validate detected patterns against known patterns."""
            try:
                from pathlib import Path

                context = analyzer.analyze_project(Path(project_path))
                is_valid, errors = pattern_validator.validate_detected_patterns(
                    context.detected_patterns, context
                )
                return {
                    "success": is_valid,
                    "errors": errors,
                    "valid_patterns": patterns,
                    "detected_patterns": context.detected_patterns,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "validate_patterns",
            validate_patterns,
            "Validate detected patterns against known patterns",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"validation", "patterns", "detected_patterns"},
        )

        @mcp.tool()
        def analyze_performance(project_path: str) -> dict:
            """Analyze project performance and identify optimization opportunities."""
            try:
                from pathlib import Path

                metrics = performance_analyzer.analyze_project_performance(
                    Path(project_path)
                )
                score = performance_analyzer.calculate_performance_score(metrics)
                return {
                    "success": True,
                    "metrics": metrics,
                    "performance_score": score,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "analyze_performance",
            analyze_performance,
            "Analyze project performance and identify optimization opportunities",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"analysis", "performance", "metrics"},
        )

        @mcp.tool()
        def match_patterns(project_path: str, patterns: list[str]) -> dict:
            """Match specific patterns in project files."""
            try:
                from pathlib import Path

                matches = pattern_matcher.match_patterns_in_project(
                    Path(project_path), patterns
                )
                return {
                    "success": True,
                    "matches": matches,
                    "match_count": len(matches),
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "match_patterns",
            match_patterns,
            "Match specific patterns in project files",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"pattern_matching", "patterns", "matches"},
        )

        # Compatibility Generator Tools
        from pathlib import Path
        from ..generators.capability_compatibility_generator import (
            CapabilityCompatibilityGenerator,
        )

        capability_generator = CapabilityCompatibilityGenerator(Path.cwd())

        @mcp.tool()
        def generate_capability_compatible_component(
            component_name: str,
            component_type: str,
            properties: dict,
            config: dict | None = None,
        ) -> dict:
            """Generate capability-compatible component with fallbacks."""
            try:
                result = capability_generator.generate_capability_compatible_component(
                    component_name, component_type, properties, config
                )
                return {
                    "success": True,
                    "component": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "generate_capability_compatible_component",
            generate_capability_compatible_component,
            "Generate capability-compatible component with fallbacks",
            {
                "component_name": {
                    "type": "string",
                    "description": "Name of component",
                },
                "component_type": {
                    "type": "string",
                    "description": "Type of component (form, custom_component, etc.)",
                },
                "properties": {
                    "type": "object",
                    "description": "Component properties and configuration",
                },
                "config": {
                    "type": "object",
                    "description": "Capability configuration (optional)",
                },
            },
            {"compatibility", "components", "phase4"},
        )

        @mcp.tool()
        def create_capability_upgrade_plan(
            current_capability: str,
            target_capability: str,
            components: list[str],
            config: dict | None = None,
        ) -> dict:
            """Create upgrade plan between capability levels."""
            try:
                result = capability_generator.create_capability_upgrade_plan(
                    current_capability, target_capability, components, config
                )
                return {
                    "success": True,
                    "plan": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        @mcp.tool()
        def generate_capability_fallback_component(
            component_name: str,
            component_type: str,
            properties: dict,
            unsupported_features: list[str],
            config: dict | None = None,
        ) -> dict:
            """Generate component with capability fallbacks."""
            try:
                result = capability_generator.generate_capability_fallback_component(
                    component_name,
                    component_type,
                    properties,
                    unsupported_features,
                    config,
                )
                return {
                    "success": True,
                    "component": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "create_capability_upgrade_plan",
            create_capability_upgrade_plan,
            "Create upgrade plan between capability levels",
            {
                "current_capability": {
                    "type": "string",
                    "description": "Current capability level",
                },
                "target_capability": {
                    "type": "string",
                    "description": "Target capability level",
                },
                "components": {
                    "type": "array",
                    "description": "List of components to upgrade",
                },
                "config": {
                    "type": "object",
                    "description": "Upgrade configuration (optional)",
                },
            },
            {"compatibility", "upgrade", "phase4"},
        )

        self.register_tool(
            "generate_capability_fallback_component",
            generate_capability_fallback_component,
            "Generate component with capability fallbacks",
            {
                "component_name": {
                    "type": "string",
                    "description": "Name of component",
                },
                "component_type": {
                    "type": "string",
                    "description": "Type of component",
                },
                "properties": {
                    "type": "object",
                    "description": "Component properties",
                },
                "unsupported_features": {
                    "type": "array",
                    "description": "List of features not supported in target capability level",
                },
                "config": {
                    "type": "object",
                    "description": "Capability configuration (optional)",
                },
            },
            {"compatibility", "fallback", "phase4"},
        )

        # Routing Migrator Tools
        from ..generators.routing_migrator import RoutingMigrator

        routing_migrator = RoutingMigrator(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )

        @mcp.tool()
        def migrate_routing_system(
            project_path: str,
            target_system: str = "official",
        ) -> dict:
            """Migrate routing system to modern official routing."""
            try:
                from pathlib import Path

                result = routing_migrator.migrate_routing_system(
                    Path(project_path), target_system
                )
                return {
                    "success": True,
                    "result": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "migrate_routing_system",
            migrate_routing_system,
            "Migrate routing system to modern official routing",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                },
                "target_system": {
                    "type": "string",
                    "description": "Target routing system (official, anvil-extras, or custom)",
                },
            },
            {"migration", "routing", "phase4"},
        )

        @mcp.tool()
        def analyze_routing_migration(
            project_path: str,
        ) -> dict:
            """Analyze routing migration requirements and complexity."""
            try:
                from pathlib import Path

                result = routing_migrator.analyze_routing_migration(Path(project_path))
                return {
                    "success": True,
                    "analysis": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "analyze_routing_migration",
            analyze_routing_migration,
            "Analyze routing migration requirements and complexity",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"migration", "routing", "phase4"},
        )

        @mcp.tool()
        def create_routing_migration_plan(
            project_path: str,
        ) -> dict:
            """Create detailed routing migration plan."""
            try:
                from pathlib import Path

                result = routing_migrator.create_routing_migration_plan(
                    Path(project_path)
                )
                return {
                    "success": True,
                    "plan": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "create_routing_migration_plan",
            create_routing_migration_plan,
            "Create detailed routing migration plan",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"migration", "routing", "phase4"},
        )

        # Layout Migrator Tools
        from ..generators.layout_migrator import LayoutMigrator

        layout_migrator = LayoutMigrator(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )

        @mcp.tool()
        def modernize_layout_architecture(
            project_path: str,
            target_forms: list[str] | None = None,
        ) -> dict:
            """Modernize layout architecture from panels to layouts."""
            try:
                from pathlib import Path

                result = layout_migrator.modernize_layout_architecture(
                    Path(project_path), target_forms
                )
                return {
                    "success": True,
                    "result": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "modernize_layout_architecture",
            modernize_layout_architecture,
            "Modernize layout architecture from panels to layouts",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                },
                "target_forms": {
                    "type": "array",
                    "description": "Specific forms to migrate (optional)",
                },
            },
            {"migration", "layouts", "phase4"},
        )

        @mcp.tool()
        def analyze_layout_migration_feasibility(
            project_path: str,
        ) -> dict:
            """Analyze feasibility of layout migration."""
            try:
                from pathlib import Path

                result = layout_migrator.analyze_layout_migration_feasibility(
                    Path(project_path)
                )
                return {
                    "success": True,
                    "analysis": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "analyze_layout_migration_feasibility",
            analyze_layout_migration_feasibility,
            "Analyze feasibility of layout migration",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                }
            },
            {"migration", "layouts", "phase4"},
        )

        @mcp.tool()
        def create_layout_migration_plan(
            project_path: str,
            strategy: str = "optimal",
        ) -> dict:
            """Create detailed layout migration plan."""
            try:
                from pathlib import Path

                result = layout_migrator.create_layout_migration_plan(
                    Path(project_path), strategy
                )
                return {
                    "success": True,
                    "plan": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "create_layout_migration_plan",
            create_layout_migration_plan,
            "Create detailed layout migration plan",
            {
                "project_path": {
                    "type": "string",
                    "description": "Path to Anvil project",
                },
                "strategy": {
                    "type": "string",
                    "description": "Migration strategy (optimal, targeted, or phased)",
                },
            },
            {"migration", "layouts", "phase4"},
        )

        # Hybrid Generator Tools
        from ..generators.hybrid_generator import (
            HybridGenerator,
            HybridGenerationConfig,
        )

        hybrid_generator = HybridGenerator(
            self.container.get(FileSystem), self.container.get(ProjectManager)
        )

        @mcp.tool()
        def generate_hybrid_component(
            component_name: str,
            component_type: str,
            properties: dict,
            config: dict | None = None,
        ) -> dict:
            """Generate component using hybrid approach based on project context."""
            try:
                result = hybrid_generator.generate_hybrid_component(
                    component_name, component_type, properties, config
                )
                return {
                    "success": True,
                    "component": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "generate_hybrid_component",
            generate_hybrid_component,
            "Generate component using hybrid approach based on project context",
            {
                "component_name": {
                    "type": "string",
                    "description": "Name of component",
                },
                "component_type": {
                    "type": "string",
                    "description": "Type of component (form, custom_component, etc.)",
                },
                "properties": {
                    "type": "object",
                    "description": "Component properties and configuration",
                },
                "config": {
                    "type": "object",
                    "description": "Hybrid generation configuration (optional)",
                },
            },
            {"hybrid", "generation", "phase4"},
        )

        @mcp.tool()
        def enhance_existing_form(
            form_path: str,
            enhancement_type: str = "adaptive",
            config: dict | None = None,
        ) -> dict:
            """Enhance an existing form with hybrid patterns."""
            try:
                result = hybrid_generator.enhance_existing_form(
                    form_path, enhancement_type, config
                )
                return {
                    "success": True,
                    "result": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "enhance_existing_form",
            enhance_existing_form,
            "Enhance an existing form with hybrid patterns",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to the existing form",
                },
                "enhancement_type": {
                    "type": "string",
                    "description": "Type of enhancement (adaptive, conservative, aggressive)",
                },
                "config": {
                    "type": "object",
                    "description": "Hybrid generation configuration (optional)",
                },
            },
            {"hybrid", "enhancement", "phase4"},
        )

        @mcp.tool()
        def create_migration_enhancement_plan(
            target_components: list[str],
            migration_goals: list[str],
            config: dict | None = None,
        ) -> dict:
            """Create a comprehensive enhancement plan for mixed architecture migration."""
            try:
                result = hybrid_generator.create_migration_enhancement_plan(
                    target_components, migration_goals, config
                )
                return {
                    "success": True,
                    "plan": result,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "create_migration_enhancement_plan",
            create_migration_enhancement_plan,
            "Create a comprehensive enhancement plan for mixed architecture migration",
            {
                "target_components": {
                    "type": "array",
                    "description": "List of components to enhance",
                },
                "migration_goals": {
                    "type": "array",
                    "description": "List of modernization goals",
                },
                "config": {
                    "type": "object",
                    "description": "Hybrid generation configuration (optional)",
                },
            },
            {"hybrid", "migration", "planning", "phase4"},
        )

    def _register_form_generation_tools(self, mcp) -> None:
        """Register form generation tools."""
        from ..generators.form_generator import FormGenerator
        from ..dependencies.container import FileSystem

        generator = FormGenerator(self.container.get(FileSystem))

        @mcp.tool()
        def create_anvil_form(form_config: dict, output_path: str) -> dict:
            """Generate Anvil form YAML from configuration."""
            try:
                success, message = generator.generate_form(form_config, output_path)
                return {
                    "success": success,
                    "message": message,
                    "output_path": output_path if success else None,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "create_anvil_form",
            create_anvil_form,
            "Generate Anvil form YAML from configuration",
            {
                "form_config": {"type": "object", "description": "Form configuration"},
                "output_path": {"type": "string", "description": "Output file path"},
            },
            {"generation", "forms", "yaml"},
        )

    def _register_modernisation_tools(self, mcp) -> None:
        """Register modernisation tools."""

        @mcp.tool()
        def suggest_modernisations(project_context: dict) -> dict:
            """Suggest modernisation improvements based on project context."""
            try:
                suggestions = []

                if project_context.get("data_layer") == "raw-tables":
                    suggestions.append(
                        {
                            "type": "data_layer",
                            "suggestion": "Migrate to model classes",
                            "benefit": "Type safety, validation, automatic serialisation",
                            "effort": "medium",
                        }
                    )

                if not project_context.get("has_reactive"):
                    suggestions.append(
                        {
                            "type": "reactive",
                            "suggestion": "Add reactive library",
                            "benefit": "Automatic UI updates, better state management",
                            "effort": "low",
                        }
                    )

                if project_context.get("theme_type") == "classic":
                    suggestions.append(
                        {
                            "type": "theme",
                            "suggestion": "Upgrade to Material 3",
                            "benefit": "Modern design, better UX, accessibility",
                            "effort": "medium",
                        }
                    )

                return {
                    "success": True,
                    "suggestions": suggestions,
                    "total_suggestions": len(suggestions),
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "suggest_modernisations",
            suggest_modernisations,
            "Suggest modernisation improvements based on project analysis",
            {
                "project_context": {
                    "type": "object",
                    "description": "Project context from analysis",
                }
            },
            {"modernisation", "suggestions", "improvements"},
        )

        # Component Management Tools
        component_manager = ComponentManager(self.container.get(FileSystem))
        dependency_analyzer = ComponentDependencyAnalyzer()

        @mcp.tool()
        def add_component_to_form(
            form_path: str,
            component_type: str,
            position: str,
            properties: dict,
            layout_properties: dict | None = None,
            event_bindings: dict | None = None,
            data_bindings: list | None = None,
        ) -> dict:
            """Add a component to an existing form with intelligent positioning."""
            try:
                success, message = component_manager.add_component_to_form(
                    form_path=form_path,
                    component_type=component_type,
                    position=position,
                    properties=properties,
                    layout_properties=layout_properties,
                    event_bindings=event_bindings,
                    data_bindings=data_bindings,
                )
                return {
                    "success": success,
                    "message": message,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "add_component_to_form",
            add_component_to_form,
            "Add a component to an existing form with intelligent positioning",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to form YAML file",
                },
                "component_type": {
                    "type": "string",
                    "description": "Anvil component type",
                },
                "position": {
                    "type": "string",
                    "description": "Grid position or layout coordinates",
                },
                "properties": {"type": "object", "description": "Component properties"},
                "layout_properties": {
                    "type": "object",
                    "description": "Layout properties",
                },
                "event_bindings": {
                    "type": "object",
                    "description": "Event handler mappings",
                },
                "data_bindings": {
                    "type": "array",
                    "description": "Reactive data bindings",
                },
            },
            {"components", "forms", "add"},
        )

        @mcp.tool()
        def update_component_properties(
            form_path: str,
            component_name: str,
            properties: dict,
        ) -> dict:
            """Update properties of an existing component."""
            try:
                success, message = component_manager.update_component_properties(
                    form_path=form_path,
                    component_name=component_name,
                    properties=properties,
                )
                return {
                    "success": success,
                    "message": message,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "update_component_properties",
            update_component_properties,
            "Update properties of an existing component",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to form YAML file",
                },
                "component_name": {
                    "type": "string",
                    "description": "Name of component to update",
                },
                "properties": {
                    "type": "object",
                    "description": "New component properties",
                },
            },
            {"components", "forms", "update"},
        )

        @mcp.tool()
        def remove_component_from_form(
            form_path: str,
            component_name: str,
        ) -> dict:
            """Remove a component from a form with cleanup."""
            try:
                success, message = component_manager.remove_component_from_form(
                    form_path=form_path,
                    component_name=component_name,
                )
                return {
                    "success": success,
                    "message": message,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "remove_component_from_form",
            remove_component_from_form,
            "Remove a component from a form with cleanup",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to form YAML file",
                },
                "component_name": {
                    "type": "string",
                    "description": "Name of component to remove",
                },
            },
            {"components", "forms", "remove"},
        )

        @mcp.tool()
        def move_component(
            form_path: str,
            component_name: str,
            new_position: str,
        ) -> dict:
            """Move a component to a new position within form."""
            try:
                success, message = component_manager.move_component(
                    form_path=form_path,
                    component_name=component_name,
                    new_position=new_position,
                )
                return {
                    "success": success,
                    "message": message,
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "move_component",
            move_component,
            "Move a component to a new position within form",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to form YAML file",
                },
                "component_name": {
                    "type": "string",
                    "description": "Name of component to move",
                },
                "new_position": {"type": "string", "description": "New grid position"},
            },
            {"components", "forms", "move"},
        )

        @mcp.tool()
        def list_form_components(
            form_path: str,
            component_type_filter: str | None = None,
        ) -> dict:
            """List components in a form with optional filtering."""
            try:
                success, message, components = component_manager.list_form_components(
                    form_path=form_path,
                    component_type_filter=component_type_filter,
                )
                return {
                    "success": success,
                    "message": message,
                    "components": components,
                    "component_count": len(components),
                }
            except Exception as e:
                return {
                    "success": False,
                    "error": str(e),
                    "error_type": type(e).__name__,
                }

        self.register_tool(
            "list_form_components",
            list_form_components,
            "List components in a form with optional filtering",
            {
                "form_path": {
                    "type": "string",
                    "description": "Path to form YAML file",
                },
                "component_type_filter": {
                    "type": "string",
                    "description": "Filter by component type",
                },
            },
            {"components", "forms", "list"},
        )

    # TODO: Add modern generation tools registration
    # - create_modern_anvil_app (ModernAppScaffolder)
    # - manage_anvil_dependencies (DependencyManager)
    # - create_reactive_page (ReactivePageGenerator)
    # - create_material_3_navigation (NavigationGenerator)
