"""Component management tools for MCP."""

from __future__ import annotations

from typing import Any

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


def register_component_management_tools(mcp, container: DIContainer) -> None:
    """Register component management tools with MCP server."""
    component_manager = ComponentManager(container.get(FileSystem))
    dependency_analyzer = ComponentDependencyAnalyzer()

    @mcp.tool()
    def add_component_to_form(
        form_path: str,
        component_type: str,
        position: str,
        properties: dict[str, Any],
        layout_properties: dict[str, Any] | None = None,
        event_bindings: dict[str, str] | None = None,
        data_bindings: list[dict[str, Any]] | None = None,
    ) -> dict[str, Any]:
        """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__,
            }

    @mcp.tool()
    def update_component_properties(
        form_path: str,
        component_name: str,
        properties: dict[str, Any],
    ) -> dict[str, Any]:
        """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__,
            }

    @mcp.tool()
    def remove_component_from_form(
        form_path: str,
        component_name: str,
    ) -> dict[str, Any]:
        """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__,
            }

    @mcp.tool()
    def move_component(
        form_path: str,
        component_name: str,
        new_position: str,
    ) -> dict[str, Any]:
        """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__,
            }

    @mcp.tool()
    def list_form_components(
        form_path: str,
        component_type_filter: str | None = None,
    ) -> dict[str, Any]:
        """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__,
            }

    @mcp.tool()
    def analyze_component_dependencies(
        form_path: str,
    ) -> dict[str, Any]:
        """Analyze dependencies between components in a form."""
        try:
            import yaml

            with open(form_path, "r") as f:
                form_config = yaml.safe_load(f)

            inventory = dependency_analyzer.analyze_form_dependencies(
                form_config, form_path
            )

            return {
                "success": True,
                "form_path": form_path,
                "total_components": len(inventory.components),
                "total_dependencies": len(inventory.dependencies),
                "components": inventory.components,
                "dependencies": [
                    {
                        "source": dep.source_component,
                        "target": dep.target_component,
                        "type": dep.dependency_type,
                        "description": dep.description,
                        "strength": dep.strength,
                    }
                    for dep in inventory.dependencies
                ],
                "statistics": inventory.statistics,
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "error_type": type(e).__name__,
            }

    @mcp.tool()
    def get_component_impact_analysis(
        form_path: str,
        component_name: str,
    ) -> dict[str, Any]:
        """Analyze impact of removing or modifying a component."""
        try:
            import yaml

            with open(form_path, "r") as f:
                form_config = yaml.safe_load(f)

            impact = dependency_analyzer.analyze_dependency_impact(
                form_config, component_name
            )

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