import os
import re
from project_generator.domain.models.project_models import ProjectInventory

class ProjectAnalyzerAdapter:
    """Analyzes the file system to build an inventory of an MCP project."""

    def analyze(self, path: str) -> ProjectInventory:
        root_path = os.path.abspath(path)
        is_valid = os.path.exists(os.path.join(root_path, "pyproject.toml")) and \
                   os.path.exists(os.path.join(root_path, "src"))

        inventory = ProjectInventory(
            is_valid=is_valid,
            project_path=root_path,
            existing_resource_uris=[]
        )

        if not is_valid:
            return inventory

        tool_pattern = r'@mcp\.tool\(\)\s*async\s*def\s*(\w+)'
        prompt_pattern = r'@mcp\.prompt\("([^"]+)"\)'
        resource_pattern = r'@mcp\.resource\("([^"]+)"\)\s*async\s*def\s*(\w+)'

        inventory.existing_tools = self._find_components(os.path.join(root_path, "src/infrastructure/entry_points/mcp/tools.py"), tool_pattern, group_index=1)
        inventory.existing_prompts = self._find_components(os.path.join(root_path, "src/infrastructure/entry_points/mcp/prompts.py"), prompt_pattern, group_index=1)

        resource_matches = self._find_components_multiple_groups(os.path.join(root_path, "src/infrastructure/entry_points/mcp/resources.py"), resource_pattern)
        inventory.existing_resources = [match[1] for match in resource_matches]
        inventory.existing_resource_uris = [match[0] for match in resource_matches]

        return inventory

    def _find_components(self, file_path: str, pattern: str, group_index: int = 1) -> list[str]:
        """Encuentra componentes usando regex y devuelve un grupo específico."""
        if not os.path.exists(file_path):
            return []
        try:
            with open(file_path, 'r') as f:
                content = f.read()
            matches = re.findall(pattern, content)
            return [match[group_index - 1] if isinstance(match, tuple) else match for match in matches]
        except IOError:
            return []

    def _find_components_multiple_groups(self, file_path: str, pattern: str) -> list[tuple]:
        """Encuentra componentes usando regex y devuelve todos los grupos capturados."""
        if not os.path.exists(file_path):
            return []
        try:
            with open(file_path, 'r') as f:
                content = f.read()
            return re.findall(pattern, content)
        except IOError:
            return []