"""
Base IDE Integration Types and Manager

Provides common types and a unified manager for IDE integrations.
"""

import logging
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Optional

logger = logging.getLogger(__name__)


class IDEType(Enum):
    """Supported IDE types"""

    VSCODE = "vscode"
    JETBRAINS = "jetbrains"
    VIM = "vim"
    NEOVIM = "neovim"
    EMACS = "emacs"
    SUBLIME = "sublime"
    ATOM = "atom"
    ZED = "zed"


@dataclass
class IDEConfig:
    """
    Base configuration for IDE integration

    Attributes:
        ide_type: Type of IDE
        project_root: Root directory of the project
        groknroll_path: Path to groknroll executable
        settings: IDE-specific settings
    """

    ide_type: IDEType
    project_root: Path
    groknroll_path: Optional[str] = None
    settings: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self):
        """Resolve paths after initialization"""
        if isinstance(self.project_root, str):
            self.project_root = Path(self.project_root)
        self.project_root = self.project_root.resolve()


@dataclass
class IntegrationResult:
    """
    Result of an IDE integration operation

    Attributes:
        success: Whether the operation succeeded
        ide_type: Type of IDE that was integrated
        files_created: List of files created
        files_modified: List of files modified
        message: Status message
        error: Error message if failed
    """

    success: bool
    ide_type: IDEType
    files_created: list[Path] = field(default_factory=list)
    files_modified: list[Path] = field(default_factory=list)
    message: str = ""
    error: Optional[str] = None


class IntegrationManager:
    """
    Manager for IDE integrations

    Provides a unified interface for setting up IDE integrations
    across multiple editors.

    Example:
        manager = IntegrationManager(project_root=Path("/project"))

        # Setup VS Code
        result = manager.setup(IDEType.VSCODE)

        # Setup Neovim
        result = manager.setup(IDEType.NEOVIM)

        # List supported IDEs
        ides = manager.get_supported_ides()
    """

    def __init__(
        self,
        project_root: Optional[Path] = None,
        groknroll_path: Optional[str] = None,
    ):
        """
        Initialize IntegrationManager

        Args:
            project_root: Root directory of the project
            groknroll_path: Path to groknroll executable
        """
        self.project_root = (project_root or Path.cwd()).resolve()
        self.groknroll_path = groknroll_path or "groknroll"

    def setup(
        self,
        ide_type: IDEType,
        config: Optional[IDEConfig] = None,
        **kwargs,
    ) -> IntegrationResult:
        """
        Setup integration for an IDE

        Args:
            ide_type: Type of IDE to integrate
            config: Optional custom configuration
            **kwargs: Additional arguments passed to setup function

        Returns:
            IntegrationResult with status
        """
        from groknroll.ide.jetbrains import setup_jetbrains_integration
        from groknroll.ide.vim import setup_neovim_integration, setup_vim_integration
        from groknroll.ide.vscode import setup_vscode_integration

        if config is None:
            config = IDEConfig(
                ide_type=ide_type,
                project_root=self.project_root,
                groknroll_path=self.groknroll_path,
            )

        try:
            if ide_type == IDEType.VSCODE:
                return setup_vscode_integration(config, **kwargs)
            elif ide_type == IDEType.JETBRAINS:
                return setup_jetbrains_integration(config, **kwargs)
            elif ide_type == IDEType.VIM:
                return setup_vim_integration(config, **kwargs)
            elif ide_type == IDEType.NEOVIM:
                return setup_neovim_integration(config, **kwargs)
            else:
                return IntegrationResult(
                    success=False,
                    ide_type=ide_type,
                    error=f"Unsupported IDE type: {ide_type}",
                )
        except Exception as e:
            logger.error(f"Failed to setup {ide_type.value} integration: {e}")
            return IntegrationResult(
                success=False,
                ide_type=ide_type,
                error=str(e),
            )

    def detect_ide(self) -> list[IDEType]:
        """
        Detect which IDEs are configured in the project

        Returns:
            List of detected IDE types
        """
        detected = []

        # VS Code
        vscode_dir = self.project_root / ".vscode"
        if vscode_dir.exists():
            detected.append(IDEType.VSCODE)

        # JetBrains
        idea_dir = self.project_root / ".idea"
        if idea_dir.exists():
            detected.append(IDEType.JETBRAINS)

        # Vim/Neovim (check for local config)
        if (self.project_root / ".vim").exists():
            detected.append(IDEType.VIM)
        if (self.project_root / ".nvim").exists():
            detected.append(IDEType.NEOVIM)

        return detected

    def get_supported_ides(self) -> list[IDEType]:
        """
        Get list of supported IDEs

        Returns:
            List of supported IDE types
        """
        return [IDEType.VSCODE, IDEType.JETBRAINS, IDEType.VIM, IDEType.NEOVIM]

    def is_integrated(self, ide_type: IDEType) -> bool:
        """
        Check if an IDE is already integrated

        Args:
            ide_type: Type of IDE to check

        Returns:
            True if groknroll is configured for the IDE
        """
        if ide_type == IDEType.VSCODE:
            settings_file = self.project_root / ".vscode" / "settings.json"
            if settings_file.exists():
                content = settings_file.read_text()
                return "groknroll" in content.lower()
        elif ide_type == IDEType.JETBRAINS:
            idea_dir = self.project_root / ".idea"
            if idea_dir.exists():
                for xml_file in idea_dir.glob("*.xml"):
                    content = xml_file.read_text()
                    if "groknroll" in content.lower():
                        return True
        elif ide_type == IDEType.VIM:
            vimrc = Path.home() / ".vimrc"
            if vimrc.exists():
                content = vimrc.read_text()
                return "groknroll" in content.lower()
        elif ide_type == IDEType.NEOVIM:
            nvim_init = Path.home() / ".config" / "nvim" / "init.lua"
            if nvim_init.exists():
                content = nvim_init.read_text()
                return "groknroll" in content.lower()

        return False

    def remove(self, ide_type: IDEType) -> IntegrationResult:
        """
        Remove integration for an IDE

        Args:
            ide_type: Type of IDE to remove integration for

        Returns:
            IntegrationResult with status
        """
        # Implementation would remove groknroll-specific configurations
        # This is a placeholder for the actual removal logic
        return IntegrationResult(
            success=True,
            ide_type=ide_type,
            message=f"Removed {ide_type.value} integration",
        )
